github.com/angdraug/packer@v1.3.2/builder/oracle/oci/step_create_instance.go (about)

     1  package oci
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/packer/helper/multistep"
     8  	"github.com/hashicorp/packer/packer"
     9  )
    10  
    11  type stepCreateInstance struct{}
    12  
    13  func (s *stepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
    14  	var (
    15  		driver = state.Get("driver").(Driver)
    16  		ui     = state.Get("ui").(packer.Ui)
    17  		config = state.Get("config").(*Config)
    18  	)
    19  
    20  	ui.Say("Creating instance...")
    21  
    22  	instanceID, err := driver.CreateInstance(ctx, string(config.Comm.SSHPublicKey))
    23  	if err != nil {
    24  		err = fmt.Errorf("Problem creating instance: %s", err)
    25  		ui.Error(err.Error())
    26  		state.Put("error", err)
    27  		return multistep.ActionHalt
    28  	}
    29  
    30  	state.Put("instance_id", instanceID)
    31  
    32  	ui.Say(fmt.Sprintf("Created instance (%s).", instanceID))
    33  
    34  	ui.Say("Waiting for instance to enter 'RUNNING' state...")
    35  
    36  	if err = driver.WaitForInstanceState(ctx, instanceID, []string{"STARTING", "PROVISIONING"}, "RUNNING"); err != nil {
    37  		err = fmt.Errorf("Error waiting for instance to start: %s", err)
    38  		ui.Error(err.Error())
    39  		state.Put("error", err)
    40  		return multistep.ActionHalt
    41  	}
    42  
    43  	ui.Say("Instance 'RUNNING'.")
    44  
    45  	return multistep.ActionContinue
    46  }
    47  
    48  func (s *stepCreateInstance) Cleanup(state multistep.StateBag) {
    49  	driver := state.Get("driver").(Driver)
    50  	ui := state.Get("ui").(packer.Ui)
    51  
    52  	idRaw, ok := state.GetOk("instance_id")
    53  	if !ok {
    54  		return
    55  	}
    56  	id := idRaw.(string)
    57  
    58  	ui.Say(fmt.Sprintf("Terminating instance (%s)...", id))
    59  
    60  	if err := driver.TerminateInstance(context.TODO(), id); err != nil {
    61  		err = fmt.Errorf("Error terminating instance. Please terminate manually: %s", err)
    62  		ui.Error(err.Error())
    63  		state.Put("error", err)
    64  		return
    65  	}
    66  
    67  	err := driver.WaitForInstanceState(context.TODO(), id, []string{"TERMINATING"}, "TERMINATED")
    68  	if err != nil {
    69  		err = fmt.Errorf("Error terminating instance. Please terminate manually: %s", err)
    70  		ui.Error(err.Error())
    71  		state.Put("error", err)
    72  		return
    73  	}
    74  
    75  	ui.Say("Terminated instance.")
    76  }