packer-cn/builder/docker/step_run.go

80 lines
2.1 KiB
Go
Raw Normal View History

2013-11-09 01:17:46 -05:00
package docker
import (
"context"
2013-11-09 01:17:46 -05:00
"fmt"
2020-12-17 16:29:25 -05:00
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
2013-11-09 01:17:46 -05:00
)
type StepRun struct {
containerId string
}
func (s *StepRun) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packersdk.Ui)
config, ok := state.Get("config").(*Config)
if !ok {
err := fmt.Errorf("error encountered obtaining docker config")
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
2013-11-09 01:17:46 -05:00
2013-11-09 16:03:01 -05:00
runConfig := ContainerConfig{
Image: config.Image,
RunCommand: config.RunCommand,
Device: config.Device,
TmpFs: config.TmpFs,
2014-09-05 18:48:42 -04:00
Volumes: make(map[string]string),
CapAdd: config.CapAdd,
CapDrop: config.CapDrop,
Privileged: config.Privileged,
}
2014-09-05 18:48:42 -04:00
for host, container := range config.Volumes {
runConfig.Volumes[host] = container
}
tempDir := state.Get("temp_dir").(string)
2017-07-17 12:08:33 -04:00
runConfig.Volumes[tempDir] = config.ContainerDir
2014-09-05 18:48:42 -04:00
driver := state.Get("driver").(Driver)
ui.Say("Starting docker container...")
2013-11-09 16:03:01 -05:00
containerId, err := driver.StartContainer(&runConfig)
if err != nil {
2013-11-09 01:17:46 -05:00
err := fmt.Errorf("Error running container: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
2013-11-09 16:03:01 -05:00
// Save the container ID
s.containerId = containerId
state.Put("container_id", s.containerId)
// instance_id is the generic term used so that users can have access to the
// instance id inside of the provisioners, used in step_provision.
state.Put("instance_id", s.containerId)
2013-11-09 16:03:01 -05:00
ui.Message(fmt.Sprintf("Container ID: %s", s.containerId))
2013-11-09 01:17:46 -05:00
return multistep.ActionContinue
}
func (s *StepRun) Cleanup(state multistep.StateBag) {
if s.containerId == "" {
return
}
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packersdk.Ui)
// Kill the container. We don't handle errors because errors usually
// just mean that the container doesn't exist anymore, which isn't a
// big deal.
ui.Say(fmt.Sprintf("Killing the container: %s", s.containerId))
driver.KillContainer(s.containerId)
2013-11-09 16:03:01 -05:00
// Reset the container ID so that we're idempotent
s.containerId = ""
2013-11-09 01:17:46 -05:00
}