packer-cn/builder/alicloud/ecs/step_config_eip.go

81 lines
2.5 KiB
Go
Raw Normal View History

package ecs
import (
"context"
"fmt"
2017-05-25 21:49:35 -04:00
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/ecs"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
2018-06-15 00:32:53 -04:00
type stepConfigAlicloudEIP struct {
AssociatePublicIpAddress bool
RegionId string
InternetChargeType string
allocatedId string
}
2018-06-15 00:32:53 -04:00
func (s *stepConfigAlicloudEIP) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
client := state.Get("client").(*ecs.Client)
ui := state.Get("ui").(packer.Ui)
instance := state.Get("instance").(*ecs.InstanceAttributesType)
2017-05-25 21:49:35 -04:00
ui.Say("Allocating eip")
ipaddress, allocateId, err := client.AllocateEipAddress(&ecs.AllocateEipAddressArgs{
RegionId: common.Region(s.RegionId), InternetChargeType: common.InternetChargeType(s.InternetChargeType),
})
if err != nil {
state.Put("error", err)
2017-05-25 21:49:35 -04:00
ui.Say(fmt.Sprintf("Error allocating eip: %s", err))
return multistep.ActionHalt
}
s.allocatedId = allocateId
2017-05-25 22:59:53 -04:00
if err = client.WaitForEip(common.Region(s.RegionId), allocateId,
ecs.EipStatusAvailable, ALICLOUD_DEFAULT_SHORT_TIMEOUT); err != nil {
state.Put("error", err)
2017-05-25 21:49:35 -04:00
ui.Say(fmt.Sprintf("Error allocating eip: %s", err))
return multistep.ActionHalt
}
if err = client.AssociateEipAddress(allocateId, instance.InstanceId); err != nil {
state.Put("error", err)
2017-05-25 21:49:35 -04:00
ui.Say(fmt.Sprintf("Error binding eip: %s", err))
return multistep.ActionHalt
}
2017-05-25 22:59:53 -04:00
if err = client.WaitForEip(common.Region(s.RegionId), allocateId,
ecs.EipStatusInUse, ALICLOUD_DEFAULT_SHORT_TIMEOUT); err != nil {
state.Put("error", err)
2017-05-25 21:49:35 -04:00
ui.Say(fmt.Sprintf("Error associating eip: %s", err))
return multistep.ActionHalt
}
2017-05-25 21:49:35 -04:00
ui.Say(fmt.Sprintf("Allocated eip %s", ipaddress))
state.Put("ipaddress", ipaddress)
return multistep.ActionContinue
}
2018-06-15 00:32:53 -04:00
func (s *stepConfigAlicloudEIP) Cleanup(state multistep.StateBag) {
if len(s.allocatedId) == 0 {
return
}
client := state.Get("client").(*ecs.Client)
instance := state.Get("instance").(*ecs.InstanceAttributesType)
ui := state.Get("ui").(packer.Ui)
message(state, "EIP")
if err := client.UnassociateEipAddress(s.allocatedId, instance.InstanceId); err != nil {
2017-06-01 22:33:12 -04:00
ui.Say(fmt.Sprintf("Failed to unassociate eip."))
}
2017-05-25 21:49:35 -04:00
if err := client.WaitForEip(common.Region(s.RegionId), s.allocatedId, ecs.EipStatusAvailable, ALICLOUD_DEFAULT_SHORT_TIMEOUT); err != nil {
ui.Say(fmt.Sprintf("Timeout while unassociating eip."))
}
if err := client.ReleaseEipAddress(s.allocatedId); err != nil {
2017-06-01 22:33:12 -04:00
ui.Say(fmt.Sprintf("Failed to release eip."))
}
}