github.com/mitchellh/packer@v1.3.2/builder/docker/step_run.go (about)

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