github.phpd.cn/hashicorp/packer@v1.3.2/builder/lxc/step_lxc_create.go (about)

     1  package lxc
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"os/user"
     8  	"path/filepath"
     9  
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	"github.com/hashicorp/packer/packer"
    12  )
    13  
    14  type stepLxcCreate struct{}
    15  
    16  func (s *stepLxcCreate) Run(_ context.Context, 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  	user, err := user.Current()
    25  	if err != nil {
    26  		log.Print("Cannot find current user. Falling back to /var/lib/lxc...")
    27  	}
    28  	if user.Uid != "0" && user.HomeDir != "" {
    29  		lxc_dir = filepath.Join(user.HomeDir, ".local", "share", "lxc")
    30  	}
    31  	rootfs := filepath.Join(lxc_dir, name, "rootfs")
    32  
    33  	if config.PackerForce {
    34  		s.Cleanup(state)
    35  	}
    36  
    37  	commands := make([][]string, 3)
    38  	commands[0] = append(commands[0], "env")
    39  	commands[0] = append(commands[0], config.EnvVars...)
    40  	commands[0] = append(commands[0], "lxc-create")
    41  	commands[0] = append(commands[0], config.CreateOptions...)
    42  	commands[0] = append(commands[0], []string{"-n", name, "-t", config.Name, "--"}...)
    43  	commands[0] = append(commands[0], config.Parameters...)
    44  	// prevent tmp from being cleaned on boot, we put provisioning scripts there
    45  	// todo: wait for init to finish before moving on to provisioning instead of this
    46  	commands[1] = []string{"touch", filepath.Join(rootfs, "tmp", ".tmpfs")}
    47  	commands[2] = append([]string{"lxc-start"}, config.StartOptions...)
    48  	commands[2] = append(commands[2], []string{"-d", "--name", name}...)
    49  
    50  	ui.Say("Creating container...")
    51  	for _, command := range commands {
    52  		err := RunCommand(command...)
    53  		if err != nil {
    54  			err := fmt.Errorf("Error creating container: %s", err)
    55  			state.Put("error", err)
    56  			ui.Error(err.Error())
    57  			return multistep.ActionHalt
    58  		}
    59  	}
    60  
    61  	state.Put("mount_path", rootfs)
    62  
    63  	return multistep.ActionContinue
    64  }
    65  
    66  func (s *stepLxcCreate) Cleanup(state multistep.StateBag) {
    67  	config := state.Get("config").(*Config)
    68  	ui := state.Get("ui").(packer.Ui)
    69  
    70  	command := []string{
    71  		"lxc-destroy", "-f", "-n", config.ContainerName,
    72  	}
    73  
    74  	ui.Say("Unregistering and deleting virtual machine...")
    75  	if err := RunCommand(command...); err != nil {
    76  		ui.Error(fmt.Sprintf("Error deleting virtual machine: %s", err))
    77  	}
    78  }