# ansible-go **Repository Path**: doove/ansible-go ## Basic Information - **Project Name**: ansible-go - **Description**: ansible-go - **Primary Language**: Go - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-01-12 - **Last Updated**: 2025-07-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Ansible-Go 一个现代化的 Go 语言 Ansible 包装器,提供类型安全的 Ansible 命令执行接口。 ## 特性 - 🚀 **现代化架构**: 基于 Go 1.24,使用最新的语言特性 - 📦 **丰富的模块支持**: 支持 20+ 个常用 Ansible 模块 - 🔧 **灵活的配置**: 链式调用的配置管理系统 - 📊 **结果解析**: 支持 JSON 和文本格式的结果解析 - 🐳 **Docker 友好**: 专门为 Docker 容器设计的 inventory 构建器 - 📝 **结构化日志**: 使用 slog 的现代日志记录 - 🛡️ **类型安全**: 强类型的错误处理和结果解析 - 🧪 **高测试覆盖率**: 51.4% 的测试覆盖率 ## 安装 ```bash go get gitee.com/doove/ansible-go ``` ## 快速开始 ### 基础用法 ```go package main import ( "context" "fmt" "log" "gitee.com/doove/ansible-go" ) func main() { // 创建简单的 inventory inventory := "localhost," // 创建 Ansible 实例 ans := ansible.NewAnsible("ansible", inventory, []string{"localhost"}, context.Background()) // 执行 ping 模块 stdout, stderr, err := ans.Ping() if err != nil { log.Printf("执行失败: %v", err) return } fmt.Printf("输出: %s\n", string(stdout)) } ``` ### Docker 容器支持 ```go // 创建 Docker SSH 容器的 inventory inventory := ansible.NewDockerInventoryBuilder(). AddDockerSSHContainer("web-server", "root", "password", 2222). AddDockerSSHContainer("db-server", "postgres", "secret", 2223). SetDockerDefaults() tempFile, err := inventory.ToTempFile() if err != nil { log.Fatal(err) } ans := ansible.NewAnsible("ansible", tempFile, []string{"all"}, context.Background()) ``` ### 高级模块使用 ```go // 文件操作 ans.Copy("/etc/hosts", "/tmp/hosts_backup", ansible.ModuleOptions{ "backup": "yes", "owner": "root", "mode": "0644", }) // 服务管理 ans.Service("nginx", "started", ansible.ModuleOptions{ "enabled": "yes", }) // 包管理 ans.Package("vim", "present") ans.Yum("httpd", "latest") ans.Apt("nginx", "present") // 用户管理 ans.User("deploy", ansible.ModuleOptions{ "state": "present", "shell": "/bin/bash", "home": "/home/deploy", }) ``` ### Playbook 执行 ```go playbook := ansible.NewPlaybook("ansible-playbook", inventory, context.Background()) // 从文件执行 stdout, stderr, err := playbook. SetOutJson(). CloseWarnings(). SetTags("web"). RunWithFile("site.yml") // 从字节数组执行 playbookContent := []byte(` --- - hosts: all tasks: - name: Ensure nginx is installed package: name: nginx state: present `) stdout, stderr, err = playbook.RunWithBytes(playbookContent) ``` ### 结果解析 ```go // 解析执行结果 result, err := ans.RunWithModuleParsed("setup") if err != nil { log.Printf("执行失败: %v", err) return } fmt.Printf("主机: %s\n", result.Host) fmt.Printf("状态: %s\n", result.Status) fmt.Printf("是否成功: %v\n", result.IsSuccess()) // 获取系统信息 if osFamily, exists := result.GetFactString("ansible_os_family"); exists { fmt.Printf("操作系统: %s\n", osFamily) } ``` ### 配置管理 ```go config := ansible.DefaultConfig(). WithBinPath("/usr/local/bin/ansible"). WithTimeout(30 * time.Second). WithOutputFormat(ansible.OutputFormatJSON). WithPTY(true). WithForceColor(true). WithSuppressWarnings(true) ans := ansible.NewAnsible("", inventory, []string{"all"}, context.Background()) // 配置会自动应用 ``` ## 支持的模块 ### 核心模块 - `ping` - 连接测试 - `shell` - Shell 命令执行 - `command` - 命令执行 - `script` - 脚本执行 - `setup` - 系统信息收集 ### 文件操作 - `copy` - 文件复制 - `file` - 文件/目录管理 - `template` - 模板渲染 - `lineinfile` - 行编辑 - `replace` - 文本替换 - `fetch` - 文件获取 - `synchronize` - 文件同步 ### 系统管理 - `service` - 服务管理 - `user` - 用户管理 - `group` - 组管理 - `cron` - 定时任务 - `mount` - 挂载管理 ### 包管理 - `package` - 通用包管理 - `yum` - YUM 包管理 - `apt` - APT 包管理 ### 其他 - `git` - Git 仓库管理 - `uri` - HTTP 请求 - `wait_for` - 等待条件 - `debug` - 调试输出 - `fail` - 强制失败 - `assert` - 断言 - `include_vars` - 包含变量 - `set_fact` - 设置事实 ## 错误处理 ```go stdout, stderr, err := ans.Ping() if err != nil { // 检查是否是 Ansible 错误 if ansible.IsAnsibleError(err) { if ansibleErr, ok := ansible.GetAnsibleError(err); ok { fmt.Printf("操作: %s\n", ansibleErr.Op) fmt.Printf("命令: %s\n", ansibleErr.Command) fmt.Printf("标准输出: %s\n", string(ansibleErr.Stdout)) fmt.Printf("标准错误: %s\n", string(ansibleErr.Stderr)) } } } ``` ## 日志记录 ```go // 设置日志级别 logger := ansible.NewLogger(slog.LevelDebug) ansible.SetDefaultLogger(logger) // 或使用 JSON 格式 jsonLogger := ansible.NewJSONLogger(slog.LevelInfo) ansible.SetDefaultLogger(jsonLogger) ``` ## 测试 ```bash # 运行所有测试 go test -v # 运行特定测试 go test -v -run TestModules # 查看测试覆盖率 go test -cover # 生成详细的覆盖率报告 go test -coverprofile=coverage.out go tool cover -html=coverage.out ``` ## 贡献 欢迎提交 Issue 和 Pull Request! ## 许可证 MIT License ## 更新日志 详细的更新日志请查看 [RELEASES.md](RELEASES.md)。