forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 2
/
resource_aws_elb.go
945 lines (803 loc) · 26.3 KB
/
resource_aws_elb.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
package aws
import (
"bytes"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsElb() *schema.Resource {
return &schema.Resource{
Create: resourceAwsElbCreate,
Read: resourceAwsElbRead,
Update: resourceAwsElbUpdate,
Delete: resourceAwsElbDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateElbName,
},
"internal": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
},
"cross_zone_load_balancing": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"availability_zones": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
Set: schema.HashString,
},
"instances": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
Set: schema.HashString,
},
"security_groups": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
Set: schema.HashString,
},
"source_security_group": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"source_security_group_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"subnets": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
Set: schema.HashString,
},
"idle_timeout": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 60,
ValidateFunc: validateIntegerInRange(1, 3600),
},
"connection_draining": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"connection_draining_timeout": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 300,
},
"access_logs": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"interval": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 60,
ValidateFunc: validateAccessLogsInterval,
},
"bucket": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"bucket_prefix": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"enabled": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
},
},
"listener": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: validateIntegerInRange(1, 65535),
},
"instance_protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateListenerProtocol,
},
"lb_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: validateIntegerInRange(1, 65535),
},
"lb_protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateListenerProtocol,
},
"ssl_certificate_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
Set: resourceAwsElbListenerHash,
},
"health_check": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"healthy_threshold": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: validateIntegerInRange(2, 10),
},
"unhealthy_threshold": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: validateIntegerInRange(2, 10),
},
"target": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateHeathCheckTarget,
},
"interval": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: validateIntegerInRange(5, 300),
},
"timeout": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: validateIntegerInRange(2, 60),
},
},
},
},
"dns_name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"zone_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsElbCreate(d *schema.ResourceData, meta interface{}) error {
elbconn := meta.(*AWSClient).elbconn
// Expand the "listener" set to aws-sdk-go compat []*elb.Listener
listeners, err := expandListeners(d.Get("listener").(*schema.Set).List())
if err != nil {
return err
}
var elbName string
if v, ok := d.GetOk("name"); ok {
elbName = v.(string)
} else {
elbName = resource.PrefixedUniqueId("tf-lb-")
d.Set("name", elbName)
}
tags := tagsFromMapELB(d.Get("tags").(map[string]interface{}))
// Provision the elb
elbOpts := &elb.CreateLoadBalancerInput{
LoadBalancerName: aws.String(elbName),
Listeners: listeners,
Tags: tags,
}
if scheme, ok := d.GetOk("internal"); ok && scheme.(bool) {
elbOpts.Scheme = aws.String("internal")
}
if v, ok := d.GetOk("availability_zones"); ok {
elbOpts.AvailabilityZones = expandStringList(v.(*schema.Set).List())
}
if v, ok := d.GetOk("security_groups"); ok {
elbOpts.SecurityGroups = expandStringList(v.(*schema.Set).List())
}
if v, ok := d.GetOk("subnets"); ok {
elbOpts.Subnets = expandStringList(v.(*schema.Set).List())
}
log.Printf("[DEBUG] ELB create configuration: %#v", elbOpts)
err = resource.Retry(1*time.Minute, func() *resource.RetryError {
_, err := elbconn.CreateLoadBalancer(elbOpts)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Check for IAM SSL Cert error, eventual consistancy issue
if awsErr.Code() == "CertificateNotFound" {
return resource.RetryableError(
fmt.Errorf("[WARN] Error creating ELB Listener with SSL Cert, retrying: %s", err))
}
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return err
}
// Assign the elb's unique identifier for use later
d.SetId(elbName)
log.Printf("[INFO] ELB ID: %s", d.Id())
// Enable partial mode and record what we set
d.Partial(true)
d.SetPartial("name")
d.SetPartial("internal")
d.SetPartial("availability_zones")
d.SetPartial("listener")
d.SetPartial("security_groups")
d.SetPartial("subnets")
d.Set("tags", tagsToMapELB(tags))
return resourceAwsElbUpdate(d, meta)
}
func resourceAwsElbRead(d *schema.ResourceData, meta interface{}) error {
elbconn := meta.(*AWSClient).elbconn
elbName := d.Id()
// Retrieve the ELB properties for updating the state
describeElbOpts := &elb.DescribeLoadBalancersInput{
LoadBalancerNames: []*string{aws.String(elbName)},
}
describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts)
if err != nil {
if isLoadBalancerNotFound(err) {
// The ELB is gone now, so just remove it from the state
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving ELB: %s", err)
}
if len(describeResp.LoadBalancerDescriptions) != 1 {
return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions)
}
describeAttrsOpts := &elb.DescribeLoadBalancerAttributesInput{
LoadBalancerName: aws.String(elbName),
}
describeAttrsResp, err := elbconn.DescribeLoadBalancerAttributes(describeAttrsOpts)
if err != nil {
if isLoadBalancerNotFound(err) {
// The ELB is gone now, so just remove it from the state
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving ELB: %s", err)
}
lbAttrs := describeAttrsResp.LoadBalancerAttributes
lb := describeResp.LoadBalancerDescriptions[0]
d.Set("name", lb.LoadBalancerName)
d.Set("dns_name", lb.DNSName)
d.Set("zone_id", lb.CanonicalHostedZoneNameID)
var scheme bool
if lb.Scheme != nil {
scheme = *lb.Scheme == "internal"
}
d.Set("internal", scheme)
d.Set("availability_zones", flattenStringList(lb.AvailabilityZones))
d.Set("instances", flattenInstances(lb.Instances))
d.Set("listener", flattenListeners(lb.ListenerDescriptions))
d.Set("security_groups", flattenStringList(lb.SecurityGroups))
if lb.SourceSecurityGroup != nil {
group := lb.SourceSecurityGroup.GroupName
if lb.SourceSecurityGroup.OwnerAlias != nil && *lb.SourceSecurityGroup.OwnerAlias != "" {
group = aws.String(*lb.SourceSecurityGroup.OwnerAlias + "/" + *lb.SourceSecurityGroup.GroupName)
}
d.Set("source_security_group", group)
// Manually look up the ELB Security Group ID, since it's not provided
var elbVpc string
if lb.VPCId != nil {
elbVpc = *lb.VPCId
sgId, err := sourceSGIdByName(meta, *lb.SourceSecurityGroup.GroupName, elbVpc)
if err != nil {
return fmt.Errorf("[WARN] Error looking up ELB Security Group ID: %s", err)
} else {
d.Set("source_security_group_id", sgId)
}
}
}
d.Set("subnets", flattenStringList(lb.Subnets))
d.Set("idle_timeout", lbAttrs.ConnectionSettings.IdleTimeout)
d.Set("connection_draining", lbAttrs.ConnectionDraining.Enabled)
d.Set("connection_draining_timeout", lbAttrs.ConnectionDraining.Timeout)
d.Set("cross_zone_load_balancing", lbAttrs.CrossZoneLoadBalancing.Enabled)
if lbAttrs.AccessLog != nil {
if err := d.Set("access_logs", flattenAccessLog(lbAttrs.AccessLog)); err != nil {
return err
}
}
resp, err := elbconn.DescribeTags(&elb.DescribeTagsInput{
LoadBalancerNames: []*string{lb.LoadBalancerName},
})
var et []*elb.Tag
if len(resp.TagDescriptions) > 0 {
et = resp.TagDescriptions[0].Tags
}
d.Set("tags", tagsToMapELB(et))
// There's only one health check, so save that to state as we
// currently can
if *lb.HealthCheck.Target != "" {
d.Set("health_check", flattenHealthCheck(lb.HealthCheck))
}
return nil
}
func resourceAwsElbUpdate(d *schema.ResourceData, meta interface{}) error {
elbconn := meta.(*AWSClient).elbconn
d.Partial(true)
if d.HasChange("listener") {
o, n := d.GetChange("listener")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove, _ := expandListeners(os.Difference(ns).List())
add, _ := expandListeners(ns.Difference(os).List())
if len(remove) > 0 {
ports := make([]*int64, 0, len(remove))
for _, listener := range remove {
ports = append(ports, listener.LoadBalancerPort)
}
deleteListenersOpts := &elb.DeleteLoadBalancerListenersInput{
LoadBalancerName: aws.String(d.Id()),
LoadBalancerPorts: ports,
}
log.Printf("[DEBUG] ELB Delete Listeners opts: %s", deleteListenersOpts)
_, err := elbconn.DeleteLoadBalancerListeners(deleteListenersOpts)
if err != nil {
return fmt.Errorf("Failure removing outdated ELB listeners: %s", err)
}
}
if len(add) > 0 {
createListenersOpts := &elb.CreateLoadBalancerListenersInput{
LoadBalancerName: aws.String(d.Id()),
Listeners: add,
}
// Occasionally AWS will error with a 'duplicate listener', without any
// other listeners on the ELB. Retry here to eliminate that.
err := resource.Retry(1*time.Minute, func() *resource.RetryError {
log.Printf("[DEBUG] ELB Create Listeners opts: %s", createListenersOpts)
if _, err := elbconn.CreateLoadBalancerListeners(createListenersOpts); err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "DuplicateListener" {
log.Printf("[DEBUG] Duplicate listener found for ELB (%s), retrying", d.Id())
return resource.RetryableError(awsErr)
}
if awsErr.Code() == "CertificateNotFound" && strings.Contains(awsErr.Message(), "Server Certificate not found for the key: arn") {
log.Printf("[DEBUG] SSL Cert not found for given ARN, retrying")
return resource.RetryableError(awsErr)
}
}
// Didn't recognize the error, so shouldn't retry.
return resource.NonRetryableError(err)
}
// Successful creation
return nil
})
if err != nil {
return fmt.Errorf("Failure adding new or updated ELB listeners: %s", err)
}
}
d.SetPartial("listener")
}
// If we currently have instances, or did have instances,
// we want to figure out what to add and remove from the load
// balancer
if d.HasChange("instances") {
o, n := d.GetChange("instances")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := expandInstanceString(os.Difference(ns).List())
add := expandInstanceString(ns.Difference(os).List())
if len(add) > 0 {
registerInstancesOpts := elb.RegisterInstancesWithLoadBalancerInput{
LoadBalancerName: aws.String(d.Id()),
Instances: add,
}
_, err := elbconn.RegisterInstancesWithLoadBalancer(®isterInstancesOpts)
if err != nil {
return fmt.Errorf("Failure registering instances with ELB: %s", err)
}
}
if len(remove) > 0 {
deRegisterInstancesOpts := elb.DeregisterInstancesFromLoadBalancerInput{
LoadBalancerName: aws.String(d.Id()),
Instances: remove,
}
_, err := elbconn.DeregisterInstancesFromLoadBalancer(&deRegisterInstancesOpts)
if err != nil {
return fmt.Errorf("Failure deregistering instances from ELB: %s", err)
}
}
d.SetPartial("instances")
}
if d.HasChange("cross_zone_load_balancing") || d.HasChange("idle_timeout") || d.HasChange("access_logs") {
attrs := elb.ModifyLoadBalancerAttributesInput{
LoadBalancerName: aws.String(d.Get("name").(string)),
LoadBalancerAttributes: &elb.LoadBalancerAttributes{
CrossZoneLoadBalancing: &elb.CrossZoneLoadBalancing{
Enabled: aws.Bool(d.Get("cross_zone_load_balancing").(bool)),
},
ConnectionSettings: &elb.ConnectionSettings{
IdleTimeout: aws.Int64(int64(d.Get("idle_timeout").(int))),
},
},
}
logs := d.Get("access_logs").([]interface{})
if len(logs) > 1 {
return fmt.Errorf("Only one access logs config per ELB is supported")
} else if len(logs) == 1 {
log := logs[0].(map[string]interface{})
accessLog := &elb.AccessLog{
Enabled: aws.Bool(log["enabled"].(bool)),
EmitInterval: aws.Int64(int64(log["interval"].(int))),
S3BucketName: aws.String(log["bucket"].(string)),
}
if log["bucket_prefix"] != "" {
accessLog.S3BucketPrefix = aws.String(log["bucket_prefix"].(string))
}
attrs.LoadBalancerAttributes.AccessLog = accessLog
} else if len(logs) == 0 {
// disable access logs
attrs.LoadBalancerAttributes.AccessLog = &elb.AccessLog{
Enabled: aws.Bool(false),
}
}
log.Printf("[DEBUG] ELB Modify Load Balancer Attributes Request: %#v", attrs)
_, err := elbconn.ModifyLoadBalancerAttributes(&attrs)
if err != nil {
return fmt.Errorf("Failure configuring ELB attributes: %s", err)
}
d.SetPartial("cross_zone_load_balancing")
d.SetPartial("idle_timeout")
d.SetPartial("connection_draining_timeout")
}
// We have to do these changes separately from everything else since
// they have some weird undocumented rules. You can't set the timeout
// without having connection draining to true, so we set that to true,
// set the timeout, then reset it to false if requested.
if d.HasChange("connection_draining") || d.HasChange("connection_draining_timeout") {
// We do timeout changes first since they require us to set draining
// to true for a hot second.
if d.HasChange("connection_draining_timeout") {
attrs := elb.ModifyLoadBalancerAttributesInput{
LoadBalancerName: aws.String(d.Get("name").(string)),
LoadBalancerAttributes: &elb.LoadBalancerAttributes{
ConnectionDraining: &elb.ConnectionDraining{
Enabled: aws.Bool(true),
Timeout: aws.Int64(int64(d.Get("connection_draining_timeout").(int))),
},
},
}
_, err := elbconn.ModifyLoadBalancerAttributes(&attrs)
if err != nil {
return fmt.Errorf("Failure configuring ELB attributes: %s", err)
}
d.SetPartial("connection_draining_timeout")
}
// Then we always set connection draining even if there is no change.
// This lets us reset to "false" if requested even with a timeout
// change.
attrs := elb.ModifyLoadBalancerAttributesInput{
LoadBalancerName: aws.String(d.Get("name").(string)),
LoadBalancerAttributes: &elb.LoadBalancerAttributes{
ConnectionDraining: &elb.ConnectionDraining{
Enabled: aws.Bool(d.Get("connection_draining").(bool)),
},
},
}
_, err := elbconn.ModifyLoadBalancerAttributes(&attrs)
if err != nil {
return fmt.Errorf("Failure configuring ELB attributes: %s", err)
}
d.SetPartial("connection_draining")
}
if d.HasChange("health_check") {
hc := d.Get("health_check").([]interface{})
if len(hc) > 0 {
check := hc[0].(map[string]interface{})
configureHealthCheckOpts := elb.ConfigureHealthCheckInput{
LoadBalancerName: aws.String(d.Id()),
HealthCheck: &elb.HealthCheck{
HealthyThreshold: aws.Int64(int64(check["healthy_threshold"].(int))),
UnhealthyThreshold: aws.Int64(int64(check["unhealthy_threshold"].(int))),
Interval: aws.Int64(int64(check["interval"].(int))),
Target: aws.String(check["target"].(string)),
Timeout: aws.Int64(int64(check["timeout"].(int))),
},
}
_, err := elbconn.ConfigureHealthCheck(&configureHealthCheckOpts)
if err != nil {
return fmt.Errorf("Failure configuring health check for ELB: %s", err)
}
d.SetPartial("health_check")
}
}
if d.HasChange("security_groups") {
groups := d.Get("security_groups").(*schema.Set).List()
applySecurityGroupsOpts := elb.ApplySecurityGroupsToLoadBalancerInput{
LoadBalancerName: aws.String(d.Id()),
SecurityGroups: expandStringList(groups),
}
_, err := elbconn.ApplySecurityGroupsToLoadBalancer(&applySecurityGroupsOpts)
if err != nil {
return fmt.Errorf("Failure applying security groups to ELB: %s", err)
}
d.SetPartial("security_groups")
}
if d.HasChange("availability_zones") {
o, n := d.GetChange("availability_zones")
os := o.(*schema.Set)
ns := n.(*schema.Set)
removed := expandStringList(os.Difference(ns).List())
added := expandStringList(ns.Difference(os).List())
if len(added) > 0 {
enableOpts := &elb.EnableAvailabilityZonesForLoadBalancerInput{
LoadBalancerName: aws.String(d.Id()),
AvailabilityZones: added,
}
log.Printf("[DEBUG] ELB enable availability zones opts: %s", enableOpts)
_, err := elbconn.EnableAvailabilityZonesForLoadBalancer(enableOpts)
if err != nil {
return fmt.Errorf("Failure enabling ELB availability zones: %s", err)
}
}
if len(removed) > 0 {
disableOpts := &elb.DisableAvailabilityZonesForLoadBalancerInput{
LoadBalancerName: aws.String(d.Id()),
AvailabilityZones: removed,
}
log.Printf("[DEBUG] ELB disable availability zones opts: %s", disableOpts)
_, err := elbconn.DisableAvailabilityZonesForLoadBalancer(disableOpts)
if err != nil {
return fmt.Errorf("Failure disabling ELB availability zones: %s", err)
}
}
d.SetPartial("availability_zones")
}
if d.HasChange("subnets") {
o, n := d.GetChange("subnets")
os := o.(*schema.Set)
ns := n.(*schema.Set)
removed := expandStringList(os.Difference(ns).List())
added := expandStringList(ns.Difference(os).List())
if len(removed) > 0 {
detachOpts := &elb.DetachLoadBalancerFromSubnetsInput{
LoadBalancerName: aws.String(d.Id()),
Subnets: removed,
}
log.Printf("[DEBUG] ELB detach subnets opts: %s", detachOpts)
_, err := elbconn.DetachLoadBalancerFromSubnets(detachOpts)
if err != nil {
return fmt.Errorf("Failure removing ELB subnets: %s", err)
}
}
if len(added) > 0 {
attachOpts := &elb.AttachLoadBalancerToSubnetsInput{
LoadBalancerName: aws.String(d.Id()),
Subnets: added,
}
log.Printf("[DEBUG] ELB attach subnets opts: %s", attachOpts)
err := resource.Retry(1*time.Minute, func() *resource.RetryError {
_, err := elbconn.AttachLoadBalancerToSubnets(attachOpts)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// eventually consistent issue with removing a subnet in AZ1 and
// immediately adding a new one in the same AZ
if awsErr.Code() == "InvalidConfigurationRequest" && strings.Contains(awsErr.Message(), "cannot be attached to multiple subnets in the same AZ") {
log.Printf("[DEBUG] retrying az association")
return resource.RetryableError(awsErr)
}
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Failure adding ELB subnets: %s", err)
}
}
d.SetPartial("subnets")
}
if err := setTagsELB(elbconn, d); err != nil {
return err
}
d.SetPartial("tags")
d.Partial(false)
return resourceAwsElbRead(d, meta)
}
func resourceAwsElbDelete(d *schema.ResourceData, meta interface{}) error {
elbconn := meta.(*AWSClient).elbconn
log.Printf("[INFO] Deleting ELB: %s", d.Id())
// Destroy the load balancer
deleteElbOpts := elb.DeleteLoadBalancerInput{
LoadBalancerName: aws.String(d.Id()),
}
if _, err := elbconn.DeleteLoadBalancer(&deleteElbOpts); err != nil {
return fmt.Errorf("Error deleting ELB: %s", err)
}
return nil
}
func resourceAwsElbListenerHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%d-", m["instance_port"].(int)))
buf.WriteString(fmt.Sprintf("%s-",
strings.ToLower(m["instance_protocol"].(string))))
buf.WriteString(fmt.Sprintf("%d-", m["lb_port"].(int)))
buf.WriteString(fmt.Sprintf("%s-",
strings.ToLower(m["lb_protocol"].(string))))
if v, ok := m["ssl_certificate_id"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
return hashcode.String(buf.String())
}
func isLoadBalancerNotFound(err error) bool {
elberr, ok := err.(awserr.Error)
return ok && elberr.Code() == "LoadBalancerNotFound"
}
func sourceSGIdByName(meta interface{}, sg, vpcId string) (string, error) {
conn := meta.(*AWSClient).ec2conn
var filters []*ec2.Filter
var sgFilterName, sgFilterVPCID *ec2.Filter
sgFilterName = &ec2.Filter{
Name: aws.String("group-name"),
Values: []*string{aws.String(sg)},
}
if vpcId != "" {
sgFilterVPCID = &ec2.Filter{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(vpcId)},
}
}
filters = append(filters, sgFilterName)
if sgFilterVPCID != nil {
filters = append(filters, sgFilterVPCID)
}
req := &ec2.DescribeSecurityGroupsInput{
Filters: filters,
}
resp, err := conn.DescribeSecurityGroups(req)
if err != nil {
if ec2err, ok := err.(awserr.Error); ok {
if ec2err.Code() == "InvalidSecurityGroupID.NotFound" ||
ec2err.Code() == "InvalidGroup.NotFound" {
resp = nil
err = nil
}
}
if err != nil {
log.Printf("Error on ELB SG look up: %s", err)
return "", err
}
}
if resp == nil || len(resp.SecurityGroups) == 0 {
return "", fmt.Errorf("No security groups found for name %s and vpc id %s", sg, vpcId)
}
group := resp.SecurityGroups[0]
return *group.GroupId, nil
}
func validateAccessLogsInterval(v interface{}, k string) (ws []string, errors []error) {
value := v.(int)
// Check if the value is either 5 or 60 (minutes).
if value != 5 && value != 60 {
errors = append(errors, fmt.Errorf(
"%q contains an invalid Access Logs interval \"%d\". "+
"Valid intervals are either 5 or 60 (minutes).",
k, value))
}
return
}
func validateHeathCheckTarget(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
// Parse the Health Check target value.
matches := regexp.MustCompile(`\A(\w+):(\d+)(.+)?\z`).FindStringSubmatch(value)
// Check if the value contains a valid target.
if matches == nil || len(matches) < 1 {
errors = append(errors, fmt.Errorf(
"%q contains an invalid Health Check: %s",
k, value))
// Invalid target? Return immediately,
// there is no need to collect other
// errors.
return
}
// Check if the value contains a valid protocol.
if !isValidProtocol(matches[1]) {
errors = append(errors, fmt.Errorf(
"%q contains an invalid Health Check protocol %q. "+
"Valid protocols are either %q, %q, %q, or %q.",
k, matches[1], "TCP", "SSL", "HTTP", "HTTPS"))
}
// Check if the value contains a valid port range.
port, _ := strconv.Atoi(matches[2])
if port < 1 || port > 65535 {
errors = append(errors, fmt.Errorf(
"%q contains an invalid Health Check target port \"%d\". "+
"Valid port is in the range from 1 to 65535 inclusive.",
k, port))
}
switch strings.ToLower(matches[1]) {
case "tcp", "ssl":
// Check if value is in the form <PROTOCOL>:<PORT> for TCP and/or SSL.
if matches[3] != "" {
errors = append(errors, fmt.Errorf(
"%q cannot contain a path in the Health Check target: %s",
k, value))
}
break
case "http", "https":
// Check if value is in the form <PROTOCOL>:<PORT>/<PATH> for HTTP and/or HTTPS.
if matches[3] == "" {
errors = append(errors, fmt.Errorf(
"%q must contain a path in the Health Check target: %s",
k, value))
}
// Cannot be longer than 1024 multibyte characters.
if len([]rune(matches[3])) > 1024 {
errors = append(errors, fmt.Errorf("%q cannot contain a path longer "+
"than 1024 characters in the Health Check target: %s",
k, value))
}
break
}
return
}
func validateListenerProtocol(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if !isValidProtocol(value) {
errors = append(errors, fmt.Errorf(
"%q contains an invalid Listener protocol %q. "+
"Valid protocols are either %q, %q, %q, or %q.",
k, value, "TCP", "SSL", "HTTP", "HTTPS"))
}
return
}
func isValidProtocol(s string) bool {
if s == "" {
return false
}
s = strings.ToLower(s)
validProtocols := map[string]bool{
"http": true,
"https": true,
"ssl": true,
"tcp": true,
}
if _, ok := validProtocols[s]; !ok {
return false
}
return true
}