github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/lxc/step_lxc_create.go (about) 1 package lxc 2 3 import ( 4 "bytes" 5 "fmt" 6 "github.com/hashicorp/packer/packer" 7 "github.com/mitchellh/multistep" 8 "log" 9 "os/exec" 10 "path/filepath" 11 "strings" 12 ) 13 14 type stepLxcCreate struct{} 15 16 func (s *stepLxcCreate) Run(state multistep.StateBag) multistep.StepAction { 17 config := state.Get("config").(*Config) 18 ui := state.Get("ui").(packer.Ui) 19 20 name := config.ContainerName 21 22 // TODO: read from env 23 lxc_dir := "/var/lib/lxc" 24 rootfs := filepath.Join(lxc_dir, name, "rootfs") 25 26 if config.PackerForce { 27 s.Cleanup(state) 28 } 29 30 commands := make([][]string, 3) 31 commands[0] = append(config.EnvVars, []string{"lxc-create", "-n", name, "-t", config.Name, "--"}...) 32 commands[0] = append(commands[0], config.Parameters...) 33 // prevent tmp from being cleaned on boot, we put provisioning scripts there 34 // todo: wait for init to finish before moving on to provisioning instead of this 35 commands[1] = []string{"touch", filepath.Join(rootfs, "tmp", ".tmpfs")} 36 commands[2] = []string{"lxc-start", "-d", "--name", name} 37 38 ui.Say("Creating container...") 39 for _, command := range commands { 40 log.Printf("Executing sudo command: %#v", command) 41 err := s.SudoCommand(command...) 42 if err != nil { 43 err := fmt.Errorf("Error creating container: %s", err) 44 state.Put("error", err) 45 ui.Error(err.Error()) 46 return multistep.ActionHalt 47 } 48 } 49 50 state.Put("mount_path", rootfs) 51 52 return multistep.ActionContinue 53 } 54 55 func (s *stepLxcCreate) Cleanup(state multistep.StateBag) { 56 config := state.Get("config").(*Config) 57 ui := state.Get("ui").(packer.Ui) 58 59 command := []string{ 60 "lxc-destroy", "-f", "-n", config.ContainerName, 61 } 62 63 ui.Say("Unregistering and deleting virtual machine...") 64 if err := s.SudoCommand(command...); err != nil { 65 ui.Error(fmt.Sprintf("Error deleting virtual machine: %s", err)) 66 } 67 } 68 69 func (s *stepLxcCreate) SudoCommand(args ...string) error { 70 var stdout, stderr bytes.Buffer 71 72 log.Printf("Executing sudo command: %#v", args) 73 cmd := exec.Command("sudo", args...) 74 cmd.Stdout = &stdout 75 cmd.Stderr = &stderr 76 err := cmd.Run() 77 78 stdoutString := strings.TrimSpace(stdout.String()) 79 stderrString := strings.TrimSpace(stderr.String()) 80 81 if _, ok := err.(*exec.ExitError); ok { 82 err = fmt.Errorf("Sudo command error: %s", stderrString) 83 } 84 85 log.Printf("stdout: %s", stdoutString) 86 log.Printf("stderr: %s", stderrString) 87 88 return err 89 }