github.phpd.cn/hashicorp/packer@v1.3.2/builder/oracle/classic/step_snapshot.go (about)

     1  package classic
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/go-oracle-terraform/compute"
     8  	"github.com/hashicorp/packer/helper/multistep"
     9  	"github.com/hashicorp/packer/packer"
    10  )
    11  
    12  type stepSnapshot struct {
    13  	cleanupSnap bool
    14  }
    15  
    16  func (s *stepSnapshot) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    17  	// get variables from state
    18  	ui := state.Get("ui").(packer.Ui)
    19  	ui.Say("Creating Snapshot...")
    20  	config := state.Get("config").(*Config)
    21  	client := state.Get("client").(*compute.ComputeClient)
    22  	instanceID := state.Get("instance_id").(string)
    23  
    24  	// get instances client
    25  	snapshotClient := client.Snapshots()
    26  
    27  	// Instances Input
    28  	snapshotInput := &compute.CreateSnapshotInput{
    29  		Instance:     fmt.Sprintf("%s/%s", config.ImageName, instanceID),
    30  		MachineImage: config.ImageName,
    31  		Timeout:      config.SnapshotTimeout,
    32  	}
    33  
    34  	snap, err := snapshotClient.CreateSnapshot(snapshotInput)
    35  	if err != nil {
    36  		err = fmt.Errorf("Problem creating snapshot: %s", err)
    37  		ui.Error(err.Error())
    38  		state.Put("error", err)
    39  		return multistep.ActionHalt
    40  	}
    41  	state.Put("snapshot", snap)
    42  	ui.Message(fmt.Sprintf("Created snapshot: %s.", snap.Name))
    43  	return multistep.ActionContinue
    44  }
    45  
    46  func (s *stepSnapshot) Cleanup(state multistep.StateBag) {
    47  	// Delete the snapshot
    48  	var snap *compute.Snapshot
    49  	if snapshot, ok := state.GetOk("snapshot"); ok {
    50  		snap = snapshot.(*compute.Snapshot)
    51  	} else {
    52  		return
    53  	}
    54  
    55  	ui := state.Get("ui").(packer.Ui)
    56  	ui.Say("Deleting Snapshot...")
    57  	client := state.Get("client").(*compute.ComputeClient)
    58  	snapClient := client.Snapshots()
    59  	snapInput := compute.DeleteSnapshotInput{
    60  		Snapshot:     snap.Name,
    61  		MachineImage: snap.MachineImage,
    62  	}
    63  
    64  	err := snapClient.DeleteSnapshotResourceOnly(&snapInput)
    65  	if err != nil {
    66  		err = fmt.Errorf("Problem deleting snapshot: %s", err)
    67  		ui.Error(err.Error())
    68  		state.Put("error", err)
    69  	}
    70  	return
    71  }