| 1 | |
| 2 | |
| 3 | |
| 4 | package instance |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | |
| 13 | "github.com/goccy/go-yaml" |
| 14 | "github.com/sirupsen/logrus" |
| 15 | |
| 16 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 17 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 18 | ) |
| 19 | |
| 20 | func runAnsibleProvision(ctx context.Context, inst *limatype.Instance) error { |
| 21 | for _, f := range inst.Config.Provision { |
| 22 | if f.Mode == limatype.ProvisionModeAnsible { |
| 23 | logrus.Infof("Waiting for ansible playbook %#q", f.Playbook) |
| 24 | if err := runAnsiblePlaybook(ctx, inst, f.Playbook); err != nil { |
| 25 | return err |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | return nil |
| 30 | } |
| 31 | |
| 32 | func runAnsiblePlaybook(ctx context.Context, inst *limatype.Instance, playbook string) error { |
| 33 | inventory, err := createAnsibleInventory(inst) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | logrus.Debugf("ansible-playbook -i %#q %#q", inventory, playbook) |
| 38 | args := []string{"-i", inventory, playbook} |
| 39 | cmd := exec.CommandContext(ctx, "ansible-playbook", args...) |
| 40 | cmd.Env = getAnsibleEnvironment(inst) |
| 41 | cmd.Stdout = os.Stdout |
| 42 | cmd.Stderr = os.Stderr |
| 43 | return cmd.Run() |
| 44 | } |
| 45 | |
| 46 | func createAnsibleInventory(inst *limatype.Instance) (string, error) { |
| 47 | vars := map[string]any{ |
| 48 | "ansible_connection": "ssh", |
| 49 | "ansible_host": inst.Hostname, |
| 50 | "ansible_ssh_common_args": "-F " + inst.SSHConfigFile, |
| 51 | } |
| 52 | hosts := map[string]any{ |
| 53 | inst.Name: vars, |
| 54 | } |
| 55 | group := "lima" |
| 56 | data := map[string]any{ |
| 57 | group: map[string]any{ |
| 58 | "hosts": hosts, |
| 59 | }, |
| 60 | } |
| 61 | bytes, err := yaml.Marshal(data) |
| 62 | if err != nil { |
| 63 | return "", err |
| 64 | } |
| 65 | inventory := filepath.Join(inst.Dir, filenames.AnsibleInventoryYAML) |
| 66 | return inventory, os.WriteFile(inventory, bytes, 0o644) |
| 67 | } |
| 68 | |
| 69 | func getAnsibleEnvironment(inst *limatype.Instance) []string { |
| 70 | env := os.Environ() |
| 71 | for key, val := range inst.Config.Param { |
| 72 | env = append(env, fmt.Sprintf("PARAM_%s=%s", key, val)) |
| 73 | } |
| 74 | return env |
| 75 | } |