github.phpd.cn/hashicorp/packer@v1.3.2/builder/hcloud/builder.go (about) 1 package hcloud 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/hashicorp/packer/common" 8 "github.com/hashicorp/packer/helper/communicator" 9 "github.com/hashicorp/packer/helper/multistep" 10 "github.com/hashicorp/packer/packer" 11 "github.com/hetznercloud/hcloud-go/hcloud" 12 ) 13 14 // The unique id for the builder 15 const BuilderId = "hcloud.builder" 16 17 type Builder struct { 18 config Config 19 runner multistep.Runner 20 hcloudClient *hcloud.Client 21 } 22 23 var pluginVersion = "1.0.0" 24 25 func (b *Builder) Prepare(raws ...interface{}) ([]string, error) { 26 config, warnings, errs := NewConfig(raws...) 27 if errs != nil { 28 return warnings, errs 29 } 30 b.config = *config 31 return nil, nil 32 } 33 34 func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) { 35 opts := []hcloud.ClientOption{ 36 hcloud.WithToken(b.config.HCloudToken), 37 hcloud.WithEndpoint(b.config.Endpoint), 38 hcloud.WithPollInterval(b.config.PollInterval), 39 hcloud.WithApplication("hcloud-packer", pluginVersion), 40 } 41 b.hcloudClient = hcloud.NewClient(opts...) 42 // Set up the state 43 state := new(multistep.BasicStateBag) 44 state.Put("config", &b.config) 45 state.Put("hcloudClient", b.hcloudClient) 46 state.Put("hook", hook) 47 state.Put("ui", ui) 48 49 // Build the steps 50 steps := []multistep.Step{ 51 &stepCreateSSHKey{ 52 Debug: b.config.PackerDebug, 53 DebugKeyPath: fmt.Sprintf("ssh_key_%s.pem", b.config.PackerBuildName), 54 }, 55 &stepCreateServer{}, 56 &communicator.StepConnect{ 57 Config: &b.config.Comm, 58 Host: getServerIP, 59 SSHConfig: b.config.Comm.SSHConfigFunc(), 60 }, 61 &common.StepProvision{}, 62 &common.StepCleanupTempKeys{ 63 Comm: &b.config.Comm, 64 }, 65 &stepShutdownServer{}, 66 &stepCreateSnapshot{}, 67 } 68 // Run the steps 69 b.runner = common.NewRunner(steps, b.config.PackerConfig, ui) 70 b.runner.Run(state) 71 // If there was an error, return that 72 if rawErr, ok := state.GetOk("error"); ok { 73 return nil, rawErr.(error) 74 } 75 76 if _, ok := state.GetOk("snapshot_name"); !ok { 77 return nil, nil 78 } 79 80 artifact := &Artifact{ 81 snapshotName: state.Get("snapshot_name").(string), 82 snapshotId: state.Get("snapshot_id").(int), 83 hcloudClient: b.hcloudClient, 84 } 85 86 return artifact, nil 87 } 88 89 func (b *Builder) Cancel() { 90 if b.runner != nil { 91 log.Println("Cancelling the step runner...") 92 b.runner.Cancel() 93 } 94 }