github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/alicloud/ecs/step_run_instance.go (about)

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