forked from aliyun/terraform-provider-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_alicloud_key_pair_attachment.go
159 lines (141 loc) · 4.5 KB
/
resource_alicloud_key_pair_attachment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-alicloud/alicloud/connectivity"
)
func resourceAlicloudKeyPairAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKeyPairAttachmentCreate,
Read: resourceAlicloudKeyPairAttachmentRead,
Delete: resourceAlicloudKeyPairAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"key_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateKeyPairName,
ForceNew: true,
},
"instance_ids": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
ForceNew: true,
},
"force": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudKeyPairAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
keyname := d.Get("key_name").(string)
instanceIds := d.Get("instance_ids").(*schema.Set).List()
force := d.Get("force").(bool)
idsMap := make(map[string]string)
var newIds []string
if force {
ids, _, err := ecsService.QueryInstancesWithKeyPair("", keyname)
if err != nil {
return fmt.Errorf("QueryInstancesWithKeyPair %s got an error: %#v.", keyname, err)
}
for _, id := range ids {
idsMap[id] = id
}
for _, id := range instanceIds {
if _, ok := idsMap[id.(string)]; ok {
continue
}
newIds = append(newIds, id.(string))
}
}
if err := ecsService.AttachKeyPair(keyname, instanceIds); err != nil {
return err
}
if force {
req := ecs.CreateRebootInstanceRequest()
req.ForceStop = requests.NewBoolean(true)
for _, id := range newIds {
req.InstanceId = id
_, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.RebootInstance(req)
})
if err != nil {
return fmt.Errorf("Reboot instance %s got an error: %#v.", id, err)
}
}
for _, id := range newIds {
if err := ecsService.WaitForEcsInstance(id, Running, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s is %s got error: %#v", id, Running, err)
}
}
}
d.SetId(keyname + ":" + convertListToJsonString(instanceIds))
return resourceAlicloudKeyPairAttachmentRead(d, meta)
}
func resourceAlicloudKeyPairAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
keyname := strings.Split(d.Id(), ":")[0]
keypair, err := ecsService.DescribeKeyPair(keyname)
if err != nil {
if NotFoundError(err) || IsExceptedError(err, KeyPairNotFound) {
d.SetId("")
return nil
}
return fmt.Errorf("Error Retrieving KeyPair: %s", err)
}
d.Set("key_name", keypair.KeyPairName)
if ids, ok := d.GetOk("instance_ids"); ok {
d.Set("instance_ids", ids)
} else {
ids, _, err := ecsService.QueryInstancesWithKeyPair("", keyname)
if err != nil {
return fmt.Errorf("Describe instances by keypair %s got an error: %#v.", keyname, err)
}
d.Set("instance_ids", ids)
}
return nil
}
func resourceAlicloudKeyPairAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
keyname := strings.Split(d.Id(), ":")[0]
instanceIds := strings.Split(d.Id(), ":")[1]
req := ecs.CreateDetachKeyPairRequest()
req.KeyPairName = keyname
return resource.Retry(5*time.Minute, func() *resource.RetryError {
req.InstanceIds = instanceIds
_, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DetachKeyPair(req)
})
if err != nil {
return resource.NonRetryableError(fmt.Errorf("Error DetachKeyPair:%#v", err))
}
instance_ids, _, err := ecsService.QueryInstancesWithKeyPair(instanceIds, d.Id())
if err != nil {
return resource.NonRetryableError(err)
}
if len(instance_ids) > 0 {
var ids []interface{}
for _, id := range instance_ids {
ids = append(ids, id)
}
instanceIds = convertListToJsonString(ids)
return resource.RetryableError(fmt.Errorf("Detach Key Pair timeout and got an error: %#v.", err))
}
return nil
})
}