github.com/jbronn/packer@v0.1.6-0.20140120165540-8a1364dbd817/builder/googlecompute/step_create_instance.go (about) 1 package googlecompute 2 3 import ( 4 "errors" 5 "fmt" 6 "time" 7 8 "github.com/mitchellh/multistep" 9 "github.com/mitchellh/packer/common/uuid" 10 "github.com/mitchellh/packer/packer" 11 ) 12 13 // StepCreateInstance represents a Packer build step that creates GCE instances. 14 type StepCreateInstance struct { 15 instanceName string 16 } 17 18 // Run executes the Packer build step that creates a GCE instance. 19 func (s *StepCreateInstance) Run(state multistep.StateBag) multistep.StepAction { 20 config := state.Get("config").(*Config) 21 driver := state.Get("driver").(Driver) 22 sshPublicKey := state.Get("ssh_public_key").(string) 23 ui := state.Get("ui").(packer.Ui) 24 25 ui.Say("Creating instance...") 26 name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID()) 27 28 errCh, err := driver.RunInstance(&InstanceConfig{ 29 Description: "New instance created by Packer", 30 Image: config.SourceImage, 31 MachineType: config.MachineType, 32 Metadata: map[string]string{ 33 "sshKeys": fmt.Sprintf("%s:%s", config.SSHUsername, sshPublicKey), 34 }, 35 Name: name, 36 Network: config.Network, 37 Tags: config.Tags, 38 Zone: config.Zone, 39 }) 40 41 if err == nil { 42 ui.Message("Waiting for creation operation to complete...") 43 select { 44 case err = <-errCh: 45 case <-time.After(config.stateTimeout): 46 err = errors.New("time out while waiting for instance to create") 47 } 48 } 49 50 if err != nil { 51 err := fmt.Errorf("Error creating instance: %s", err) 52 state.Put("error", err) 53 ui.Error(err.Error()) 54 return multistep.ActionHalt 55 } 56 57 ui.Message("Instance has been created!") 58 59 // Things succeeded, store the name so we can remove it later 60 state.Put("instance_name", name) 61 s.instanceName = name 62 63 return multistep.ActionContinue 64 } 65 66 // Cleanup destroys the GCE instance created during the image creation process. 67 func (s *StepCreateInstance) Cleanup(state multistep.StateBag) { 68 if s.instanceName == "" { 69 return 70 } 71 72 config := state.Get("config").(*Config) 73 driver := state.Get("driver").(Driver) 74 ui := state.Get("ui").(packer.Ui) 75 76 ui.Say("Deleting instance...") 77 errCh, err := driver.DeleteInstance(config.Zone, s.instanceName) 78 if err == nil { 79 select { 80 case err = <-errCh: 81 case <-time.After(config.stateTimeout): 82 err = errors.New("time out while waiting for instance to delete") 83 } 84 } 85 86 if err != nil { 87 ui.Error(fmt.Sprintf( 88 "Error deleting instance. Please delete it manually.\n\n"+ 89 "Name: %s\n"+ 90 "Error: %s", s.instanceName, err)) 91 } 92 93 s.instanceName = "" 94 return 95 }