diff --git a/builder/docker/builder.go b/builder/docker/builder.go index 9f14a20d0..ecc794f26 100644 --- a/builder/docker/builder.go +++ b/builder/docker/builder.go @@ -38,6 +38,7 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, error) { func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) { steps := []multistep.Step{ &StepPull{}, + &StepRun{}, } // Setup the state bag and initial state for the steps diff --git a/builder/docker/step_run.go b/builder/docker/step_run.go new file mode 100644 index 000000000..51bc504db --- /dev/null +++ b/builder/docker/step_run.go @@ -0,0 +1,53 @@ +package docker + +import ( + "bytes" + "fmt" + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" + "os/exec" + "strings" +) + +type StepRun struct { + containerId string +} + +func (s *StepRun) Run(state multistep.StateBag) multistep.StepAction { + config := state.Get("config").(*Config) + ui := state.Get("ui").(packer.Ui) + + ui.Say("Starting docker container with /bin/bash") + + var stdout, stderr bytes.Buffer + cmd := exec.Command("docker", "run", "-d", "-i", "-t", config.Image, "/bin/bash") + cmd.Stdout = &stdout + cmd.Stderr = &stderr + if err := cmd.Start(); err != nil { + err := fmt.Errorf("Error running container: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + if err := cmd.Wait(); err != nil { + err := fmt.Errorf("Error running container: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + s.containerId = strings.TrimSpace(stdout.String()) + ui.Message(fmt.Sprintf("Container ID: %s", s.containerId)) + + return multistep.ActionContinue +} + +func (s *StepRun) Cleanup(state multistep.StateBag) { + if s.containerId == "" { + return + } + + // TODO(mitchellh): handle errors + exec.Command("docker", "kill", s.containerId).Run() +}