github.phpd.cn/hashicorp/packer@v1.3.2/builder/scaleway/builder.go (about) 1 // The scaleway package contains a packer.Builder implementation 2 // that builds Scaleway images (snapshots). 3 4 package scaleway 5 6 import ( 7 "errors" 8 "fmt" 9 "log" 10 11 "github.com/hashicorp/packer/common" 12 "github.com/hashicorp/packer/helper/communicator" 13 "github.com/hashicorp/packer/helper/multistep" 14 "github.com/hashicorp/packer/packer" 15 "github.com/scaleway/scaleway-cli/pkg/api" 16 ) 17 18 // The unique id for the builder 19 const BuilderId = "hashicorp.scaleway" 20 21 type Builder struct { 22 config *Config 23 runner multistep.Runner 24 } 25 26 func (b *Builder) Prepare(raws ...interface{}) ([]string, error) { 27 c, warnings, errs := NewConfig(raws...) 28 if errs != nil { 29 return warnings, errs 30 } 31 b.config = c 32 33 return nil, nil 34 } 35 36 func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) { 37 client, err := api.NewScalewayAPI(b.config.Organization, b.config.Token, b.config.UserAgent, b.config.Region) 38 39 if err != nil { 40 ui.Error(err.Error()) 41 return nil, err 42 } 43 44 state := new(multistep.BasicStateBag) 45 state.Put("config", b.config) 46 state.Put("client", client) 47 state.Put("hook", hook) 48 state.Put("ui", ui) 49 50 steps := []multistep.Step{ 51 &stepCreateSSHKey{ 52 Debug: b.config.PackerDebug, 53 DebugKeyPath: fmt.Sprintf("scw_%s.pem", b.config.PackerBuildName), 54 }, 55 new(stepCreateServer), 56 new(stepServerInfo), 57 &communicator.StepConnect{ 58 Config: &b.config.Comm, 59 Host: commHost, 60 SSHConfig: b.config.Comm.SSHConfigFunc(), 61 }, 62 new(common.StepProvision), 63 &common.StepCleanupTempKeys{ 64 Comm: &b.config.Comm, 65 }, 66 new(stepShutdown), 67 new(stepSnapshot), 68 new(stepImage), 69 } 70 71 b.runner = common.NewRunnerWithPauseFn(steps, b.config.PackerConfig, ui, state) 72 b.runner.Run(state) 73 74 if rawErr, ok := state.GetOk("error"); ok { 75 return nil, rawErr.(error) 76 } 77 78 // If we were interrupted or cancelled, then just exit. 79 if _, ok := state.GetOk(multistep.StateCancelled); ok { 80 return nil, errors.New("Build was cancelled.") 81 } 82 83 if _, ok := state.GetOk(multistep.StateHalted); ok { 84 return nil, errors.New("Build was halted.") 85 } 86 87 if _, ok := state.GetOk("snapshot_name"); !ok { 88 return nil, errors.New("Cannot find snapshot_name in state.") 89 } 90 91 artifact := &Artifact{ 92 imageName: state.Get("image_name").(string), 93 imageID: state.Get("image_id").(string), 94 snapshotName: state.Get("snapshot_name").(string), 95 snapshotID: state.Get("snapshot_id").(string), 96 regionName: state.Get("region").(string), 97 client: client, 98 } 99 100 return artifact, nil 101 } 102 103 func (b *Builder) Cancel() { 104 if b.runner != nil { 105 log.Println("Cancelling the step runner...") 106 b.runner.Cancel() 107 } 108 }