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