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

76 lines
2.3 KiB
Go
Raw Normal View History

package ecs
import (
"context"
"fmt"
2017-05-25 21:20:20 -04:00
2018-01-22 20:21:10 -05:00
"time"
"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 stepAttachKeyPair struct {
}
2018-06-15 00:32:53 -04:00
func (s *stepAttachKeyPair) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
client := state.Get("client").(*ecs.Client)
config := state.Get("config").(Config)
instance := state.Get("instance").(*ecs.InstanceAttributesType)
timeoutPoint := time.Now().Add(120 * time.Second)
2018-08-27 09:58:00 -04:00
keyPairName := config.Comm.SSHKeyPair
if keyPairName == "" {
return multistep.ActionContinue
}
2017-05-25 22:23:36 -04:00
for {
2017-05-25 22:59:53 -04:00
err := client.AttachKeyPair(&ecs.AttachKeyPairArgs{RegionId: common.Region(config.AlicloudRegion),
KeyPairName: keyPairName, InstanceIds: "[\"" + instance.InstanceId + "\"]"})
if err != nil {
e, _ := err.(*common.Error)
2017-05-25 22:59:53 -04:00
if (!(e.Code == "MissingParameter" || e.Code == "DependencyViolation.WindowsInstance" ||
e.Code == "InvalidKeyPairName.NotFound" || e.Code == "InvalidRegionId.NotFound")) &&
time.Now().Before(timeoutPoint) {
time.Sleep(5 * time.Second)
continue
}
2017-05-25 22:59:53 -04:00
err := fmt.Errorf("Error attaching keypair %s to instance %s : %s",
keyPairName, instance.InstanceId, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
break
}
ui.Message(fmt.Sprintf("Attach keypair %s to instance: %s", keyPairName, instance.InstanceId))
return multistep.ActionContinue
}
2018-06-15 00:32:53 -04:00
func (s *stepAttachKeyPair) Cleanup(state multistep.StateBag) {
client := state.Get("client").(*ecs.Client)
config := state.Get("config").(Config)
ui := state.Get("ui").(packer.Ui)
instance := state.Get("instance").(*ecs.InstanceAttributesType)
2018-08-27 09:58:00 -04:00
keyPairName := config.Comm.SSHKeyPair
if keyPairName == "" {
return
}
2017-05-25 22:59:53 -04:00
err := client.DetachKeyPair(&ecs.DetachKeyPairArgs{RegionId: common.Region(config.AlicloudRegion),
KeyPairName: keyPairName, InstanceIds: "[\"" + instance.InstanceId + "\"]"})
if err != nil {
2017-05-25 22:59:53 -04:00
err := fmt.Errorf("Error Detaching keypair %s to instance %s : %s", keyPairName,
instance.InstanceId, err)
state.Put("error", err)
ui.Error(err.Error())
return
}
ui.Message(fmt.Sprintf("Detach keypair %s from instance: %s", keyPairName, instance.InstanceId))
}