github.com/sneal/packer@v0.5.2/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: map[string]string{
    23  			tempDir: "/packer-files",
    24  		},
    25  	}
    26  
    27  	ui.Say("Starting docker container...")
    28  	containerId, err := driver.StartContainer(&runConfig)
    29  	if err != nil {
    30  		err := fmt.Errorf("Error running container: %s", err)
    31  		state.Put("error", err)
    32  		ui.Error(err.Error())
    33  		return multistep.ActionHalt
    34  	}
    35  
    36  	// Save the container ID
    37  	s.containerId = containerId
    38  	state.Put("container_id", s.containerId)
    39  	ui.Message(fmt.Sprintf("Container ID: %s", s.containerId))
    40  	return multistep.ActionContinue
    41  }
    42  
    43  func (s *StepRun) Cleanup(state multistep.StateBag) {
    44  	if s.containerId == "" {
    45  		return
    46  	}
    47  
    48  	driver := state.Get("driver").(Driver)
    49  	ui := state.Get("ui").(packer.Ui)
    50  
    51  	// Kill the container. We don't handle errors because errors usually
    52  	// just mean that the container doesn't exist anymore, which isn't a
    53  	// big deal.
    54  	ui.Say(fmt.Sprintf("Killing the container: %s", s.containerId))
    55  	driver.StopContainer(s.containerId)
    56  
    57  	// Reset the container ID so that we're idempotent
    58  	s.containerId = ""
    59  }