github.com/rothwerx/packer@v0.9.0/builder/docker/step_run.go (about)

     1  package docker
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  )
     8  
     9  type StepRun struct {
    10  	containerId string
    11  }
    12  
    13  func (s *StepRun) Run(state multistep.StateBag) multistep.StepAction {
    14  	config := state.Get("config").(*Config)
    15  	driver := state.Get("driver").(Driver)
    16  	tempDir := state.Get("temp_dir").(string)
    17  	ui := state.Get("ui").(packer.Ui)
    18  
    19  	runConfig := ContainerConfig{
    20  		Image:      config.Image,
    21  		RunCommand: config.RunCommand,
    22  		Volumes:    make(map[string]string),
    23  	}
    24  
    25  	for host, container := range config.Volumes {
    26  		runConfig.Volumes[host] = container
    27  	}
    28  	runConfig.Volumes[tempDir] = "/packer-files"
    29  
    30  	ui.Say("Starting docker container...")
    31  	containerId, err := driver.StartContainer(&runConfig)
    32  	if err != nil {
    33  		err := fmt.Errorf("Error running container: %s", err)
    34  		state.Put("error", err)
    35  		ui.Error(err.Error())
    36  		return multistep.ActionHalt
    37  	}
    38  
    39  	// Save the container ID
    40  	s.containerId = containerId
    41  	state.Put("container_id", s.containerId)
    42  	ui.Message(fmt.Sprintf("Container ID: %s", s.containerId))
    43  	return multistep.ActionContinue
    44  }
    45  
    46  func (s *StepRun) Cleanup(state multistep.StateBag) {
    47  	if s.containerId == "" {
    48  		return
    49  	}
    50  
    51  	driver := state.Get("driver").(Driver)
    52  	ui := state.Get("ui").(packer.Ui)
    53  
    54  	// Kill the container. We don't handle errors because errors usually
    55  	// just mean that the container doesn't exist anymore, which isn't a
    56  	// big deal.
    57  	ui.Say(fmt.Sprintf("Killing the container: %s", s.containerId))
    58  	driver.StopContainer(s.containerId)
    59  
    60  	// Reset the container ID so that we're idempotent
    61  	s.containerId = ""
    62  }