github.com/sneal/packer@v0.5.2/builder/googlecompute/builder.go (about) 1 // The googlecompute package contains a packer.Builder implementation that 2 // builds images for Google Compute Engine. 3 package googlecompute 4 5 import ( 6 "fmt" 7 "github.com/mitchellh/multistep" 8 "github.com/mitchellh/packer/common" 9 "github.com/mitchellh/packer/packer" 10 "log" 11 "time" 12 ) 13 14 // The unique ID for this builder. 15 const BuilderId = "packer.googlecompute" 16 17 // Builder represents a Packer Builder. 18 type Builder struct { 19 config *Config 20 runner multistep.Runner 21 } 22 23 // Prepare processes the build configuration parameters. 24 func (b *Builder) Prepare(raws ...interface{}) ([]string, error) { 25 c, warnings, errs := NewConfig(raws...) 26 if errs != nil { 27 return warnings, errs 28 } 29 b.config = c 30 31 return warnings, nil 32 } 33 34 // Run executes a googlecompute Packer build and returns a packer.Artifact 35 // representing a GCE machine image. 36 func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) { 37 driver, err := NewDriverGCE( 38 ui, b.config.ProjectId, b.config.clientSecrets, b.config.privateKeyBytes) 39 if err != nil { 40 return nil, err 41 } 42 43 // Set up the state. 44 state := new(multistep.BasicStateBag) 45 state.Put("config", b.config) 46 state.Put("driver", driver) 47 state.Put("hook", hook) 48 state.Put("ui", ui) 49 50 // Build the steps. 51 steps := []multistep.Step{ 52 &StepCreateSSHKey{ 53 Debug: b.config.PackerDebug, 54 DebugKeyPath: fmt.Sprintf("gce_%s.pem", b.config.PackerBuildName), 55 }, 56 &StepCreateInstance{ 57 Debug: b.config.PackerDebug, 58 }, 59 &StepInstanceInfo{ 60 Debug: b.config.PackerDebug, 61 }, 62 &common.StepConnectSSH{ 63 SSHAddress: sshAddress, 64 SSHConfig: sshConfig, 65 SSHWaitTimeout: 5 * time.Minute, 66 }, 67 new(common.StepProvision), 68 new(StepUpdateGsutil), 69 new(StepCreateImage), 70 new(StepUploadImage), 71 new(StepRegisterImage), 72 } 73 74 // Run the steps. 75 if b.config.PackerDebug { 76 b.runner = &multistep.DebugRunner{ 77 Steps: steps, 78 PauseFn: common.MultistepDebugFn(ui), 79 } 80 } else { 81 b.runner = &multistep.BasicRunner{Steps: steps} 82 } 83 b.runner.Run(state) 84 85 // Report any errors. 86 if rawErr, ok := state.GetOk("error"); ok { 87 return nil, rawErr.(error) 88 } 89 if _, ok := state.GetOk("image_name"); !ok { 90 log.Println("Failed to find image_name in state. Bug?") 91 return nil, nil 92 } 93 94 artifact := &Artifact{ 95 imageName: state.Get("image_name").(string), 96 driver: driver, 97 } 98 return artifact, nil 99 } 100 101 // Cancel. 102 func (b *Builder) Cancel() { 103 if b.runner != nil { 104 log.Println("Cancelling the step runner...") 105 b.runner.Cancel() 106 } 107 }