github.phpd.cn/hashicorp/packer@v1.3.2/builder/alicloud/ecs/step_attach_keypair.go (about) 1 package ecs 2 3 import ( 4 "context" 5 "fmt" 6 7 "time" 8 9 "github.com/denverdino/aliyungo/common" 10 "github.com/denverdino/aliyungo/ecs" 11 "github.com/hashicorp/packer/helper/multistep" 12 "github.com/hashicorp/packer/packer" 13 ) 14 15 type stepAttachKeyPair struct { 16 } 17 18 func (s *stepAttachKeyPair) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 19 ui := state.Get("ui").(packer.Ui) 20 client := state.Get("client").(*ecs.Client) 21 config := state.Get("config").(*Config) 22 instance := state.Get("instance").(*ecs.InstanceAttributesType) 23 timeoutPoint := time.Now().Add(120 * time.Second) 24 keyPairName := config.Comm.SSHKeyPairName 25 if keyPairName == "" { 26 return multistep.ActionContinue 27 } 28 for { 29 err := client.AttachKeyPair(&ecs.AttachKeyPairArgs{RegionId: common.Region(config.AlicloudRegion), 30 KeyPairName: keyPairName, InstanceIds: "[\"" + instance.InstanceId + "\"]"}) 31 if err != nil { 32 e, _ := err.(*common.Error) 33 if (!(e.Code == "MissingParameter" || e.Code == "DependencyViolation.WindowsInstance" || 34 e.Code == "InvalidKeyPairName.NotFound" || e.Code == "InvalidRegionId.NotFound")) && 35 time.Now().Before(timeoutPoint) { 36 time.Sleep(5 * time.Second) 37 continue 38 } 39 err := fmt.Errorf("Error attaching keypair %s to instance %s : %s", 40 keyPairName, instance.InstanceId, err) 41 state.Put("error", err) 42 ui.Error(err.Error()) 43 return multistep.ActionHalt 44 } 45 break 46 } 47 48 ui.Message(fmt.Sprintf("Attach keypair %s to instance: %s", keyPairName, instance.InstanceId)) 49 50 return multistep.ActionContinue 51 } 52 53 func (s *stepAttachKeyPair) Cleanup(state multistep.StateBag) { 54 client := state.Get("client").(*ecs.Client) 55 config := state.Get("config").(*Config) 56 ui := state.Get("ui").(packer.Ui) 57 instance := state.Get("instance").(*ecs.InstanceAttributesType) 58 keyPairName := config.Comm.SSHKeyPairName 59 if keyPairName == "" { 60 return 61 } 62 63 err := client.DetachKeyPair(&ecs.DetachKeyPairArgs{RegionId: common.Region(config.AlicloudRegion), 64 KeyPairName: keyPairName, InstanceIds: "[\"" + instance.InstanceId + "\"]"}) 65 if err != nil { 66 err := fmt.Errorf("Error Detaching keypair %s to instance %s : %s", keyPairName, 67 instance.InstanceId, err) 68 state.Put("error", err) 69 ui.Error(err.Error()) 70 return 71 } 72 73 ui.Message(fmt.Sprintf("Detach keypair %s from instance: %s", keyPairName, instance.InstanceId)) 74 75 }