github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/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  	ui.Say("Starting instance.")
    28  	err = client.WaitForInstance(instance.InstanceId, ecs.Running, ALICLOUD_DEFAULT_TIMEOUT)
    29  	if err != nil {
    30  		err := fmt.Errorf("Timeout waiting for instance to start: %s", err)
    31  		state.Put("error", err)
    32  		ui.Error(err.Error())
    33  		return multistep.ActionHalt
    34  	}
    35  
    36  	return multistep.ActionContinue
    37  }
    38  
    39  func (s *stepRunAlicloudInstance) Cleanup(state multistep.StateBag) {
    40  	_, cancelled := state.GetOk(multistep.StateCancelled)
    41  	_, halted := state.GetOk(multistep.StateHalted)
    42  	if cancelled || halted {
    43  		ui := state.Get("ui").(packer.Ui)
    44  		client := state.Get("client").(*ecs.Client)
    45  		instance := state.Get("instance").(*ecs.InstanceAttributesType)
    46  		instanceAttribute, _ := client.DescribeInstanceAttribute(instance.InstanceId)
    47  		if instanceAttribute.Status == ecs.Starting || instanceAttribute.Status == ecs.Running {
    48  			if err := client.StopInstance(instance.InstanceId, true); err != nil {
    49  				ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err))
    50  				return
    51  			}
    52  			if err := client.WaitForInstance(instance.InstanceId, ecs.Stopped, ALICLOUD_DEFAULT_TIMEOUT); err != nil {
    53  				ui.Say(fmt.Sprintf("Error stopping instance %s, it may still be around %s", instance.InstanceId, err))
    54  			}
    55  		}
    56  	}
    57  }