github.com/angdraug/packer@v1.3.2/builder/digitalocean/step_power_off.go (about)

     1  package digitalocean
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/digitalocean/godo"
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  type stepPowerOff struct{}
    14  
    15  func (s *stepPowerOff) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    16  	client := state.Get("client").(*godo.Client)
    17  	c := state.Get("config").(*Config)
    18  	ui := state.Get("ui").(packer.Ui)
    19  	dropletId := state.Get("droplet_id").(int)
    20  
    21  	droplet, _, err := client.Droplets.Get(context.TODO(), dropletId)
    22  	if err != nil {
    23  		err := fmt.Errorf("Error checking droplet state: %s", err)
    24  		state.Put("error", err)
    25  		ui.Error(err.Error())
    26  		return multistep.ActionHalt
    27  	}
    28  
    29  	if droplet.Status == "off" {
    30  		// Droplet is already off, don't do anything
    31  		return multistep.ActionContinue
    32  	}
    33  
    34  	// Pull the plug on the Droplet
    35  	ui.Say("Forcefully shutting down Droplet...")
    36  	_, _, err = client.DropletActions.PowerOff(context.TODO(), dropletId)
    37  	if err != nil {
    38  		err := fmt.Errorf("Error powering off droplet: %s", err)
    39  		state.Put("error", err)
    40  		ui.Error(err.Error())
    41  		return multistep.ActionHalt
    42  	}
    43  
    44  	log.Println("Waiting for poweroff event to complete...")
    45  	err = waitForDropletState("off", dropletId, client, c.StateTimeout)
    46  	if err != nil {
    47  		state.Put("error", err)
    48  		ui.Error(err.Error())
    49  		return multistep.ActionHalt
    50  	}
    51  
    52  	// Wait for the droplet to become unlocked for future steps
    53  	if err := waitForDropletUnlocked(client, dropletId, c.StateTimeout); err != nil {
    54  		// If we get an error the first time, actually report it
    55  		err := fmt.Errorf("Error powering off droplet: %s", err)
    56  		state.Put("error", err)
    57  		ui.Error(err.Error())
    58  		return multistep.ActionHalt
    59  	}
    60  
    61  	return multistep.ActionContinue
    62  }
    63  
    64  func (s *stepPowerOff) Cleanup(state multistep.StateBag) {
    65  	// no cleanup
    66  }