package ansible import ( "fmt" "os" "path/filepath" "text/template" ) // InventoryHost represents a single host in the inventory type InventoryHost struct { Name string IP string Port int User string AuthMethod string SSHKey string Password string DeployType string Token string GRPCURL string } // Inventory represents an Ansible inventory file type Inventory struct { Hosts []InventoryHost } const inventoryTemplateText = `{{- range $i, $host := .Hosts }} {{ $host.Name }} ansible_host={{ $host.IP }} ansible_port={{ $host.Port }} ansible_user={{ $host.User }} ansible_connection=ssh{{ if eq $host.AuthMethod "key" }} ansible_ssh_private_key_file={{ $host.SSHKey }}{{ end }}{{ if eq $host.AuthMethod "password" }} ansible_ssh_pass={{ $host.Password }}{{ end }} deploy_type={{ $host.DeployType }} agent_token={{ $host.Token }} agent_label={{ $host.Name }} grpc_url={{ $host.GRPCURL }} {{ end -}}` // GenerateInventory generates an Ansible inventory file from the given hosts func GenerateInventory(hosts []InventoryHost, outputPath string) error { tmpl, err := template.New("inventory").Parse(inventoryTemplateText) if err != nil { return fmt.Errorf("failed to parse inventory template: %w", err) } // Ensure directory exists dir := filepath.Dir(outputPath) if err := os.MkdirAll(dir, 0755); err != nil { return fmt.Errorf("failed to create inventory directory: %w", err) } file, err := os.Create(outputPath) if err != nil { return fmt.Errorf("failed to create inventory file: %w", err) } defer file.Close() if err := tmpl.Execute(file, Inventory{Hosts: hosts}); err != nil { return fmt.Errorf("failed to execute inventory template: %w", err) } return nil }