2017-03-03 16:56:17 +08:00
|
|
|
package ecs
|
|
|
|
|
|
|
|
import (
|
2018-01-22 15:32:33 -08:00
|
|
|
"context"
|
2017-03-03 16:56:17 +08:00
|
|
|
"fmt"
|
2017-05-25 18:49:35 -07:00
|
|
|
|
2017-03-03 16:56:17 +08:00
|
|
|
"github.com/denverdino/aliyungo/ecs"
|
2018-01-19 16:18:44 -08:00
|
|
|
"github.com/hashicorp/packer/helper/multistep"
|
2017-04-17 21:04:52 +08:00
|
|
|
"github.com/hashicorp/packer/packer"
|
2017-03-03 16:56:17 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type stepRunAlicloudInstance struct {
|
|
|
|
}
|
|
|
|
|
2018-01-22 15:31:41 -08:00
|
|
|
func (s *stepRunAlicloudInstance) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
|
2017-03-03 16:56:17 +08:00
|
|
|
client := state.Get("client").(*ecs.Client)
|
|
|
|
ui := state.Get("ui").(packer.Ui)
|
|
|
|
instance := state.Get("instance").(*ecs.InstanceAttributesType)
|
|
|
|
|
|
|
|
err := client.StartInstance(instance.InstanceId)
|
|
|
|
if err != nil {
|
2017-05-25 18:49:35 -07:00
|
|
|
err := fmt.Errorf("Error starting instance: %s", err)
|
2017-03-03 16:56:17 +08:00
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
2017-06-01 19:33:12 -07:00
|
|
|
ui.Say("Starting instance.")
|
2017-03-03 16:56:17 +08:00
|
|
|
err = client.WaitForInstance(instance.InstanceId, ecs.Running, ALICLOUD_DEFAULT_TIMEOUT)
|
|
|
|
if err != nil {
|
2017-05-25 18:49:35 -07:00
|
|
|
err := fmt.Errorf("Timeout waiting for instance to start: %s", err)
|
2017-03-03 16:56:17 +08:00
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *stepRunAlicloudInstance) Cleanup(state multistep.StateBag) {
|
|
|
|
_, cancelled := state.GetOk(multistep.StateCancelled)
|
|
|
|
_, halted := state.GetOk(multistep.StateHalted)
|
|
|
|
if cancelled || halted {
|
|
|
|
ui := state.Get("ui").(packer.Ui)
|
|
|
|
client := state.Get("client").(*ecs.Client)
|
|
|
|
instance := state.Get("instance").(*ecs.InstanceAttributesType)
|
2018-03-13 07:12:16 +00:00
|
|
|
instanceAttribute, _ := client.DescribeInstanceAttribute(instance.InstanceId)
|
|
|
|
if instanceAttribute.Status == ecs.Starting || instanceAttribute.Status == ecs.Running {
|
2017-03-03 16:56:17 +08:00
|
|
|
if err := client.StopInstance(instance.InstanceId, true); err != nil {
|
2017-05-25 18:49:35 -07:00
|
|
|
ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err))
|
2017-03-03 16:56:17 +08:00
|
|
|
return
|
|
|
|
}
|
2017-06-02 11:28:41 +08:00
|
|
|
if err := client.WaitForInstance(instance.InstanceId, ecs.Stopped, ALICLOUD_DEFAULT_TIMEOUT); err != nil {
|
|
|
|
ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err))
|
|
|
|
}
|
2017-03-03 16:56:17 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|