github.phpd.cn/hashicorp/packer@v1.3.2/builder/alicloud/ecs/step_run_instance.go (about) 1 package ecs 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/denverdino/aliyungo/ecs" 8 "github.com/hashicorp/packer/helper/multistep" 9 "github.com/hashicorp/packer/packer" 10 ) 11 12 type stepRunAlicloudInstance struct { 13 } 14 15 func (s *stepRunAlicloudInstance) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 16 client := state.Get("client").(*ecs.Client) 17 ui := state.Get("ui").(packer.Ui) 18 instance := state.Get("instance").(*ecs.InstanceAttributesType) 19 20 err := client.StartInstance(instance.InstanceId) 21 if err != nil { 22 err := fmt.Errorf("Error starting instance: %s", err) 23 state.Put("error", err) 24 ui.Error(err.Error()) 25 return multistep.ActionHalt 26 } 27 28 ui.Say(fmt.Sprintf("Starting instance: %s", instance.InstanceId)) 29 30 err = client.WaitForInstance(instance.InstanceId, ecs.Running, ALICLOUD_DEFAULT_TIMEOUT) 31 if err != nil { 32 err := fmt.Errorf("Timeout waiting for instance to start: %s", err) 33 state.Put("error", err) 34 ui.Error(err.Error()) 35 return multistep.ActionHalt 36 } 37 38 return multistep.ActionContinue 39 } 40 41 func (s *stepRunAlicloudInstance) Cleanup(state multistep.StateBag) { 42 _, cancelled := state.GetOk(multistep.StateCancelled) 43 _, halted := state.GetOk(multistep.StateHalted) 44 if cancelled || halted { 45 ui := state.Get("ui").(packer.Ui) 46 client := state.Get("client").(*ecs.Client) 47 instance := state.Get("instance").(*ecs.InstanceAttributesType) 48 instanceAttribute, _ := client.DescribeInstanceAttribute(instance.InstanceId) 49 if instanceAttribute.Status == ecs.Starting || instanceAttribute.Status == ecs.Running { 50 if err := client.StopInstance(instance.InstanceId, true); err != nil { 51 ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err)) 52 return 53 } 54 if err := client.WaitForInstance(instance.InstanceId, ecs.Stopped, ALICLOUD_DEFAULT_TIMEOUT); err != nil { 55 ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err)) 56 } 57 } 58 } 59 }