Files
HellreigN/backend/internal/ansible/inventory.go
T
d3m0k1d b516a54c17
ci-agent / build (push) Failing after 2m42s
fixsess and logic for web ide
2026-04-04 23:56:28 +03:00

65 lines
1.6 KiB
Go

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 .Hosts }}
{{ .Name }} ansible_host={{ .IP }} ansible_port={{ .Port }} ansible_user={{ .User }} ansible_connection=ssh
{{ if eq .AuthMethod "key" }}ansible_ssh_private_key_file={{ .SSHKey }}{{ end }}
{{ if eq .AuthMethod "password" }}ansible_ssh_pass={{ .Password }}{{ end }}
deploy_type={{ .DeployType }}
agent_token={{ .Token }}
agent_label={{ .Name }}
grpc_url={{ .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
}