github.phpd.cn/hashicorp/packer@v1.3.2/builder/triton/step_create_source_machine.go (about) 1 package triton 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "github.com/hashicorp/packer/helper/multistep" 9 "github.com/hashicorp/packer/packer" 10 ) 11 12 // StepCreateSourceMachine creates an machine with the specified attributes 13 // and waits for it to become available for provisioners. 14 type StepCreateSourceMachine struct{} 15 16 func (s *StepCreateSourceMachine) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 17 config := state.Get("config").(*Config) 18 driver := state.Get("driver").(Driver) 19 ui := state.Get("ui").(packer.Ui) 20 21 if !config.MachineImageFilters.Empty() { 22 ui.Say("Selecting an image based on search criteria") 23 imageId, err := driver.GetImage(*config) 24 if err != nil { 25 state.Put("error", fmt.Errorf("Problem selecting an image based on an search criteria: %s", err)) 26 return multistep.ActionHalt 27 } 28 ui.Say(fmt.Sprintf("Based, on given search criteria, Machine ID is: %q", imageId)) 29 config.MachineImage = imageId 30 } 31 32 machineId, err := driver.CreateMachine(*config) 33 if err != nil { 34 state.Put("error", fmt.Errorf("Problem creating source machine: %s", err)) 35 return multistep.ActionHalt 36 } 37 38 ui.Say("Waiting for source machine to become available...") 39 err = driver.WaitForMachineState(machineId, "running", 10*time.Minute) 40 if err != nil { 41 state.Put("error", fmt.Errorf("Problem waiting for source machine to become available: %s", err)) 42 return multistep.ActionHalt 43 } 44 45 state.Put("machine", machineId) 46 return multistep.ActionContinue 47 } 48 49 func (s *StepCreateSourceMachine) Cleanup(state multistep.StateBag) { 50 driver := state.Get("driver").(Driver) 51 ui := state.Get("ui").(packer.Ui) 52 53 machineIdRaw, ok := state.GetOk("machine") 54 if ok && machineIdRaw.(string) != "" { 55 machineId := machineIdRaw.(string) 56 ui.Say(fmt.Sprintf("Stopping source machine (%s)...", machineId)) 57 err := driver.StopMachine(machineId) 58 if err != nil { 59 state.Put("error", fmt.Errorf("Problem stopping source machine: %s", err)) 60 return 61 } 62 63 ui.Say(fmt.Sprintf("Waiting for source machine to stop (%s)...", machineId)) 64 err = driver.WaitForMachineState(machineId, "stopped", 10*time.Minute) 65 if err != nil { 66 state.Put("error", fmt.Errorf("Problem waiting for source machine to stop: %s", err)) 67 return 68 } 69 70 ui.Say(fmt.Sprintf("Deleting source machine (%s)...", machineId)) 71 err = driver.DeleteMachine(machineId) 72 if err != nil { 73 state.Put("error", fmt.Errorf("Problem deleting source machine: %s", err)) 74 return 75 } 76 77 ui.Say(fmt.Sprintf("Waiting for source machine to be destroyed (%s)...", machineId)) 78 err = driver.WaitForMachineDeletion(machineId, 10*time.Minute) 79 if err != nil { 80 state.Put("error", fmt.Errorf("Problem waiting for source machine to be deleted: %s", err)) 81 return 82 } 83 } 84 }