forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_autoscaling_group.go
363 lines (303 loc) · 10.1 KB
/
resource_aws_autoscaling_group.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package aws
import (
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/autoscaling"
)
func resourceAwsAutoscalingGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAwsAutoscalingGroupCreate,
Read: resourceAwsAutoscalingGroupRead,
Update: resourceAwsAutoscalingGroupUpdate,
Delete: resourceAwsAutoscalingGroupDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"launch_configuration": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"desired_capacity": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"min_size": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"max_size": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"default_cooldown": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"force_delete": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"health_check_grace_period": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"health_check_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"availability_zones": &schema.Schema{
Type: schema.TypeSet,
Required: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
"load_balancers": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
"vpc_zone_identifier": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
"termination_policies": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
"tag": autoscalingTagsSchema(),
},
}
}
func resourceAwsAutoscalingGroupCreate(d *schema.ResourceData, meta interface{}) error {
autoscalingconn := meta.(*AWSClient).autoscalingconn
var autoScalingGroupOpts autoscaling.CreateAutoScalingGroupType
autoScalingGroupOpts.AutoScalingGroupName = aws.String(d.Get("name").(string))
autoScalingGroupOpts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string))
autoScalingGroupOpts.MinSize = aws.Integer(d.Get("min_size").(int))
autoScalingGroupOpts.MaxSize = aws.Integer(d.Get("max_size").(int))
autoScalingGroupOpts.AvailabilityZones = expandStringList(
d.Get("availability_zones").(*schema.Set).List())
if v, ok := d.GetOk("tag"); ok {
autoScalingGroupOpts.Tags = autoscalingTagsFromMap(
setToMapByKey(v.(*schema.Set), "key"), d.Get("name").(string))
}
if v, ok := d.GetOk("default_cooldown"); ok {
autoScalingGroupOpts.DefaultCooldown = aws.Integer(v.(int))
}
if v, ok := d.GetOk("health_check_type"); ok && v.(string) != "" {
autoScalingGroupOpts.HealthCheckType = aws.String(v.(string))
}
if v, ok := d.GetOk("desired_capacity"); ok {
autoScalingGroupOpts.DesiredCapacity = aws.Integer(v.(int))
}
if v, ok := d.GetOk("health_check_grace_period"); ok {
autoScalingGroupOpts.HealthCheckGracePeriod = aws.Integer(v.(int))
}
if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 {
autoScalingGroupOpts.LoadBalancerNames = expandStringList(
v.(*schema.Set).List())
}
if v, ok := d.GetOk("vpc_zone_identifier"); ok && v.(*schema.Set).Len() > 0 {
exp := expandStringList(v.(*schema.Set).List())
autoScalingGroupOpts.VPCZoneIdentifier = aws.String(strings.Join(exp, ","))
}
if v, ok := d.GetOk("termination_policies"); ok && v.(*schema.Set).Len() > 0 {
autoScalingGroupOpts.TerminationPolicies = expandStringList(
v.(*schema.Set).List())
}
log.Printf("[DEBUG] AutoScaling Group create configuration: %#v", autoScalingGroupOpts)
err := autoscalingconn.CreateAutoScalingGroup(&autoScalingGroupOpts)
if err != nil {
return fmt.Errorf("Error creating Autoscaling Group: %s", err)
}
d.SetId(d.Get("name").(string))
log.Printf("[INFO] AutoScaling Group ID: %s", d.Id())
return resourceAwsAutoscalingGroupRead(d, meta)
}
func resourceAwsAutoscalingGroupRead(d *schema.ResourceData, meta interface{}) error {
g, err := getAwsAutoscalingGroup(d, meta)
if err != nil {
return err
}
if g == nil {
return nil
}
d.Set("availability_zones", g.AvailabilityZones)
d.Set("default_cooldown", g.DefaultCooldown)
d.Set("desired_capacity", g.DesiredCapacity)
d.Set("health_check_grace_period", g.HealthCheckGracePeriod)
d.Set("health_check_type", g.HealthCheckType)
d.Set("launch_configuration", g.LaunchConfigurationName)
d.Set("load_balancers", g.LoadBalancerNames)
d.Set("min_size", g.MinSize)
d.Set("max_size", g.MaxSize)
d.Set("name", g.AutoScalingGroupName)
d.Set("tag", g.Tags)
d.Set("vpc_zone_identifier", strings.Split(*g.VPCZoneIdentifier, ","))
d.Set("termination_policies", g.TerminationPolicies)
return nil
}
func resourceAwsAutoscalingGroupUpdate(d *schema.ResourceData, meta interface{}) error {
autoscalingconn := meta.(*AWSClient).autoscalingconn
opts := autoscaling.UpdateAutoScalingGroupType{
AutoScalingGroupName: aws.String(d.Id()),
}
if d.HasChange("desired_capacity") {
opts.DesiredCapacity = aws.Integer(d.Get("desired_capacity").(int))
}
if d.HasChange("launch_configuration") {
opts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string))
}
if d.HasChange("min_size") {
opts.MinSize = aws.Integer(d.Get("min_size").(int))
}
if d.HasChange("max_size") {
opts.MaxSize = aws.Integer(d.Get("max_size").(int))
}
if err := setAutoscalingTags(autoscalingconn, d); err != nil {
return err
} else {
d.SetPartial("tag")
}
log.Printf("[DEBUG] AutoScaling Group update configuration: %#v", opts)
err := autoscalingconn.UpdateAutoScalingGroup(&opts)
if err != nil {
d.Partial(true)
return fmt.Errorf("Error updating Autoscaling group: %s", err)
}
return resourceAwsAutoscalingGroupRead(d, meta)
}
func resourceAwsAutoscalingGroupDelete(d *schema.ResourceData, meta interface{}) error {
autoscalingconn := meta.(*AWSClient).autoscalingconn
// Read the autoscaling group first. If it doesn't exist, we're done.
// We need the group in order to check if there are instances attached.
// If so, we need to remove those first.
g, err := getAwsAutoscalingGroup(d, meta)
if err != nil {
return err
}
if g == nil {
return nil
}
if len(g.Instances) > 0 || *g.DesiredCapacity > 0 {
if err := resourceAwsAutoscalingGroupDrain(d, meta); err != nil {
return err
}
}
log.Printf("[DEBUG] AutoScaling Group destroy: %v", d.Id())
deleteopts := autoscaling.DeleteAutoScalingGroupType{AutoScalingGroupName: aws.String(d.Id())}
// You can force an autoscaling group to delete
// even if it's in the process of scaling a resource.
// Normally, you would set the min-size and max-size to 0,0
// and then delete the group. This bypasses that and leaves
// resources potentially dangling.
if d.Get("force_delete").(bool) {
deleteopts.ForceDelete = aws.Boolean(true)
}
if err := autoscalingconn.DeleteAutoScalingGroup(&deleteopts); err != nil {
autoscalingerr, ok := err.(aws.APIError)
if ok && autoscalingerr.Code == "InvalidGroup.NotFound" {
return nil
}
return err
}
return resource.Retry(5*time.Minute, func() error {
if g, _ = getAwsAutoscalingGroup(d, meta); g != nil {
return fmt.Errorf("Auto Scaling Group still exists")
}
return nil
})
}
func getAwsAutoscalingGroup(
d *schema.ResourceData,
meta interface{}) (*autoscaling.AutoScalingGroup, error) {
autoscalingconn := meta.(*AWSClient).autoscalingconn
describeOpts := autoscaling.AutoScalingGroupNamesType{
AutoScalingGroupNames: []string{d.Id()},
}
log.Printf("[DEBUG] AutoScaling Group describe configuration: %#v", describeOpts)
describeGroups, err := autoscalingconn.DescribeAutoScalingGroups(&describeOpts)
if err != nil {
autoscalingerr, ok := err.(aws.APIError)
if ok && autoscalingerr.Code == "InvalidGroup.NotFound" {
d.SetId("")
return nil, nil
}
return nil, fmt.Errorf("Error retrieving AutoScaling groups: %s", err)
}
// Search for the autoscaling group
for idx, asc := range describeGroups.AutoScalingGroups {
if *asc.AutoScalingGroupName == d.Id() {
return &describeGroups.AutoScalingGroups[idx], nil
}
}
// ASG not found
d.SetId("")
return nil, nil
}
func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error {
autoscalingconn := meta.(*AWSClient).autoscalingconn
// First, set the capacity to zero so the group will drain
log.Printf("[DEBUG] Reducing autoscaling group capacity to zero")
opts := autoscaling.UpdateAutoScalingGroupType{
AutoScalingGroupName: aws.String(d.Id()),
DesiredCapacity: aws.Integer(0),
MinSize: aws.Integer(0),
MaxSize: aws.Integer(0),
}
if err := autoscalingconn.UpdateAutoScalingGroup(&opts); err != nil {
return fmt.Errorf("Error setting capacity to zero to drain: %s", err)
}
// Next, wait for the autoscale group to drain
log.Printf("[DEBUG] Waiting for group to have zero instances")
return resource.Retry(10*time.Minute, func() error {
g, err := getAwsAutoscalingGroup(d, meta)
if err != nil {
return resource.RetryError{Err: err}
}
if g == nil {
return nil
}
if len(g.Instances) == 0 {
return nil
}
return fmt.Errorf("group still has %d instances", len(g.Instances))
})
}