-
Notifications
You must be signed in to change notification settings - Fork 9.2k
/
resource_aws_security_group.go
1517 lines (1312 loc) · 41.8 KB
/
resource_aws_security_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
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package aws
import (
"bytes"
"fmt"
"log"
"sort"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
func resourceAwsSecurityGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAwsSecurityGroupCreate,
Read: resourceAwsSecurityGroupRead,
Update: resourceAwsSecurityGroupUpdate,
Delete: resourceAwsSecurityGroupDelete,
Importer: &schema.ResourceImporter{
State: resourceAwsSecurityGroupImportState,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
SchemaVersion: 1,
MigrateState: resourceAwsSecurityGroupMigrateState,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validation.StringLenBetween(0, 255),
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"name"},
ValidateFunc: validation.StringLenBetween(0, 100),
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Managed by Terraform",
ValidateFunc: validation.StringLenBetween(0, 255),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"ingress": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_port": {
Type: schema.TypeInt,
Required: true,
},
"to_port": {
Type: schema.TypeInt,
Required: true,
},
"protocol": {
Type: schema.TypeString,
Required: true,
StateFunc: protocolStateFunc,
},
"cidr_blocks": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateCIDRNetworkAddress,
},
},
"ipv6_cidr_blocks": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateCIDRNetworkAddress,
},
},
"prefix_list_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"self": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateSecurityGroupRuleDescription,
},
},
},
Set: resourceAwsSecurityGroupRuleHash,
},
"egress": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_port": {
Type: schema.TypeInt,
Required: true,
},
"to_port": {
Type: schema.TypeInt,
Required: true,
},
"protocol": {
Type: schema.TypeString,
Required: true,
StateFunc: protocolStateFunc,
},
"cidr_blocks": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateCIDRNetworkAddress,
},
},
"ipv6_cidr_blocks": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateCIDRNetworkAddress,
},
},
"prefix_list_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"self": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateSecurityGroupRuleDescription,
},
},
},
Set: resourceAwsSecurityGroupRuleHash,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"revoke_rules_on_delete": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
},
}
}
func resourceAwsSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
securityGroupOpts := &ec2.CreateSecurityGroupInput{}
if v, ok := d.GetOk("vpc_id"); ok {
securityGroupOpts.VpcId = aws.String(v.(string))
}
if v := d.Get("description"); v != nil {
securityGroupOpts.Description = aws.String(v.(string))
}
var groupName string
if v, ok := d.GetOk("name"); ok {
groupName = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
groupName = resource.PrefixedUniqueId(v.(string))
} else {
groupName = resource.UniqueId()
}
securityGroupOpts.GroupName = aws.String(groupName)
var err error
log.Printf(
"[DEBUG] Security Group create configuration: %#v", securityGroupOpts)
createResp, err := conn.CreateSecurityGroup(securityGroupOpts)
if err != nil {
return fmt.Errorf("Error creating Security Group: %s", err)
}
d.SetId(*createResp.GroupId)
log.Printf("[INFO] Security Group ID: %s", d.Id())
// Wait for the security group to truly exist
resp, err := waitForSgToExist(conn, d.Id(), d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf(
"Error waiting for Security Group (%s) to become available: %s",
d.Id(), err)
}
if err := setTags(conn, d); err != nil {
return err
}
// AWS defaults all Security Groups to have an ALLOW ALL egress rule. Here we
// revoke that rule, so users don't unknowingly have/use it.
group := resp.(*ec2.SecurityGroup)
if group.VpcId != nil && *group.VpcId != "" {
log.Printf("[DEBUG] Revoking default egress rule for Security Group for %s", d.Id())
req := &ec2.RevokeSecurityGroupEgressInput{
GroupId: createResp.GroupId,
IpPermissions: []*ec2.IpPermission{
{
FromPort: aws.Int64(int64(0)),
ToPort: aws.Int64(int64(0)),
IpRanges: []*ec2.IpRange{
{
CidrIp: aws.String("0.0.0.0/0"),
},
},
IpProtocol: aws.String("-1"),
},
},
}
if _, err = conn.RevokeSecurityGroupEgress(req); err != nil {
return fmt.Errorf(
"Error revoking default egress rule for Security Group (%s): %s",
d.Id(), err)
}
log.Printf("[DEBUG] Revoking default IPv6 egress rule for Security Group for %s", d.Id())
req = &ec2.RevokeSecurityGroupEgressInput{
GroupId: createResp.GroupId,
IpPermissions: []*ec2.IpPermission{
{
FromPort: aws.Int64(int64(0)),
ToPort: aws.Int64(int64(0)),
Ipv6Ranges: []*ec2.Ipv6Range{
{
CidrIpv6: aws.String("::/0"),
},
},
IpProtocol: aws.String("-1"),
},
},
}
_, err = conn.RevokeSecurityGroupEgress(req)
if err != nil {
//If we have a NotFound or InvalidParameterValue, then we are trying to remove the default IPv6 egress of a non-IPv6
//enabled SG
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() != "InvalidPermission.NotFound" && !isAWSErr(err, "InvalidParameterValue", "remote-ipv6-range") {
return fmt.Errorf(
"Error revoking default IPv6 egress rule for Security Group (%s): %s",
d.Id(), err)
}
}
}
return resourceAwsSecurityGroupUpdate(d, meta)
}
func resourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
var sgRaw interface{}
var err error
if d.IsNewResource() {
sgRaw, err = waitForSgToExist(conn, d.Id(), d.Timeout(schema.TimeoutRead))
} else {
sgRaw, _, err = SGStateRefreshFunc(conn, d.Id())()
}
if err != nil {
return err
}
if sgRaw == nil {
log.Printf("[WARN] Security group (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
sg := sgRaw.(*ec2.SecurityGroup)
remoteIngressRules := resourceAwsSecurityGroupIPPermGather(d.Id(), sg.IpPermissions, sg.OwnerId)
remoteEgressRules := resourceAwsSecurityGroupIPPermGather(d.Id(), sg.IpPermissionsEgress, sg.OwnerId)
localIngressRules := d.Get("ingress").(*schema.Set).List()
localEgressRules := d.Get("egress").(*schema.Set).List()
// Loop through the local state of rules, doing a match against the remote
// ruleSet we built above.
ingressRules := matchRules("ingress", localIngressRules, remoteIngressRules)
egressRules := matchRules("egress", localEgressRules, remoteEgressRules)
sgArn := arn.ARN{
AccountID: aws.StringValue(sg.OwnerId),
Partition: meta.(*AWSClient).partition,
Region: meta.(*AWSClient).region,
Resource: fmt.Sprintf("security-group/%s", aws.StringValue(sg.GroupId)),
Service: ec2.ServiceName,
}
d.Set("arn", sgArn.String())
d.Set("description", sg.Description)
d.Set("name", sg.GroupName)
d.Set("vpc_id", sg.VpcId)
d.Set("owner_id", sg.OwnerId)
if err := d.Set("ingress", ingressRules); err != nil {
log.Printf("[WARN] Error setting Ingress rule set for (%s): %s", d.Id(), err)
}
if err := d.Set("egress", egressRules); err != nil {
log.Printf("[WARN] Error setting Egress rule set for (%s): %s", d.Id(), err)
}
d.Set("tags", tagsToMap(sg.Tags))
return nil
}
func resourceAwsSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
var sgRaw interface{}
var err error
if d.IsNewResource() {
sgRaw, err = waitForSgToExist(conn, d.Id(), d.Timeout(schema.TimeoutRead))
} else {
sgRaw, _, err = SGStateRefreshFunc(conn, d.Id())()
}
if err != nil {
return err
}
if sgRaw == nil {
log.Printf("[WARN] Security group (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
group := sgRaw.(*ec2.SecurityGroup)
err = resourceAwsSecurityGroupUpdateRules(d, "ingress", meta, group)
if err != nil {
return err
}
if d.Get("vpc_id") != nil {
err = resourceAwsSecurityGroupUpdateRules(d, "egress", meta, group)
if err != nil {
return err
}
}
if !d.IsNewResource() {
if err := setTags(conn, d); err != nil {
return err
}
d.SetPartial("tags")
}
return resourceAwsSecurityGroupRead(d, meta)
}
func resourceAwsSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
log.Printf("[DEBUG] Security Group destroy: %v", d.Id())
if err := deleteLingeringLambdaENIs(conn, d, "group-id"); err != nil {
return fmt.Errorf("Failed to delete Lambda ENIs: %s", err)
}
// conditionally revoke rules first before attempting to delete the group
if v := d.Get("revoke_rules_on_delete").(bool); v {
if err := forceRevokeSecurityGroupRules(conn, d); err != nil {
return err
}
}
return resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{
GroupId: aws.String(d.Id()),
})
if err != nil {
ec2err, ok := err.(awserr.Error)
if !ok {
return resource.RetryableError(err)
}
switch ec2err.Code() {
case "InvalidGroup.NotFound":
return nil
case "DependencyViolation":
// If it is a dependency violation, we want to retry
return resource.RetryableError(err)
default:
// Any other error, we want to quit the retry loop immediately
return resource.NonRetryableError(err)
}
}
return nil
})
}
// Revoke all ingress/egress rules that a Security Group has
func forceRevokeSecurityGroupRules(conn *ec2.EC2, d *schema.ResourceData) error {
sgRaw, _, err := SGStateRefreshFunc(conn, d.Id())()
if err != nil {
return err
}
if sgRaw == nil {
return nil
}
group := sgRaw.(*ec2.SecurityGroup)
if len(group.IpPermissions) > 0 {
req := &ec2.RevokeSecurityGroupIngressInput{
GroupId: group.GroupId,
IpPermissions: group.IpPermissions,
}
if group.VpcId == nil || *group.VpcId == "" {
req.GroupId = nil
req.GroupName = group.GroupName
}
_, err = conn.RevokeSecurityGroupIngress(req)
if err != nil {
return fmt.Errorf(
"Error revoking security group %s rules: %s",
*group.GroupId, err)
}
}
if len(group.IpPermissionsEgress) > 0 {
req := &ec2.RevokeSecurityGroupEgressInput{
GroupId: group.GroupId,
IpPermissions: group.IpPermissionsEgress,
}
_, err = conn.RevokeSecurityGroupEgress(req)
if err != nil {
return fmt.Errorf(
"Error revoking security group %s rules: %s",
*group.GroupId, err)
}
}
return nil
}
func resourceAwsSecurityGroupRuleHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%d-", m["from_port"].(int)))
buf.WriteString(fmt.Sprintf("%d-", m["to_port"].(int)))
p := protocolForValue(m["protocol"].(string))
buf.WriteString(fmt.Sprintf("%s-", p))
buf.WriteString(fmt.Sprintf("%t-", m["self"].(bool)))
// We need to make sure to sort the strings below so that we always
// generate the same hash code no matter what is in the set.
if v, ok := m["cidr_blocks"]; ok {
vs := v.([]interface{})
s := make([]string, len(vs))
for i, raw := range vs {
s[i] = raw.(string)
}
sort.Strings(s)
for _, v := range s {
buf.WriteString(fmt.Sprintf("%s-", v))
}
}
if v, ok := m["ipv6_cidr_blocks"]; ok {
vs := v.([]interface{})
s := make([]string, len(vs))
for i, raw := range vs {
s[i] = raw.(string)
}
sort.Strings(s)
for _, v := range s {
buf.WriteString(fmt.Sprintf("%s-", v))
}
}
if v, ok := m["prefix_list_ids"]; ok {
vs := v.([]interface{})
s := make([]string, len(vs))
for i, raw := range vs {
s[i] = raw.(string)
}
sort.Strings(s)
for _, v := range s {
buf.WriteString(fmt.Sprintf("%s-", v))
}
}
if v, ok := m["security_groups"]; ok {
vs := v.(*schema.Set).List()
s := make([]string, len(vs))
for i, raw := range vs {
s[i] = raw.(string)
}
sort.Strings(s)
for _, v := range s {
buf.WriteString(fmt.Sprintf("%s-", v))
}
}
if m["description"].(string) != "" {
buf.WriteString(fmt.Sprintf("%s-", m["description"].(string)))
}
return hashcode.String(buf.String())
}
func resourceAwsSecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, ownerId *string) []map[string]interface{} {
ruleMap := make(map[string]map[string]interface{})
for _, perm := range permissions {
if len(perm.IpRanges) > 0 {
for _, ip := range perm.IpRanges {
desc := aws.StringValue(ip.Description)
rule := initSecurityGroupRule(ruleMap, perm, desc)
raw, ok := rule["cidr_blocks"]
if !ok {
raw = make([]string, 0)
}
list := raw.([]string)
rule["cidr_blocks"] = append(list, *ip.CidrIp)
}
}
if len(perm.Ipv6Ranges) > 0 {
for _, ip := range perm.Ipv6Ranges {
desc := aws.StringValue(ip.Description)
rule := initSecurityGroupRule(ruleMap, perm, desc)
raw, ok := rule["ipv6_cidr_blocks"]
if !ok {
raw = make([]string, 0)
}
list := raw.([]string)
rule["ipv6_cidr_blocks"] = append(list, *ip.CidrIpv6)
}
}
if len(perm.PrefixListIds) > 0 {
for _, pl := range perm.PrefixListIds {
desc := aws.StringValue(pl.Description)
rule := initSecurityGroupRule(ruleMap, perm, desc)
raw, ok := rule["prefix_list_ids"]
if !ok {
raw = make([]string, 0)
}
list := raw.([]string)
rule["prefix_list_ids"] = append(list, *pl.PrefixListId)
}
}
groups := flattenSecurityGroups(perm.UserIdGroupPairs, ownerId)
if len(groups) > 0 {
for _, g := range groups {
desc := aws.StringValue(g.Description)
rule := initSecurityGroupRule(ruleMap, perm, desc)
if *g.GroupId == groupId {
rule["self"] = true
continue
}
raw, ok := rule["security_groups"]
if !ok {
raw = schema.NewSet(schema.HashString, nil)
}
list := raw.(*schema.Set)
if g.GroupName != nil {
list.Add(*g.GroupName)
} else {
list.Add(*g.GroupId)
}
rule["security_groups"] = list
}
}
}
rules := make([]map[string]interface{}, 0, len(ruleMap))
for _, m := range ruleMap {
rules = append(rules, m)
}
return rules
}
func resourceAwsSecurityGroupUpdateRules(
d *schema.ResourceData, ruleset string,
meta interface{}, group *ec2.SecurityGroup) error {
if d.HasChange(ruleset) {
o, n := d.GetChange(ruleset)
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
os := resourceAwsSecurityGroupExpandRules(o.(*schema.Set))
ns := resourceAwsSecurityGroupExpandRules(n.(*schema.Set))
remove, err := expandIPPerms(group, resourceAwsSecurityGroupCollapseRules(ruleset, os.Difference(ns).List()))
if err != nil {
return err
}
add, err := expandIPPerms(group, resourceAwsSecurityGroupCollapseRules(ruleset, ns.Difference(os).List()))
if err != nil {
return err
}
// TODO: We need to handle partial state better in the in-between
// in this update.
// TODO: It'd be nicer to authorize before removing, but then we have
// to deal with complicated unrolling to get individual CIDR blocks
// to avoid authorizing already authorized sources. Removing before
// adding is easier here, and Terraform should be fast enough to
// not have service issues.
if len(remove) > 0 || len(add) > 0 {
conn := meta.(*AWSClient).ec2conn
var err error
if len(remove) > 0 {
log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v",
group, ruleset, remove)
if ruleset == "egress" {
req := &ec2.RevokeSecurityGroupEgressInput{
GroupId: group.GroupId,
IpPermissions: remove,
}
_, err = conn.RevokeSecurityGroupEgress(req)
} else {
req := &ec2.RevokeSecurityGroupIngressInput{
GroupId: group.GroupId,
IpPermissions: remove,
}
if group.VpcId == nil || *group.VpcId == "" {
req.GroupId = nil
req.GroupName = group.GroupName
}
_, err = conn.RevokeSecurityGroupIngress(req)
}
if err != nil {
return fmt.Errorf(
"Error revoking security group %s rules: %s",
ruleset, err)
}
}
if len(add) > 0 {
log.Printf("[DEBUG] Authorizing security group %#v %s rule: %#v",
group, ruleset, add)
// Authorize the new rules
if ruleset == "egress" {
req := &ec2.AuthorizeSecurityGroupEgressInput{
GroupId: group.GroupId,
IpPermissions: add,
}
_, err = conn.AuthorizeSecurityGroupEgress(req)
} else {
req := &ec2.AuthorizeSecurityGroupIngressInput{
GroupId: group.GroupId,
IpPermissions: add,
}
if group.VpcId == nil || *group.VpcId == "" {
req.GroupId = nil
req.GroupName = group.GroupName
}
_, err = conn.AuthorizeSecurityGroupIngress(req)
}
if err != nil {
return fmt.Errorf(
"Error authorizing security group %s rules: %s",
ruleset, err)
}
}
}
}
return nil
}
// SGStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a security group.
func SGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
req := &ec2.DescribeSecurityGroupsInput{
GroupIds: []*string{aws.String(id)},
}
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 SGStateRefresh: %s", err)
return nil, "", err
}
}
if resp == nil {
return nil, "", nil
}
group := resp.SecurityGroups[0]
return group, "exists", nil
}
}
func waitForSgToExist(conn *ec2.EC2, id string, timeout time.Duration) (interface{}, error) {
log.Printf("[DEBUG] Waiting for Security Group (%s) to exist", id)
stateConf := &resource.StateChangeConf{
Pending: []string{""},
Target: []string{"exists"},
Refresh: SGStateRefreshFunc(conn, id),
Timeout: timeout,
}
return stateConf.WaitForState()
}
// matchRules receives the group id, type of rules, and the local / remote maps
// of rules. We iterate through the local set of rules trying to find a matching
// remote rule, which may be structured differently because of how AWS
// aggregates the rules under the to, from, and type.
//
//
// Matching rules are written to state, with their elements removed from the
// remote set
//
// If no match is found, we'll write the remote rule to state and let the graph
// sort things out
func matchRules(rType string, local []interface{}, remote []map[string]interface{}) []map[string]interface{} {
// For each local ip or security_group, we need to match against the remote
// ruleSet until all ips or security_groups are found
// saves represents the rules that have been identified to be saved to state,
// in the appropriate d.Set("{ingress,egress}") call.
var saves []map[string]interface{}
for _, raw := range local {
l := raw.(map[string]interface{})
var selfVal bool
if v, ok := l["self"]; ok {
selfVal = v.(bool)
}
// matching against self is required to detect rules that only include self
// as the rule. resourceAwsSecurityGroupIPPermGather parses the group out
// and replaces it with self if it's ID is found
localHash := idHash(rType, l["protocol"].(string), int64(l["to_port"].(int)), int64(l["from_port"].(int)), selfVal)
// loop remote rules, looking for a matching hash
for _, r := range remote {
var remoteSelfVal bool
if v, ok := r["self"]; ok {
remoteSelfVal = v.(bool)
}
// hash this remote rule and compare it for a match consideration with the
// local rule we're examining
rHash := idHash(rType, r["protocol"].(string), r["to_port"].(int64), r["from_port"].(int64), remoteSelfVal)
if rHash == localHash {
var numExpectedCidrs, numExpectedIpv6Cidrs, numExpectedPrefixLists, numExpectedSGs, numRemoteCidrs, numRemoteIpv6Cidrs, numRemotePrefixLists, numRemoteSGs int
var matchingCidrs []string
var matchingIpv6Cidrs []string
var matchingSGs []string
var matchingPrefixLists []string
// grab the local/remote cidr and sg groups, capturing the expected and
// actual counts
lcRaw, ok := l["cidr_blocks"]
if ok {
numExpectedCidrs = len(l["cidr_blocks"].([]interface{}))
}
liRaw, ok := l["ipv6_cidr_blocks"]
if ok {
numExpectedIpv6Cidrs = len(l["ipv6_cidr_blocks"].([]interface{}))
}
lpRaw, ok := l["prefix_list_ids"]
if ok {
numExpectedPrefixLists = len(l["prefix_list_ids"].([]interface{}))
}
lsRaw, ok := l["security_groups"]
if ok {
numExpectedSGs = len(l["security_groups"].(*schema.Set).List())
}
rcRaw, ok := r["cidr_blocks"]
if ok {
numRemoteCidrs = len(r["cidr_blocks"].([]string))
}
riRaw, ok := r["ipv6_cidr_blocks"]
if ok {
numRemoteIpv6Cidrs = len(r["ipv6_cidr_blocks"].([]string))
}
rpRaw, ok := r["prefix_list_ids"]
if ok {
numRemotePrefixLists = len(r["prefix_list_ids"].([]string))
}
rsRaw, ok := r["security_groups"]
if ok {
numRemoteSGs = len(r["security_groups"].(*schema.Set).List())
}
// check some early failures
if numExpectedCidrs > numRemoteCidrs {
log.Printf("[DEBUG] Local rule has more CIDR blocks, continuing (%d/%d)", numExpectedCidrs, numRemoteCidrs)
continue
}
if numExpectedIpv6Cidrs > numRemoteIpv6Cidrs {
log.Printf("[DEBUG] Local rule has more IPV6 CIDR blocks, continuing (%d/%d)", numExpectedIpv6Cidrs, numRemoteIpv6Cidrs)
continue
}
if numExpectedPrefixLists > numRemotePrefixLists {
log.Printf("[DEBUG] Local rule has more prefix lists, continuing (%d/%d)", numExpectedPrefixLists, numRemotePrefixLists)
continue
}
if numExpectedSGs > numRemoteSGs {
log.Printf("[DEBUG] Local rule has more Security Groups, continuing (%d/%d)", numExpectedSGs, numRemoteSGs)
continue
}
// match CIDRs by converting both to sets, and using Set methods
var localCidrs []interface{}
if lcRaw != nil {
localCidrs = lcRaw.([]interface{})
}
localCidrSet := schema.NewSet(schema.HashString, localCidrs)
// remote cidrs are presented as a slice of strings, so we need to
// reformat them into a slice of interfaces to be used in creating the
// remote cidr set
var remoteCidrs []string
if rcRaw != nil {
remoteCidrs = rcRaw.([]string)
}
// convert remote cidrs to a set, for easy comparisons
var list []interface{}
for _, s := range remoteCidrs {
list = append(list, s)
}
remoteCidrSet := schema.NewSet(schema.HashString, list)
// Build up a list of local cidrs that are found in the remote set
for _, s := range localCidrSet.List() {
if remoteCidrSet.Contains(s) {
matchingCidrs = append(matchingCidrs, s.(string))
}
}
//IPV6 CIDRs
var localIpv6Cidrs []interface{}
if liRaw != nil {
localIpv6Cidrs = liRaw.([]interface{})
}
localIpv6CidrSet := schema.NewSet(schema.HashString, localIpv6Cidrs)
var remoteIpv6Cidrs []string
if riRaw != nil {
remoteIpv6Cidrs = riRaw.([]string)
}
var listIpv6 []interface{}
for _, s := range remoteIpv6Cidrs {
listIpv6 = append(listIpv6, s)
}
remoteIpv6CidrSet := schema.NewSet(schema.HashString, listIpv6)
for _, s := range localIpv6CidrSet.List() {
if remoteIpv6CidrSet.Contains(s) {
matchingIpv6Cidrs = append(matchingIpv6Cidrs, s.(string))
}
}
// match prefix lists by converting both to sets, and using Set methods
var localPrefixLists []interface{}
if lpRaw != nil {
localPrefixLists = lpRaw.([]interface{})
}
localPrefixListsSet := schema.NewSet(schema.HashString, localPrefixLists)
// remote prefix lists are presented as a slice of strings, so we need to
// reformat them into a slice of interfaces to be used in creating the
// remote prefix list set
var remotePrefixLists []string
if rpRaw != nil {
remotePrefixLists = rpRaw.([]string)
}
// convert remote prefix lists to a set, for easy comparison
list = nil