github.com/daniellockard/packer@v0.7.6-0.20141210173435-5a9390934716/builder/openstack/step_allocate_ip.go (about)

     1  package openstack
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  
     8  	"github.com/mitchellh/gophercloud-fork-40444fb"
     9  )
    10  
    11  type StepAllocateIp struct {
    12  	FloatingIpPool string
    13  	FloatingIp     string
    14  }
    15  
    16  func (s *StepAllocateIp) Run(state multistep.StateBag) multistep.StepAction {
    17  	ui := state.Get("ui").(packer.Ui)
    18  	csp := state.Get("csp").(gophercloud.CloudServersProvider)
    19  	server := state.Get("server").(*gophercloud.Server)
    20  
    21  	var instanceIp gophercloud.FloatingIp
    22  	// This is here in case we error out before putting instanceIp into the
    23  	// statebag below, because it is requested by Cleanup()
    24  	state.Put("access_ip", instanceIp)
    25  
    26  	if s.FloatingIp != "" {
    27  		instanceIp.Ip = s.FloatingIp
    28  	} else if s.FloatingIpPool != "" {
    29  		newIp, err := csp.CreateFloatingIp(s.FloatingIpPool)
    30  		if err != nil {
    31  			err := fmt.Errorf("Error creating floating ip from pool '%s'", s.FloatingIpPool)
    32  			state.Put("error", err)
    33  			ui.Error(err.Error())
    34  			return multistep.ActionHalt
    35  		}
    36  		instanceIp = newIp
    37  		ui.Say(fmt.Sprintf("Created temporary floating IP %s...", instanceIp.Ip))
    38  	}
    39  
    40  	if instanceIp.Ip != "" {
    41  		if err := csp.AssociateFloatingIp(server.Id, instanceIp); err != nil {
    42  			err := fmt.Errorf("Error associating floating IP %s with instance.", instanceIp.Ip)
    43  			state.Put("error", err)
    44  			ui.Error(err.Error())
    45  			return multistep.ActionHalt
    46  		} else {
    47  			ui.Say(fmt.Sprintf("Added floating IP %s to instance...", instanceIp.Ip))
    48  		}
    49  	}
    50  
    51  	state.Put("access_ip", instanceIp)
    52  
    53  	return multistep.ActionContinue
    54  }
    55  
    56  func (s *StepAllocateIp) Cleanup(state multistep.StateBag) {
    57  	ui := state.Get("ui").(packer.Ui)
    58  	csp := state.Get("csp").(gophercloud.CloudServersProvider)
    59  	instanceIp := state.Get("access_ip").(gophercloud.FloatingIp)
    60  	if s.FloatingIpPool != "" && instanceIp.Id != 0 {
    61  		if err := csp.DeleteFloatingIp(instanceIp); err != nil {
    62  			ui.Error(fmt.Sprintf("Error deleting temporary floating IP %s", instanceIp.Ip))
    63  			return
    64  		}
    65  		ui.Say(fmt.Sprintf("Deleted temporary floating IP %s", instanceIp.Ip))
    66  	}
    67  }