forked from aliyun/terraform-provider-alicloud
/
resource_alicloud_ess_attachment.go
286 lines (250 loc) · 8.74 KB
/
resource_alicloud_ess_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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package alicloud
import (
"fmt"
"time"
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-alicloud/alicloud/connectivity"
)
func resourceAlicloudEssAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssAttachmentCreate,
Read: resourceAliyunEssAttachmentRead,
Update: resourceAliyunEssAttachmentUpdate,
Delete: resourceAliyunEssAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"instance_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
MaxItems: 20,
MinItems: 1,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunEssAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("scaling_group_id").(string))
return resourceAliyunEssAttachmentUpdate(d, meta)
}
func resourceAliyunEssAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
d.Partial(true)
if d.HasChange("instance_ids") {
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
return WrapError(err)
}
if object.LifecycleState == string(Inactive) {
return WrapError(Error("Scaling group current status is %s, please active it before attaching or removing ECS instances.", object.LifecycleState))
} else {
if err := essService.WaitForEssScalingGroup(object.ScalingGroupId, Active, DefaultTimeout); err != nil {
return WrapError(err)
}
}
o, n := d.GetChange("instance_ids")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := convertArrayInterfaceToArrayString(ns.Difference(os).List())
if len(add) > 0 {
request := ess.CreateAttachInstancesRequest()
request.ScalingGroupId = d.Id()
s := reflect.ValueOf(request).Elem()
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
for i, id := range add {
s.FieldByName(fmt.Sprintf("InstanceId%d", i+1)).Set(reflect.ValueOf(id))
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.AttachInstances(request)
})
if err != nil {
if IsExceptedError(err, IncorrectCapacityMaxSize) {
instances, err := essService.DescribeEssAttachment(d.Id(), make([]string, 0))
if err != nil {
return resource.NonRetryableError(err)
}
var autoAdded, attached []string
if len(instances) > 0 {
for _, inst := range instances {
if inst.CreationType == "Attached" {
attached = append(attached, inst.InstanceId)
} else {
autoAdded = append(autoAdded, inst.InstanceId)
}
}
}
if len(add) > object.MaxSize {
return resource.NonRetryableError(WrapError(Error("To attach %d instances, the total capacity will be greater than the scaling group max size %d. "+
"Please enlarge scaling group max size.", len(add), object.MaxSize)))
}
if len(autoAdded) > 0 {
if d.Get("force").(bool) {
if err := essService.EssRemoveInstances(d.Id(), autoAdded); err != nil {
return resource.NonRetryableError(WrapError(err))
}
time.Sleep(5)
return resource.RetryableError(WrapError(err))
} else {
return resource.NonRetryableError(WrapError(Error("To attach the instances, the total capacity will be greater than the scaling group max size %d."+
"Please enlarge scaling group max size or set 'force' to true to remove autocreated instances: %#v.", object.MaxSize, autoAdded)))
}
}
if len(attached) > 0 {
return resource.NonRetryableError(WrapError(Error("To attach the instances, the total capacity will be greater than the scaling group max size %d. "+
"Please enlarge scaling group max size or remove already attached instances: %#v.", object.MaxSize, attached)))
}
}
if IsExceptedError(err, ScalingActivityInProgress) {
time.Sleep(5)
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug(request.GetActionName(), raw)
return nil
}); err != nil {
return WrapError(err)
}
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
instances, err := essService.DescribeEssAttachment(d.Id(), add)
if err != nil {
return resource.NonRetryableError(WrapError(err))
}
if len(instances) < 0 {
return resource.RetryableError(WrapError(Error("There are no ECS instances have been attached.")))
}
for _, inst := range instances {
if inst.LifecycleState != string(InService) {
return resource.RetryableError(WrapError(Error("There are still ECS instances are not %s.", string(InService))))
}
}
return nil
}); err != nil {
return WrapError(err)
}
}
if len(remove) > 0 {
if err := essService.EssRemoveInstances(d.Id(), convertArrayInterfaceToArrayString(remove)); err != nil {
return WrapError(err)
}
}
d.SetPartial("instance_ids")
}
d.Partial(false)
return resourceAliyunEssAttachmentRead(d, meta)
}
func resourceAliyunEssAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssAttachment(d.Id(), make([]string, 0))
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
var instanceIds []string
for _, inst := range object {
instanceIds = append(instanceIds, inst.InstanceId)
}
d.Set("scaling_group_id", object[0].ScalingGroupId)
d.Set("instance_ids", instanceIds)
return nil
}
func resourceAliyunEssAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
removed := convertArrayInterfaceToArrayString(d.Get("instance_ids").(*schema.Set).List())
if len(removed) < 1 {
return nil
}
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
return WrapError(err)
}
if err := essService.WaitForEssScalingGroup(object.ScalingGroupId, Active, DefaultTimeout); err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
request := ess.CreateRemoveInstancesRequest()
request.ScalingGroupId = d.Id()
if len(removed) > 0 {
request.InstanceId = &removed
} else {
return nil
}
raw, err := essService.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.RemoveInstances(request)
})
if err != nil {
if IsExceptedError(err, IncorrectCapacityMinSize) {
instances, err := essService.DescribeEssAttachment(d.Id(), removed)
if len(instances) > 0 {
if object.MinSize == 0 {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(Error("To remove %d instances, the total capacity will be lesser than the scaling group min size %d. "+
"Please shorten scaling group min size and try again.", len(removed), object.MinSize)))
}
}
if IsExceptedErrors(err, []string{ScalingActivityInProgress, IncorrectScalingGroupStatus}) {
time.Sleep(5)
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
if IsExceptedError(err, InvalidScalingGroupIdNotFound) {
return nil
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw)
time.Sleep(3 * time.Second)
instances, err := essService.DescribeEssAttachment(d.Id(), removed)
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(WrapError(err))
}
if len(instances) > 0 {
removed = make([]string, 0)
for _, inst := range instances {
removed = append(removed, inst.InstanceId)
}
return resource.RetryableError(WrapError(Error("There are still ECS instances in the scaling group.")))
}
return nil
}); err != nil {
return WrapError(err)
}
return WrapError(essService.WaitForEssAttachment(d.Id(), Deleted, DefaultTimeout))
}
func convertArrayInterfaceToArrayString(elm []interface{}) (arr []string) {
if len(elm) < 1 {
return
}
for _, e := range elm {
arr = append(arr, e.(string))
}
return
}