2017-03-03 03:56:17 -05:00
|
|
|
package ecs
|
|
|
|
|
|
|
|
import (
|
2018-01-22 18:32:33 -05:00
|
|
|
"context"
|
2017-03-03 03:56:17 -05:00
|
|
|
"fmt"
|
2017-05-25 21:49:35 -04:00
|
|
|
|
2017-03-03 03:56:17 -05:00
|
|
|
"github.com/denverdino/aliyungo/ecs"
|
2018-01-19 19:18:44 -05:00
|
|
|
"github.com/hashicorp/packer/helper/multistep"
|
2017-04-17 09:04:52 -04:00
|
|
|
"github.com/hashicorp/packer/packer"
|
2017-03-03 03:56:17 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type stepRunAlicloudInstance struct {
|
|
|
|
}
|
|
|
|
|
2018-01-22 18:31:41 -05:00
|
|
|
func (s *stepRunAlicloudInstance) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
|
2017-03-03 03:56:17 -05: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 21:49:35 -04:00
|
|
|
err := fmt.Errorf("Error starting instance: %s", err)
|
2017-03-03 03:56:17 -05:00
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
2017-06-01 22:33:12 -04:00
|
|
|
ui.Say("Starting instance.")
|
2017-03-03 03:56:17 -05:00
|
|
|
err = client.WaitForInstance(instance.InstanceId, ecs.Running, ALICLOUD_DEFAULT_TIMEOUT)
|
|
|
|
if err != nil {
|
2017-05-25 21:49:35 -04:00
|
|
|
err := fmt.Errorf("Timeout waiting for instance to start: %s", err)
|
2017-03-03 03:56:17 -05: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 03:12:16 -04:00
|
|
|
instanceAttribute, _ := client.DescribeInstanceAttribute(instance.InstanceId)
|
|
|
|
if instanceAttribute.Status == ecs.Starting || instanceAttribute.Status == ecs.Running {
|
2017-03-03 03:56:17 -05:00
|
|
|
if err := client.StopInstance(instance.InstanceId, true); err != nil {
|
2017-05-25 21:49:35 -04:00
|
|
|
ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err))
|
2017-03-03 03:56:17 -05:00
|
|
|
return
|
|
|
|
}
|
2017-06-01 23:28:41 -04: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 03:56:17 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|