是的,Ansible支持使用Go编写模块。可以通过以下步骤来创建一个Go模块:
example.go
,并添加以下代码:package main
import (
"encoding/json"
"fmt"
"os"
)
type MyModule struct {
Arg1 string `json:"arg1"`
Arg2 int `json:"arg2"`
}
type MyModuleResult struct {
Changed bool `json:"changed"`
Output string `json:"output"`
}
func (m *MyModule) Run() (MyModuleResult, error) {
result := MyModuleResult{
Changed: true,
Output: fmt.Sprintf("arg1: %s, arg2: %d", m.Arg1, m.Arg2),
}
return result, nil
}
func main() {
var module MyModule
if err := json.NewDecoder(os.Stdin).Decode(&module); err != nil {
fmt.Println(err)
os.Exit(1)
}
result, err := module.Run()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
json.NewEncoder(os.Stdout).Encode(result)
}
将上述代码保存为example.go
文件。
使用Go命令编译模块:go build example.go
。
在Ansible playbook中使用该模块,例如example.yml
:
---
- name: Run Go module
hosts: localhost
gather_facts: false
tasks:
- name: Run Go module
command: /path/to/example --arg1 "hello" --arg2 42
register: result
- name: Print result
debug:
var: result.stdout
ansible-playbook example.yml
。这样,Go编写的模块将被执行,并且可以在Ansible playbook的输出中查看结果。