github.phpd.cn/hashicorp/packer@v1.3.2/builder/cloudstack/step_shutdown_instance.go (about)

     1  package cloudstack
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/packer/helper/multistep"
     8  	"github.com/hashicorp/packer/packer"
     9  	"github.com/xanzy/go-cloudstack/cloudstack"
    10  )
    11  
    12  type stepShutdownInstance struct{}
    13  
    14  func (s *stepShutdownInstance) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    15  	client := state.Get("client").(*cloudstack.CloudStackClient)
    16  	config := state.Get("config").(*Config)
    17  	ui := state.Get("ui").(packer.Ui)
    18  
    19  	ui.Say("Shutting down instance...")
    20  
    21  	// Retrieve the instance ID from the previously saved state.
    22  	instanceID, ok := state.Get("instance_id").(string)
    23  	if !ok || instanceID == "" {
    24  		state.Put("error", fmt.Errorf("Could not retrieve instance_id from state!"))
    25  		return multistep.ActionHalt
    26  	}
    27  
    28  	// Create a new parameter struct.
    29  	p := client.VirtualMachine.NewStopVirtualMachineParams(instanceID)
    30  
    31  	// Shutdown the virtual machine.
    32  	_, err := client.VirtualMachine.StopVirtualMachine(p)
    33  	if err != nil {
    34  		err := fmt.Errorf("Error shutting down instance %s: %s", config.InstanceName, err)
    35  		state.Put("error", err)
    36  		ui.Error(err.Error())
    37  		return multistep.ActionHalt
    38  	}
    39  
    40  	ui.Message("Instance has been shutdown!")
    41  	return multistep.ActionContinue
    42  }
    43  
    44  // Cleanup any resources that may have been created during the Run phase.
    45  func (s *stepShutdownInstance) Cleanup(state multistep.StateBag) {
    46  	// Nothing to cleanup for this step.
    47  }