|
| 1 | +package start |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + "path/filepath" |
| 8 | + |
| 9 | + "github.com/goccy/go-yaml" |
| 10 | + "github.com/lima-vm/lima/pkg/limayaml" |
| 11 | + "github.com/lima-vm/lima/pkg/store" |
| 12 | + "github.com/lima-vm/lima/pkg/store/filenames" |
| 13 | + "github.com/sirupsen/logrus" |
| 14 | +) |
| 15 | + |
| 16 | +func runAnsibleProvision(ctx context.Context, inst *store.Instance) error { |
| 17 | + y, err := inst.LoadYAML() |
| 18 | + if err != nil { |
| 19 | + return err |
| 20 | + } |
| 21 | + for _, f := range y.Provision { |
| 22 | + if f.Mode == limayaml.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 *store.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.Stdout = os.Stdout |
| 41 | + cmd.Stderr = os.Stderr |
| 42 | + return cmd.Run() |
| 43 | +} |
| 44 | + |
| 45 | +func createAnsibleInventory(inst *store.Instance) (string, error) { |
| 46 | + vars := map[string]interface{}{ |
| 47 | + "ansible_connection": "ssh", |
| 48 | + "ansible_host": "lima-" + inst.Name, |
| 49 | + "ansible_ssh_common_args": "-F " + inst.SSHConfigFile, |
| 50 | + } |
| 51 | + hosts := map[string]interface{}{ |
| 52 | + inst.Name: vars, |
| 53 | + } |
| 54 | + group := "lima" |
| 55 | + data := map[string]interface{}{ |
| 56 | + group: map[string]interface{}{ |
| 57 | + "hosts": hosts, |
| 58 | + }, |
| 59 | + } |
| 60 | + bytes, err := yaml.Marshal(data) |
| 61 | + if err != nil { |
| 62 | + return "", err |
| 63 | + } |
| 64 | + inventory := filepath.Join(inst.Dir, filenames.AnsibleInventoryYAML) |
| 65 | + return inventory, os.WriteFile(inventory, bytes, 0o644) |
| 66 | +} |
0 commit comments