From c9544f51af4b9a32b75ae6281a92269beb5de5c2 Mon Sep 17 00:00:00 2001 From: Tom Elliff Date: Thu, 3 Sep 2020 15:01:43 +0100 Subject: [PATCH 001/120] Validate that security group names aren't prefixed with sg- The [API docs](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) have this to say: > Constraints: Up to 255 characters in length. Cannot start with sg-. --- aws/resource_aws_security_group.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/aws/resource_aws_security_group.go b/aws/resource_aws_security_group.go index 8b43234d871b..959a96fe08c3 100644 --- a/aws/resource_aws_security_group.go +++ b/aws/resource_aws_security_group.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "log" + "regexp" "sort" "strconv" "strings" @@ -47,7 +48,10 @@ func resourceAwsSecurityGroup() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: validation.StringLenBetween(0, 255), + ValidateFunc: validation.All( + validation.StringLenBetween(0, 255), + validation.StringDoesNotMatch(regexp.MustCompile(`^sg-`), "cannot begin with sg-"), + ), }, "name_prefix": { From 1a5a1ded5ef764e2d2709def39ed67e051b2f072 Mon Sep 17 00:00:00 2001 From: Derrick Petzold Date: Fri, 25 Sep 2020 13:38:42 -0700 Subject: [PATCH 002/120] d/aws_security_group: more verbose error on dne If the security group does not exist output an error with the sg name in message. --- aws/data_source_aws_security_group.go | 16 ++++++++-- aws/data_source_aws_security_group_test.go | 35 ++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/aws/data_source_aws_security_group.go b/aws/data_source_aws_security_group.go index a3ffc8f52ef7..06da6142e8b4 100644 --- a/aws/data_source_aws_security_group.go +++ b/aws/data_source_aws_security_group.go @@ -59,10 +59,13 @@ func dataSourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) er req.GroupIds = []*string{aws.String(id.(string))} } + group_name := d.Get("name").(string) + vpc_id := d.Get("vpc_id").(string) + req.Filters = buildEC2AttributeFilterList( map[string]string{ - "group-name": d.Get("name").(string), - "vpc-id": d.Get("vpc_id").(string), + "group-name": group_name, + "vpc-id": vpc_id, }, ) req.Filters = append(req.Filters, buildEC2TagFilterList( @@ -82,7 +85,14 @@ func dataSourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) er return err } if resp == nil || len(resp.SecurityGroups) == 0 { - return fmt.Errorf("no matching SecurityGroup found") + + err_msg := "" + if group_name != "" && vpc_id != "" { + err_msg = fmt.Sprintf(": %s/%s", vpc_id, group_name) + } else if group_name != "" { + err_msg = fmt.Sprintf(": %s", group_name) + } + return fmt.Errorf("no matching SecurityGroup found%s", err_msg) } if len(resp.SecurityGroups) > 1 { return fmt.Errorf("multiple Security Groups matched; use additional constraints to reduce matches to a single Security Group") diff --git a/aws/data_source_aws_security_group_test.go b/aws/data_source_aws_security_group_test.go index 75b6b2ce03ca..86c5e7927904 100644 --- a/aws/data_source_aws_security_group_test.go +++ b/aws/data_source_aws_security_group_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "regexp" "testing" "strings" @@ -32,6 +33,23 @@ func TestAccDataSourceAwsSecurityGroup_basic(t *testing.T) { }) } +func TestAccDataSourceAwsSecurityGroup_dne(t *testing.T) { + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsSecurityGroupConfigDne(), + ExpectError: regexp.MustCompile(`no matching SecurityGroup found: dne`), + }, + { + Config: testAccDataSourceAwsSecurityGroupConfigDneVpc(), + ExpectError: regexp.MustCompile(`no matching SecurityGroup found: vpc-xxxxxxx/dne`), + }, + }, + }) +} + func testAccDataSourceAwsSecurityGroupCheck(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] @@ -151,3 +169,20 @@ data "aws_security_group" "by_filter" { } `, rInt, rInt) } + +func testAccDataSourceAwsSecurityGroupConfigDne() string { + return ` +data "aws_security_group" "dne" { + name = "dne" +} +` +} + +func testAccDataSourceAwsSecurityGroupConfigDneVpc() string { + return ` +data "aws_security_group" "dne_vpc" { + name = "dne" + vpc_id = "vpc-xxxxxxx" +} +` +} From 807d6911c7c257898dce55d9a086e72bf7710dd8 Mon Sep 17 00:00:00 2001 From: Thayne McCombs Date: Tue, 24 Sep 2019 15:30:47 -0600 Subject: [PATCH 003/120] Change the default description for inline security group rules to "" --- internal/service/ec2/security_group.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index b450fe3ed60e..72593cab51bd 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -140,6 +140,7 @@ func ResourceSecurityGroup() *schema.Resource { "description": { Type: schema.TypeString, Optional: true, + Default: "", ValidateFunc: validSecurityGroupRuleDescription, }, }, @@ -210,6 +211,7 @@ func ResourceSecurityGroup() *schema.Resource { "description": { Type: schema.TypeString, Optional: true, + Default: "", ValidateFunc: validSecurityGroupRuleDescription, }, }, From e2fcdf207996f5b1ca2103c81cd30e9691748c7f Mon Sep 17 00:00:00 2001 From: Thayne McCombs Date: Mon, 23 Sep 2019 22:49:21 -0600 Subject: [PATCH 004/120] Use sets for security groups They are treated as a set anyway. --- internal/service/ec2/security_group.go | 113 ++++++++---------- .../ec2/security_group_rules_matching_test.go | 103 ++++++++-------- internal/service/ec2/security_group_test.go | 40 +++---- 3 files changed, 117 insertions(+), 139 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index b450fe3ed60e..f79f7cd2495c 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -101,7 +101,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "cidr_blocks": { - Type: schema.TypeList, + Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -110,7 +110,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "ipv6_cidr_blocks": { - Type: schema.TypeList, + Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -171,7 +171,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "cidr_blocks": { - Type: schema.TypeList, + Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -180,7 +180,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "ipv6_cidr_blocks": { - Type: schema.TypeList, + Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -537,7 +537,7 @@ func SecurityGroupRuleHash(v interface{}) int { // 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{}) + vs := v.(*schema.Set).List() s := make([]string, len(vs)) for i, raw := range vs { s[i] = raw.(string) @@ -549,7 +549,7 @@ func SecurityGroupRuleHash(v interface{}) int { } } if v, ok := m["ipv6_cidr_blocks"]; ok { - vs := v.([]interface{}) + vs := v.(*schema.Set).List() s := make([]string, len(vs)) for i, raw := range vs { s[i] = raw.(string) @@ -602,11 +602,12 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, raw, ok := rule["cidr_blocks"] if !ok { - raw = make([]string, 0) + raw = schema.NewSet(schema.HashString, nil) } - list := raw.([]string) + list := raw.(*schema.Set) - rule["cidr_blocks"] = append(list, *ip.CidrIp) + list.Add(*ip.CidrIp) + rule["cidr_blocks"] = list } } @@ -618,11 +619,11 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, raw, ok := rule["ipv6_cidr_blocks"] if !ok { - raw = make([]string, 0) + raw = schema.NewSet(schema.HashString, nil) } - list := raw.([]string) - - rule["ipv6_cidr_blocks"] = append(list, *ip.CidrIpv6) + list := raw.(*schema.Set) + list.Add(*ip.CidrIpv6) + rule["ipv6_cidr_blocks"] = list } } @@ -828,11 +829,11 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface // actual counts lcRaw, ok := l["cidr_blocks"] if ok { - numExpectedCidrs = len(l["cidr_blocks"].([]interface{})) + numExpectedCidrs = len(l["cidr_blocks"].(*schema.Set).List()) } liRaw, ok := l["ipv6_cidr_blocks"] if ok { - numExpectedIpv6Cidrs = len(l["ipv6_cidr_blocks"].([]interface{})) + numExpectedIpv6Cidrs = len(l["ipv6_cidr_blocks"].(*schema.Set).List()) } lpRaw, ok := l["prefix_list_ids"] if ok { @@ -845,11 +846,11 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface rcRaw, ok := r["cidr_blocks"] if ok { - numRemoteCidrs = len(r["cidr_blocks"].([]string)) + numRemoteCidrs = len(r["cidr_blocks"].(*schema.Set).List()) } riRaw, ok := r["ipv6_cidr_blocks"] if ok { - numRemoteIpv6Cidrs = len(r["ipv6_cidr_blocks"].([]string)) + numRemoteIpv6Cidrs = len(r["ipv6_cidr_blocks"].(*schema.Set).List()) } rpRaw, ok := r["prefix_list_ids"] if ok { @@ -879,26 +880,20 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface continue } - // match CIDRs by converting both to sets, and using Set methods - var localCidrs []interface{} - if lcRaw != nil { - localCidrs = lcRaw.([]interface{}) + // match CIDRs. Both local and remote are already sets + var localCidrSet *schema.Set + if lcRaw == nil { + localCidrSet = schema.NewSet(schema.HashString, nil) + } else { + localCidrSet = lcRaw.(*schema.Set) } - 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) + var remoteCidrSet *schema.Set + if rcRaw == nil { + remoteCidrSet = schema.NewSet(schema.HashString, nil) + } else { + remoteCidrSet = rcRaw.(*schema.Set) } - 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() { @@ -908,21 +903,19 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface } //IPV6 CIDRs - var localIpv6Cidrs []interface{} - if liRaw != nil { - localIpv6Cidrs = liRaw.([]interface{}) + var localIpv6CidrSet *schema.Set + if liRaw == nil { + localIpv6CidrSet = schema.NewSet(schema.HashString, nil) + } else { + localIpv6CidrSet = liRaw.(*schema.Set) } - 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) + var remoteIpv6CidrSet *schema.Set + if riRaw == nil { + remoteIpv6CidrSet = schema.NewSet(schema.HashString, nil) + } else { + remoteIpv6CidrSet = rcRaw.(*schema.Set) } - remoteIpv6CidrSet := schema.NewSet(schema.HashString, listIpv6) for _, s := range localIpv6CidrSet.List() { if remoteIpv6CidrSet.Contains(s) { @@ -945,7 +938,7 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface remotePrefixLists = rpRaw.([]string) } // convert remote prefix lists to a set, for easy comparison - list = nil + var list []interface{} = nil for _, s := range remotePrefixLists { list = append(list, s) } @@ -1000,14 +993,10 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface if rSelf == lSelf { delete(r, "self") // pop local cidrs from remote - diffCidr := remoteCidrSet.Difference(localCidrSet) - var newCidr []string - for _, cRaw := range diffCidr.List() { - newCidr = append(newCidr, cRaw.(string)) - } + newCidr := remoteCidrSet.Difference(localCidrSet) // reassigning - if len(newCidr) > 0 { + if newCidr.Len() > 0 { r["cidr_blocks"] = newCidr } else { delete(r, "cidr_blocks") @@ -1015,14 +1004,10 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface //// IPV6 //// Comparison - diffIpv6Cidr := remoteIpv6CidrSet.Difference(localIpv6CidrSet) - var newIpv6Cidr []string - for _, cRaw := range diffIpv6Cidr.List() { - newIpv6Cidr = append(newIpv6Cidr, cRaw.(string)) - } + newIpv6Cidr := remoteIpv6CidrSet.Difference(localIpv6CidrSet) // reassigning - if len(newIpv6Cidr) > 0 { + if newIpv6Cidr.Len() > 0 { r["ipv6_cidr_blocks"] = newIpv6Cidr } else { delete(r, "ipv6_cidr_blocks") @@ -1072,10 +1057,10 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface for _, r := range remote { var lenCidr, lenIpv6Cidr, lenPrefixLists, lenSGs int if rCidrs, ok := r["cidr_blocks"]; ok { - lenCidr = len(rCidrs.([]string)) + lenCidr = rCidrs.(*schema.Set).Len() } if rIpv6Cidrs, ok := r["ipv6_cidr_blocks"]; ok { - lenIpv6Cidr = len(rIpv6Cidrs.([]string)) + lenIpv6Cidr = rIpv6Cidrs.(*schema.Set).Len() } if rPrefixLists, ok := r["prefix_list_ids"]; ok { lenPrefixLists = len(rPrefixLists.([]string)) @@ -1149,7 +1134,7 @@ func SecurityGroupCollapseRules(ruleset string, rules []interface{}) []interface for _, key := range keys_to_collapse { if _, ok := r[key]; ok { if _, ok := collapsed[ruleHash][key]; ok { - if key == "security_groups" { + if key != "prefix_list_ids" { collapsed[ruleHash][key] = collapsed[ruleHash][key].(*schema.Set).Union(r[key].(*schema.Set)) } else { collapsed[ruleHash][key] = append(collapsed[ruleHash][key].([]interface{}), r[key].([]interface{})...) @@ -1230,14 +1215,14 @@ func SecurityGroupExpandRules(rules *schema.Set) *schema.Set { item, exists := rule[key] if exists { var list []interface{} - if key == "security_groups" { + if key != "prefix_list_ids" { list = item.(*schema.Set).List() } else { list = item.([]interface{}) } for _, v := range list { var new_rule map[string]interface{} - if key == "security_groups" { + if key != "prefix_list_ids" { new_v := schema.NewSet(schema.HashString, nil) new_v.Add(v) new_rule = resourceSecurityGroupCopyRule(rule, false, key, new_v) diff --git a/internal/service/ec2/security_group_rules_matching_test.go b/internal/service/ec2/security_group_rules_matching_test.go index 058f08a19830..15756c32a1b5 100644 --- a/internal/service/ec2/security_group_rules_matching_test.go +++ b/internal/service/ec2/security_group_rules_matching_test.go @@ -21,7 +21,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -30,7 +30,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -39,7 +39,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -58,7 +58,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -73,7 +73,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), }, }, }, @@ -83,7 +83,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), }, }, remote: []map[string]interface{}{ @@ -91,7 +91,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), }, }, saves: []map[string]interface{}{ @@ -99,7 +99,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), }, }, }, @@ -135,13 +135,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), }, map[string]interface{}{ "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), }, }, remote: []map[string]interface{}{ @@ -149,7 +149,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), }, }, saves: []map[string]interface{}{ @@ -157,13 +157,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), }, { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), }, }, }, @@ -174,7 +174,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), }, }, saves: []map[string]interface{}{ @@ -182,7 +182,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), }, }, }, @@ -217,7 +217,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), }, }, remote: []map[string]interface{}{ @@ -225,7 +225,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"10.0.0.0/16"}), }, }, // Because this is the remote rule being saved, we need to check for int64 @@ -236,7 +236,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"10.0.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"10.0.0.0/16"}), }, }, }, @@ -247,7 +247,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}), }, }, remote: []map[string]interface{}{ @@ -255,7 +255,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), }, }, saves: []map[string]interface{}{ @@ -263,7 +263,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), }, }, }, @@ -275,19 +275,19 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), }, map[string]interface{}{ "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"10.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"10.8.0.0/16"}), }, map[string]interface{}{ "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), }, }, remote: []map[string]interface{}{ @@ -295,7 +295,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), }, }, saves: []map[string]interface{}{ @@ -303,13 +303,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), }, { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), }, }, }, @@ -321,7 +321,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16"}), }, }, remote: []map[string]interface{}{ @@ -329,7 +329,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16", "10.8.0.0/16", "206.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16", "10.8.0.0/16", "206.8.0.0/16"}), }, }, saves: []map[string]interface{}{ @@ -337,13 +337,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "10.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16"}), }, { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"192.168.0.0/16", "206.8.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16", "206.8.0.0/16"}), }, }, }, @@ -511,7 +511,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}), }, map[string]interface{}{ "from_port": 80, @@ -525,7 +525,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -534,7 +534,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), }, { "from_port": int64(80), @@ -550,7 +550,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}), }, map[string]interface{}{ "from_port": 80, @@ -564,7 +564,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), "self": true, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, @@ -580,7 +580,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -616,9 +616,9 @@ func TestRulesMixedMatching(t *testing.T) { if _, ok := s["cidr_blocks"]; ok { switch s["cidr_blocks"].(type) { case []string: - numExpectedCidrs = len(s["cidr_blocks"].([]string)) + numExpectedCidrs = s["cidr_blocks"].(*schema.Set).Len() default: - numExpectedCidrs = len(s["cidr_blocks"].([]interface{})) + numExpectedCidrs = s["cidr_blocks"].(*schema.Set).Len() } } @@ -627,7 +627,7 @@ func TestRulesMixedMatching(t *testing.T) { } if _, ok := cs["cidr_blocks"]; ok { - numRemoteCidrs = len(cs["cidr_blocks"].([]string)) + numRemoteCidrs = cs["cidr_blocks"].(*schema.Set).Len() } if _, ok := cs["security_groups"]; ok { @@ -652,27 +652,20 @@ func TestRulesMixedMatching(t *testing.T) { } // convert save cidrs to set - var lcs []interface{} + var savesCidrs *schema.Set if _, ok := s["cidr_blocks"]; ok { - switch s["cidr_blocks"].(type) { - case []string: - for _, c := range s["cidr_blocks"].([]string) { - lcs = append(lcs, c) - } - default: - lcs = append(lcs, s["cidr_blocks"].([]interface{})...) - } + savesCidrs = s["cidr_blocks"].(*schema.Set) + } else { + savesCidrs = schema.NewSet(schema.HashString, nil) } - savesCidrs := schema.NewSet(schema.HashString, lcs) // convert cs cidrs to set - var cslcs []interface{} + var csCidrs *schema.Set if _, ok := cs["cidr_blocks"]; ok { - for _, c := range cs["cidr_blocks"].([]string) { - cslcs = append(cslcs, c) - } + csCidrs = cs["cidr_blocks"].(*schema.Set) + } else { + csCidrs = schema.NewSet(schema.HashString, nil) } - csCidrs := schema.NewSet(schema.HashString, cslcs) if csCidrs.Equal(savesCidrs) { log.Printf("\nmatched cidrs") diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index d159fb467d61..ef828db8c1ba 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -158,11 +158,11 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": true, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "10.0.0.1/32", "10.0.0.2/32", "10.0.0.3/32", - }, + }), }, map[string]interface{}{ "protocol": "tcp", @@ -170,10 +170,10 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with another description", "self": false, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "192.168.0.1/32", "192.168.0.2/32", - }, + }), }, map[string]interface{}{ "protocol": "-1", @@ -181,10 +181,10 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(8080), "description": "", "self": false, - "ipv6_cidr_blocks": []interface{}{ + "ipv6_cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "fd00::1/128", "fd00::2/128", - }, + }), "security_groups": schema.NewSet(schema.HashString, []interface{}{ "sg-11111", "sg-22222", @@ -218,9 +218,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": false, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "10.0.0.1/32", - }, + }), }, map[string]interface{}{ "protocol": "tcp", @@ -228,9 +228,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": false, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "10.0.0.2/32", - }, + }), }, map[string]interface{}{ "protocol": "tcp", @@ -238,9 +238,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": false, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "10.0.0.3/32", - }, + }), }, map[string]interface{}{ "protocol": "tcp", @@ -248,9 +248,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with another description", "self": false, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "192.168.0.1/32", - }, + }), }, map[string]interface{}{ "protocol": "tcp", @@ -258,9 +258,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with another description", "self": false, - "cidr_blocks": []interface{}{ + "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "192.168.0.2/32", - }, + }), }, map[string]interface{}{ "protocol": "-1", @@ -268,9 +268,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(8080), "description": "", "self": false, - "ipv6_cidr_blocks": []interface{}{ + "ipv6_cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "fd00::1/128", - }, + }), }, map[string]interface{}{ "protocol": "-1", @@ -278,9 +278,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(8080), "description": "", "self": false, - "ipv6_cidr_blocks": []interface{}{ + "ipv6_cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ "fd00::2/128", - }, + }), }, map[string]interface{}{ "protocol": "-1", From a5f2c9ddd7cd22f8ac949416f1db66f360d3da6f Mon Sep 17 00:00:00 2001 From: Thayne McCombs Date: Sun, 22 Sep 2019 00:05:06 -0600 Subject: [PATCH 005/120] Allow update instead for recreate for aws_security_group_rule. With this change, changes it cidr_blocks and ipv6_cidr_blocks will only remove/add the cidr ranges that were removed/added in config, rather than destroying the entire resource and recreating it. It also changes the type of those attributes to sets to make the diffs more readable. --- internal/service/ec2/security_group_rule.go | 170 ++++++++++++++++---- 1 file changed, 142 insertions(+), 28 deletions(-) diff --git a/internal/service/ec2/security_group_rule.go b/internal/service/ec2/security_group_rule.go index b8b1b6f67df7..25c382142110 100644 --- a/internal/service/ec2/security_group_rule.go +++ b/internal/service/ec2/security_group_rule.go @@ -92,9 +92,8 @@ func ResourceSecurityGroupRule() *schema.Resource { }, "cidr_blocks": { - Type: schema.TypeList, + Type: schema.TypeSet, Optional: true, - ForceNew: true, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: verify.ValidCIDRNetworkAddress, @@ -103,9 +102,8 @@ func ResourceSecurityGroupRule() *schema.Resource { }, "ipv6_cidr_blocks": { - Type: schema.TypeList, + Type: schema.TypeSet, Optional: true, - ForceNew: true, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: verify.ValidCIDRNetworkAddress, @@ -349,6 +347,12 @@ func resourceSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) e } } + if d.HasChange("cidr_blocks") || d.HasChange("ipv6_cidr_blocks") { + if err := resourceSecurityGroupRuleCidrUpdate(conn, d); err != nil { + return err + } + } + return resourceSecurityGroupRuleRead(d, meta) } @@ -641,7 +645,7 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss } if raw, ok := d.GetOk("cidr_blocks"); ok { - list := raw.([]interface{}) + list := raw.(*schema.Set).List() perm.IpRanges = make([]*ec2.IpRange, len(list)) for i, v := range list { cidrIP, ok := v.(string) @@ -657,7 +661,7 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss } if raw, ok := d.GetOk("ipv6_cidr_blocks"); ok { - list := raw.([]interface{}) + list := raw.(*schema.Set).List() perm.Ipv6Ranges = make([]*ec2.Ipv6Range, len(list)) for i, v := range list { cidrIP, ok := v.(string) @@ -691,6 +695,63 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss return &perm, nil } +func expandCidrIPPerm(d *schema.ResourceData, cidrBlocks *schema.Set, ipv6CidrBlocks *schema.Set) *ec2.IpPermission { + var perm ec2.IpPermission + + protocol := ProtocolForValue(d.Get("protocol").(string)) + perm.IpProtocol = aws.String(protocol) + + if protocol != "-1" { + perm.FromPort = aws.Int64(int64(d.Get("from_port").(int))) + perm.ToPort = aws.Int64(int64(d.Get("to_port").(int))) + } + + description := d.Get("description").(string) + + if cidrBlocks.Len() > 0 { + list := cidrBlocks.List() + perm.IpRanges = make([]*ec2.IpRange, len(list)) + for i, v := range list { + cidrIP := v.(string) + perm.IpRanges[i] = &ec2.IpRange{CidrIp: aws.String(cidrIP)} + if description != "" { + perm.IpRanges[i].Description = aws.String(description) + } + } + } + + if ipv6CidrBlocks.Len() > 0 { + list := ipv6CidrBlocks.List() + perm.Ipv6Ranges = make([]*ec2.Ipv6Range, len(list)) + for i, v := range list { + cidrIP := v.(string) + perm.Ipv6Ranges[i] = &ec2.Ipv6Range{CidrIpv6: aws.String(cidrIP)} + if description != "" { + perm.Ipv6Ranges[i].Description = aws.String(description) + } + } + } + + return &perm +} + +// Get the sets of removed and added items in a set of +func getSetChange(d *schema.ResourceData, name string) (removed *schema.Set, added *schema.Set) { + o, n := d.GetChange(name) + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + old := o.(*schema.Set) + new_ := n.(*schema.Set) + removed = old.Difference(new_) + added = new_.Difference(old) + + return removed, added +} + func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPermission) { isVPC := aws.StringValue(sg.VpcId) != "" @@ -698,15 +759,15 @@ func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPe d.Set("to_port", rule.ToPort) d.Set("protocol", rule.IpProtocol) - var cb []string + cb := &schema.Set{F: schema.HashString} for _, c := range rule.IpRanges { - cb = append(cb, *c.CidrIp) + cb.Add(*c.CidrIp) } d.Set("cidr_blocks", cb) - var ipv6 []string + ipv6 := &schema.Set{F: schema.HashString} for _, ip := range rule.Ipv6Ranges { - ipv6 = append(ipv6, *ip.CidrIpv6) + ipv6.Add(*ip.CidrIpv6) } d.Set("ipv6_cidr_blocks", ipv6) @@ -741,16 +802,14 @@ func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPe func descriptionFromIPPerm(d *schema.ResourceData, rule *ec2.IpPermission) string { // probe IpRanges - cidrIps := make(map[string]bool) + var cidrIps *schema.Set if raw, ok := d.GetOk("cidr_blocks"); ok { - for _, v := range raw.([]interface{}) { - cidrIps[v.(string)] = true - } + cidrIps = raw.(*schema.Set) } - if len(cidrIps) > 0 { + if cidrIps != nil && cidrIps.Len() > 0 { for _, c := range rule.IpRanges { - if _, ok := cidrIps[*c.CidrIp]; !ok { + if !cidrIps.Contains(*c.CidrIp) { continue } @@ -761,16 +820,14 @@ func descriptionFromIPPerm(d *schema.ResourceData, rule *ec2.IpPermission) strin } // probe Ipv6Ranges - cidrIpv6s := make(map[string]bool) + var cidrIpv6s *schema.Set if raw, ok := d.GetOk("ipv6_cidr_blocks"); ok { - for _, v := range raw.([]interface{}) { - cidrIpv6s[v.(string)] = true - } + cidrIpv6s = raw.(*schema.Set) } - if len(cidrIpv6s) > 0 { + if cidrIpv6s != nil && cidrIpv6s.Len() > 0 { for _, ip := range rule.Ipv6Ranges { - if _, ok := cidrIpv6s[*ip.CidrIpv6]; !ok { + if !cidrIpv6s.Contains(*ip.CidrIpv6) { continue } @@ -897,6 +954,63 @@ func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.Resourc return nil } +func resourceSecurityGroupRuleCidrUpdate(conn *ec2.EC2, d *schema.ResourceData) error { + var err error + sg_id := d.Get("security_group_id").(string) + + removed, added := getSetChange(d, "cidr_blocks") + ipv6Removed, ipv6Added := getSetChange(d, "ipv6_cidr_blocks") + + removePerm := expandCidrIPPerm(d, removed, ipv6Removed) + addPerm := expandCidrIPPerm(d, added, ipv6Added) + + conns.GlobalMutexKV.Lock(sg_id) + defer conns.GlobalMutexKV.Unlock(sg_id) + + ruleType := d.Get("type").(string) + log.Printf("[DEBUG] Revoking rules (%s) from security group %s:\n%s", ruleType, sg_id, removePerm) + switch ruleType { + case "ingress": + req := &ec2.RevokeSecurityGroupIngressInput{ + GroupId: aws.String(sg_id), + IpPermissions: []*ec2.IpPermission{removePerm}, + } + _, err = conn.RevokeSecurityGroupIngress(req) + case "egress": + req := &ec2.RevokeSecurityGroupEgressInput{ + GroupId: aws.String(sg_id), + IpPermissions: []*ec2.IpPermission{removePerm}, + } + _, err = conn.RevokeSecurityGroupEgress(req) + } + if err != nil { + return fmt.Errorf("Error revoking security group %s rules: %s", sg_id, err) + } + + log.Printf("[DEBUG] Adding rules (%s) for security group %s:\n%s", ruleType, sg_id, addPerm) + switch ruleType { + case "ingress": + req := &ec2.AuthorizeSecurityGroupIngressInput{ + GroupId: aws.String(sg_id), + IpPermissions: []*ec2.IpPermission{addPerm}, + } + + _, err = conn.AuthorizeSecurityGroupIngress(req) + case "egress": + req := &ec2.AuthorizeSecurityGroupEgressInput{ + GroupId: aws.String(sg_id), + IpPermissions: []*ec2.IpPermission{addPerm}, + } + + _, err = conn.AuthorizeSecurityGroupEgress(req) + } + if err != nil { + return fmt.Errorf("Error adding security group %s rules: %s", sg_id, err) + } + + return nil +} + // validateSecurityGroupRuleImportString does minimal validation of import string without going to AWS func validateSecurityGroupRuleImportString(importStr string) ([]string, error) { // example: sg-09a093729ef9382a6_ingress_tcp_8000_8000_10.0.3.0/24 @@ -981,9 +1095,9 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s d.Set("to_port", toPort) d.Set("self", false) - var cidrs []string + cidrs := schema.Set{F: schema.HashString} var prefixList []string - var ipv6cidrs []string + ipv6cidrs := schema.Set{F: schema.HashString} for _, source := range sources { if source == "self" { d.Set("self", true) @@ -992,13 +1106,13 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s } else if strings.Contains(source, "pl-") { prefixList = append(prefixList, source) } else if strings.Contains(source, ":") { - ipv6cidrs = append(ipv6cidrs, source) + ipv6cidrs.Add(source) } else { - cidrs = append(cidrs, source) + cidrs.Add(source) } } - d.Set("ipv6_cidr_blocks", ipv6cidrs) - d.Set("cidr_blocks", cidrs) + d.Set("ipv6_cidr_blocks", &ipv6cidrs) + d.Set("cidr_blocks", &cidrs) d.Set("prefix_list_ids", prefixList) return nil From 93a7e0a67cad0478da8f1ee7708bf469faa24407 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 16:58:38 -0400 Subject: [PATCH 006/120] Revert "Allow update instead for recreate for aws_security_group_rule." This reverts commit a5f2c9ddd7cd22f8ac949416f1db66f360d3da6f. --- internal/service/ec2/security_group_rule.go | 170 ++++---------------- 1 file changed, 28 insertions(+), 142 deletions(-) diff --git a/internal/service/ec2/security_group_rule.go b/internal/service/ec2/security_group_rule.go index 25c382142110..b8b1b6f67df7 100644 --- a/internal/service/ec2/security_group_rule.go +++ b/internal/service/ec2/security_group_rule.go @@ -92,8 +92,9 @@ func ResourceSecurityGroupRule() *schema.Resource { }, "cidr_blocks": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, + ForceNew: true, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: verify.ValidCIDRNetworkAddress, @@ -102,8 +103,9 @@ func ResourceSecurityGroupRule() *schema.Resource { }, "ipv6_cidr_blocks": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, + ForceNew: true, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: verify.ValidCIDRNetworkAddress, @@ -347,12 +349,6 @@ func resourceSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) e } } - if d.HasChange("cidr_blocks") || d.HasChange("ipv6_cidr_blocks") { - if err := resourceSecurityGroupRuleCidrUpdate(conn, d); err != nil { - return err - } - } - return resourceSecurityGroupRuleRead(d, meta) } @@ -645,7 +641,7 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss } if raw, ok := d.GetOk("cidr_blocks"); ok { - list := raw.(*schema.Set).List() + list := raw.([]interface{}) perm.IpRanges = make([]*ec2.IpRange, len(list)) for i, v := range list { cidrIP, ok := v.(string) @@ -661,7 +657,7 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss } if raw, ok := d.GetOk("ipv6_cidr_blocks"); ok { - list := raw.(*schema.Set).List() + list := raw.([]interface{}) perm.Ipv6Ranges = make([]*ec2.Ipv6Range, len(list)) for i, v := range list { cidrIP, ok := v.(string) @@ -695,63 +691,6 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss return &perm, nil } -func expandCidrIPPerm(d *schema.ResourceData, cidrBlocks *schema.Set, ipv6CidrBlocks *schema.Set) *ec2.IpPermission { - var perm ec2.IpPermission - - protocol := ProtocolForValue(d.Get("protocol").(string)) - perm.IpProtocol = aws.String(protocol) - - if protocol != "-1" { - perm.FromPort = aws.Int64(int64(d.Get("from_port").(int))) - perm.ToPort = aws.Int64(int64(d.Get("to_port").(int))) - } - - description := d.Get("description").(string) - - if cidrBlocks.Len() > 0 { - list := cidrBlocks.List() - perm.IpRanges = make([]*ec2.IpRange, len(list)) - for i, v := range list { - cidrIP := v.(string) - perm.IpRanges[i] = &ec2.IpRange{CidrIp: aws.String(cidrIP)} - if description != "" { - perm.IpRanges[i].Description = aws.String(description) - } - } - } - - if ipv6CidrBlocks.Len() > 0 { - list := ipv6CidrBlocks.List() - perm.Ipv6Ranges = make([]*ec2.Ipv6Range, len(list)) - for i, v := range list { - cidrIP := v.(string) - perm.Ipv6Ranges[i] = &ec2.Ipv6Range{CidrIpv6: aws.String(cidrIP)} - if description != "" { - perm.Ipv6Ranges[i].Description = aws.String(description) - } - } - } - - return &perm -} - -// Get the sets of removed and added items in a set of -func getSetChange(d *schema.ResourceData, name string) (removed *schema.Set, added *schema.Set) { - o, n := d.GetChange(name) - if o == nil { - o = new(schema.Set) - } - if n == nil { - n = new(schema.Set) - } - old := o.(*schema.Set) - new_ := n.(*schema.Set) - removed = old.Difference(new_) - added = new_.Difference(old) - - return removed, added -} - func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPermission) { isVPC := aws.StringValue(sg.VpcId) != "" @@ -759,15 +698,15 @@ func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPe d.Set("to_port", rule.ToPort) d.Set("protocol", rule.IpProtocol) - cb := &schema.Set{F: schema.HashString} + var cb []string for _, c := range rule.IpRanges { - cb.Add(*c.CidrIp) + cb = append(cb, *c.CidrIp) } d.Set("cidr_blocks", cb) - ipv6 := &schema.Set{F: schema.HashString} + var ipv6 []string for _, ip := range rule.Ipv6Ranges { - ipv6.Add(*ip.CidrIpv6) + ipv6 = append(ipv6, *ip.CidrIpv6) } d.Set("ipv6_cidr_blocks", ipv6) @@ -802,14 +741,16 @@ func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPe func descriptionFromIPPerm(d *schema.ResourceData, rule *ec2.IpPermission) string { // probe IpRanges - var cidrIps *schema.Set + cidrIps := make(map[string]bool) if raw, ok := d.GetOk("cidr_blocks"); ok { - cidrIps = raw.(*schema.Set) + for _, v := range raw.([]interface{}) { + cidrIps[v.(string)] = true + } } - if cidrIps != nil && cidrIps.Len() > 0 { + if len(cidrIps) > 0 { for _, c := range rule.IpRanges { - if !cidrIps.Contains(*c.CidrIp) { + if _, ok := cidrIps[*c.CidrIp]; !ok { continue } @@ -820,14 +761,16 @@ func descriptionFromIPPerm(d *schema.ResourceData, rule *ec2.IpPermission) strin } // probe Ipv6Ranges - var cidrIpv6s *schema.Set + cidrIpv6s := make(map[string]bool) if raw, ok := d.GetOk("ipv6_cidr_blocks"); ok { - cidrIpv6s = raw.(*schema.Set) + for _, v := range raw.([]interface{}) { + cidrIpv6s[v.(string)] = true + } } - if cidrIpv6s != nil && cidrIpv6s.Len() > 0 { + if len(cidrIpv6s) > 0 { for _, ip := range rule.Ipv6Ranges { - if !cidrIpv6s.Contains(*ip.CidrIpv6) { + if _, ok := cidrIpv6s[*ip.CidrIpv6]; !ok { continue } @@ -954,63 +897,6 @@ func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.Resourc return nil } -func resourceSecurityGroupRuleCidrUpdate(conn *ec2.EC2, d *schema.ResourceData) error { - var err error - sg_id := d.Get("security_group_id").(string) - - removed, added := getSetChange(d, "cidr_blocks") - ipv6Removed, ipv6Added := getSetChange(d, "ipv6_cidr_blocks") - - removePerm := expandCidrIPPerm(d, removed, ipv6Removed) - addPerm := expandCidrIPPerm(d, added, ipv6Added) - - conns.GlobalMutexKV.Lock(sg_id) - defer conns.GlobalMutexKV.Unlock(sg_id) - - ruleType := d.Get("type").(string) - log.Printf("[DEBUG] Revoking rules (%s) from security group %s:\n%s", ruleType, sg_id, removePerm) - switch ruleType { - case "ingress": - req := &ec2.RevokeSecurityGroupIngressInput{ - GroupId: aws.String(sg_id), - IpPermissions: []*ec2.IpPermission{removePerm}, - } - _, err = conn.RevokeSecurityGroupIngress(req) - case "egress": - req := &ec2.RevokeSecurityGroupEgressInput{ - GroupId: aws.String(sg_id), - IpPermissions: []*ec2.IpPermission{removePerm}, - } - _, err = conn.RevokeSecurityGroupEgress(req) - } - if err != nil { - return fmt.Errorf("Error revoking security group %s rules: %s", sg_id, err) - } - - log.Printf("[DEBUG] Adding rules (%s) for security group %s:\n%s", ruleType, sg_id, addPerm) - switch ruleType { - case "ingress": - req := &ec2.AuthorizeSecurityGroupIngressInput{ - GroupId: aws.String(sg_id), - IpPermissions: []*ec2.IpPermission{addPerm}, - } - - _, err = conn.AuthorizeSecurityGroupIngress(req) - case "egress": - req := &ec2.AuthorizeSecurityGroupEgressInput{ - GroupId: aws.String(sg_id), - IpPermissions: []*ec2.IpPermission{addPerm}, - } - - _, err = conn.AuthorizeSecurityGroupEgress(req) - } - if err != nil { - return fmt.Errorf("Error adding security group %s rules: %s", sg_id, err) - } - - return nil -} - // validateSecurityGroupRuleImportString does minimal validation of import string without going to AWS func validateSecurityGroupRuleImportString(importStr string) ([]string, error) { // example: sg-09a093729ef9382a6_ingress_tcp_8000_8000_10.0.3.0/24 @@ -1095,9 +981,9 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s d.Set("to_port", toPort) d.Set("self", false) - cidrs := schema.Set{F: schema.HashString} + var cidrs []string var prefixList []string - ipv6cidrs := schema.Set{F: schema.HashString} + var ipv6cidrs []string for _, source := range sources { if source == "self" { d.Set("self", true) @@ -1106,13 +992,13 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s } else if strings.Contains(source, "pl-") { prefixList = append(prefixList, source) } else if strings.Contains(source, ":") { - ipv6cidrs.Add(source) + ipv6cidrs = append(ipv6cidrs, source) } else { - cidrs.Add(source) + cidrs = append(cidrs, source) } } - d.Set("ipv6_cidr_blocks", &ipv6cidrs) - d.Set("cidr_blocks", &cidrs) + d.Set("ipv6_cidr_blocks", ipv6cidrs) + d.Set("cidr_blocks", cidrs) d.Set("prefix_list_ids", prefixList) return nil From 2c0978bf3ae12b83407fb26bb0623d071c1aaf7c Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 17:00:44 -0400 Subject: [PATCH 007/120] Revert "Validate that security group names aren't prefixed with sg-" This reverts commit c9544f51af4b9a32b75ae6281a92269beb5de5c2. --- aws/resource_aws_security_group.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/aws/resource_aws_security_group.go b/aws/resource_aws_security_group.go index 959a96fe08c3..8b43234d871b 100644 --- a/aws/resource_aws_security_group.go +++ b/aws/resource_aws_security_group.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "log" - "regexp" "sort" "strconv" "strings" @@ -48,10 +47,7 @@ func resourceAwsSecurityGroup() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: validation.All( - validation.StringLenBetween(0, 255), - validation.StringDoesNotMatch(regexp.MustCompile(`^sg-`), "cannot begin with sg-"), - ), + ValidateFunc: validation.StringLenBetween(0, 255), }, "name_prefix": { From 750c381d8340632e9db094e7ceedb470f159975d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 17:02:15 -0400 Subject: [PATCH 008/120] Revert "Change the default description for inline security group rules to """ This reverts commit 807d6911c7c257898dce55d9a086e72bf7710dd8. --- internal/service/ec2/security_group.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index 72593cab51bd..b450fe3ed60e 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -140,7 +140,6 @@ func ResourceSecurityGroup() *schema.Resource { "description": { Type: schema.TypeString, Optional: true, - Default: "", ValidateFunc: validSecurityGroupRuleDescription, }, }, @@ -211,7 +210,6 @@ func ResourceSecurityGroup() *schema.Resource { "description": { Type: schema.TypeString, Optional: true, - Default: "", ValidateFunc: validSecurityGroupRuleDescription, }, }, From d3523edf3734cdf83d8da5c7032f90bcf1f7f693 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 17:03:24 -0400 Subject: [PATCH 009/120] Revert "Use sets for security groups" This reverts commit e2fcdf207996f5b1ca2103c81cd30e9691748c7f. --- internal/service/ec2/security_group.go | 113 ++++++++++-------- .../ec2/security_group_rules_matching_test.go | 103 ++++++++-------- internal/service/ec2/security_group_test.go | 40 +++---- 3 files changed, 139 insertions(+), 117 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index f79f7cd2495c..b450fe3ed60e 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -101,7 +101,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "cidr_blocks": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -110,7 +110,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "ipv6_cidr_blocks": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -171,7 +171,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "cidr_blocks": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -180,7 +180,7 @@ func ResourceSecurityGroup() *schema.Resource { }, "ipv6_cidr_blocks": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, @@ -537,7 +537,7 @@ func SecurityGroupRuleHash(v interface{}) int { // 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.(*schema.Set).List() + vs := v.([]interface{}) s := make([]string, len(vs)) for i, raw := range vs { s[i] = raw.(string) @@ -549,7 +549,7 @@ func SecurityGroupRuleHash(v interface{}) int { } } if v, ok := m["ipv6_cidr_blocks"]; ok { - vs := v.(*schema.Set).List() + vs := v.([]interface{}) s := make([]string, len(vs)) for i, raw := range vs { s[i] = raw.(string) @@ -602,12 +602,11 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, raw, ok := rule["cidr_blocks"] if !ok { - raw = schema.NewSet(schema.HashString, nil) + raw = make([]string, 0) } - list := raw.(*schema.Set) + list := raw.([]string) - list.Add(*ip.CidrIp) - rule["cidr_blocks"] = list + rule["cidr_blocks"] = append(list, *ip.CidrIp) } } @@ -619,11 +618,11 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, raw, ok := rule["ipv6_cidr_blocks"] if !ok { - raw = schema.NewSet(schema.HashString, nil) + raw = make([]string, 0) } - list := raw.(*schema.Set) - list.Add(*ip.CidrIpv6) - rule["ipv6_cidr_blocks"] = list + list := raw.([]string) + + rule["ipv6_cidr_blocks"] = append(list, *ip.CidrIpv6) } } @@ -829,11 +828,11 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface // actual counts lcRaw, ok := l["cidr_blocks"] if ok { - numExpectedCidrs = len(l["cidr_blocks"].(*schema.Set).List()) + numExpectedCidrs = len(l["cidr_blocks"].([]interface{})) } liRaw, ok := l["ipv6_cidr_blocks"] if ok { - numExpectedIpv6Cidrs = len(l["ipv6_cidr_blocks"].(*schema.Set).List()) + numExpectedIpv6Cidrs = len(l["ipv6_cidr_blocks"].([]interface{})) } lpRaw, ok := l["prefix_list_ids"] if ok { @@ -846,11 +845,11 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface rcRaw, ok := r["cidr_blocks"] if ok { - numRemoteCidrs = len(r["cidr_blocks"].(*schema.Set).List()) + numRemoteCidrs = len(r["cidr_blocks"].([]string)) } riRaw, ok := r["ipv6_cidr_blocks"] if ok { - numRemoteIpv6Cidrs = len(r["ipv6_cidr_blocks"].(*schema.Set).List()) + numRemoteIpv6Cidrs = len(r["ipv6_cidr_blocks"].([]string)) } rpRaw, ok := r["prefix_list_ids"] if ok { @@ -880,20 +879,26 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface continue } - // match CIDRs. Both local and remote are already sets - var localCidrSet *schema.Set - if lcRaw == nil { - localCidrSet = schema.NewSet(schema.HashString, nil) - } else { - localCidrSet = lcRaw.(*schema.Set) + // 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) - var remoteCidrSet *schema.Set - if rcRaw == nil { - remoteCidrSet = schema.NewSet(schema.HashString, nil) - } else { - remoteCidrSet = rcRaw.(*schema.Set) + // 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() { @@ -903,19 +908,21 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface } //IPV6 CIDRs - var localIpv6CidrSet *schema.Set - if liRaw == nil { - localIpv6CidrSet = schema.NewSet(schema.HashString, nil) - } else { - localIpv6CidrSet = liRaw.(*schema.Set) + var localIpv6Cidrs []interface{} + if liRaw != nil { + localIpv6Cidrs = liRaw.([]interface{}) } + localIpv6CidrSet := schema.NewSet(schema.HashString, localIpv6Cidrs) - var remoteIpv6CidrSet *schema.Set - if riRaw == nil { - remoteIpv6CidrSet = schema.NewSet(schema.HashString, nil) - } else { - remoteIpv6CidrSet = rcRaw.(*schema.Set) + 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) { @@ -938,7 +945,7 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface remotePrefixLists = rpRaw.([]string) } // convert remote prefix lists to a set, for easy comparison - var list []interface{} = nil + list = nil for _, s := range remotePrefixLists { list = append(list, s) } @@ -993,10 +1000,14 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface if rSelf == lSelf { delete(r, "self") // pop local cidrs from remote - newCidr := remoteCidrSet.Difference(localCidrSet) + diffCidr := remoteCidrSet.Difference(localCidrSet) + var newCidr []string + for _, cRaw := range diffCidr.List() { + newCidr = append(newCidr, cRaw.(string)) + } // reassigning - if newCidr.Len() > 0 { + if len(newCidr) > 0 { r["cidr_blocks"] = newCidr } else { delete(r, "cidr_blocks") @@ -1004,10 +1015,14 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface //// IPV6 //// Comparison - newIpv6Cidr := remoteIpv6CidrSet.Difference(localIpv6CidrSet) + diffIpv6Cidr := remoteIpv6CidrSet.Difference(localIpv6CidrSet) + var newIpv6Cidr []string + for _, cRaw := range diffIpv6Cidr.List() { + newIpv6Cidr = append(newIpv6Cidr, cRaw.(string)) + } // reassigning - if newIpv6Cidr.Len() > 0 { + if len(newIpv6Cidr) > 0 { r["ipv6_cidr_blocks"] = newIpv6Cidr } else { delete(r, "ipv6_cidr_blocks") @@ -1057,10 +1072,10 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface for _, r := range remote { var lenCidr, lenIpv6Cidr, lenPrefixLists, lenSGs int if rCidrs, ok := r["cidr_blocks"]; ok { - lenCidr = rCidrs.(*schema.Set).Len() + lenCidr = len(rCidrs.([]string)) } if rIpv6Cidrs, ok := r["ipv6_cidr_blocks"]; ok { - lenIpv6Cidr = rIpv6Cidrs.(*schema.Set).Len() + lenIpv6Cidr = len(rIpv6Cidrs.([]string)) } if rPrefixLists, ok := r["prefix_list_ids"]; ok { lenPrefixLists = len(rPrefixLists.([]string)) @@ -1134,7 +1149,7 @@ func SecurityGroupCollapseRules(ruleset string, rules []interface{}) []interface for _, key := range keys_to_collapse { if _, ok := r[key]; ok { if _, ok := collapsed[ruleHash][key]; ok { - if key != "prefix_list_ids" { + if key == "security_groups" { collapsed[ruleHash][key] = collapsed[ruleHash][key].(*schema.Set).Union(r[key].(*schema.Set)) } else { collapsed[ruleHash][key] = append(collapsed[ruleHash][key].([]interface{}), r[key].([]interface{})...) @@ -1215,14 +1230,14 @@ func SecurityGroupExpandRules(rules *schema.Set) *schema.Set { item, exists := rule[key] if exists { var list []interface{} - if key != "prefix_list_ids" { + if key == "security_groups" { list = item.(*schema.Set).List() } else { list = item.([]interface{}) } for _, v := range list { var new_rule map[string]interface{} - if key != "prefix_list_ids" { + if key == "security_groups" { new_v := schema.NewSet(schema.HashString, nil) new_v.Add(v) new_rule = resourceSecurityGroupCopyRule(rule, false, key, new_v) diff --git a/internal/service/ec2/security_group_rules_matching_test.go b/internal/service/ec2/security_group_rules_matching_test.go index 15756c32a1b5..058f08a19830 100644 --- a/internal/service/ec2/security_group_rules_matching_test.go +++ b/internal/service/ec2/security_group_rules_matching_test.go @@ -21,7 +21,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16", "10.0.0.0/16"}, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -30,7 +30,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -39,7 +39,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -58,7 +58,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -73,7 +73,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, }, }, @@ -83,7 +83,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16", "10.0.0.0/16"}, }, }, remote: []map[string]interface{}{ @@ -91,7 +91,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, }, saves: []map[string]interface{}{ @@ -99,7 +99,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, }, }, @@ -135,13 +135,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16"}, }, map[string]interface{}{ "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), + "cidr_blocks": []interface{}{"192.168.0.0/16"}, }, }, remote: []map[string]interface{}{ @@ -149,7 +149,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, }, saves: []map[string]interface{}{ @@ -157,13 +157,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16"}, }, { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), + "cidr_blocks": []string{"192.168.0.0/16"}, }, }, }, @@ -174,7 +174,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, }, saves: []map[string]interface{}{ @@ -182,7 +182,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.0.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, }, }, @@ -217,7 +217,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16"}, }, }, remote: []map[string]interface{}{ @@ -225,7 +225,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"10.0.0.0/16"}), + "cidr_blocks": []string{"10.0.0.0/16"}, }, }, // Because this is the remote rule being saved, we need to check for int64 @@ -236,7 +236,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"10.0.0.0/16"}), + "cidr_blocks": []string{"10.0.0.0/16"}, }, }, }, @@ -247,7 +247,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}, }, }, remote: []map[string]interface{}{ @@ -255,7 +255,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, }, saves: []map[string]interface{}{ @@ -263,7 +263,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, }, }, @@ -275,19 +275,19 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16"}, }, map[string]interface{}{ "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"10.8.0.0/16"}), + "cidr_blocks": []interface{}{"10.8.0.0/16"}, }, map[string]interface{}{ "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), + "cidr_blocks": []interface{}{"192.168.0.0/16"}, }, }, remote: []map[string]interface{}{ @@ -295,7 +295,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, }, saves: []map[string]interface{}{ @@ -303,13 +303,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16"}, }, { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16"}), + "cidr_blocks": []string{"192.168.0.0/16"}, }, }, }, @@ -321,7 +321,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16"}, }, }, remote: []map[string]interface{}{ @@ -329,7 +329,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16", "10.8.0.0/16", "206.8.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16", "10.8.0.0/16", "206.8.0.0/16"}, }, }, saves: []map[string]interface{}{ @@ -337,13 +337,13 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "10.8.0.0/16"}, }, { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"192.168.0.0/16", "206.8.0.0/16"}), + "cidr_blocks": []string{"192.168.0.0/16", "206.8.0.0/16"}, }, }, }, @@ -511,7 +511,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}, }, map[string]interface{}{ "from_port": 80, @@ -525,7 +525,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -534,7 +534,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, { "from_port": int64(80), @@ -550,7 +550,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": 80, "to_port": 8000, "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []interface{}{"172.8.0.0/16", "10.8.0.0/16", "192.168.0.0/16"}, }, map[string]interface{}{ "from_port": 80, @@ -564,7 +564,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, "self": true, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, @@ -580,7 +580,7 @@ func TestRulesMixedMatching(t *testing.T) { "from_port": int64(80), "to_port": int64(8000), "protocol": "tcp", - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{"172.8.0.0/16", "192.168.0.0/16"}), + "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, }, @@ -616,9 +616,9 @@ func TestRulesMixedMatching(t *testing.T) { if _, ok := s["cidr_blocks"]; ok { switch s["cidr_blocks"].(type) { case []string: - numExpectedCidrs = s["cidr_blocks"].(*schema.Set).Len() + numExpectedCidrs = len(s["cidr_blocks"].([]string)) default: - numExpectedCidrs = s["cidr_blocks"].(*schema.Set).Len() + numExpectedCidrs = len(s["cidr_blocks"].([]interface{})) } } @@ -627,7 +627,7 @@ func TestRulesMixedMatching(t *testing.T) { } if _, ok := cs["cidr_blocks"]; ok { - numRemoteCidrs = cs["cidr_blocks"].(*schema.Set).Len() + numRemoteCidrs = len(cs["cidr_blocks"].([]string)) } if _, ok := cs["security_groups"]; ok { @@ -652,20 +652,27 @@ func TestRulesMixedMatching(t *testing.T) { } // convert save cidrs to set - var savesCidrs *schema.Set + var lcs []interface{} if _, ok := s["cidr_blocks"]; ok { - savesCidrs = s["cidr_blocks"].(*schema.Set) - } else { - savesCidrs = schema.NewSet(schema.HashString, nil) + switch s["cidr_blocks"].(type) { + case []string: + for _, c := range s["cidr_blocks"].([]string) { + lcs = append(lcs, c) + } + default: + lcs = append(lcs, s["cidr_blocks"].([]interface{})...) + } } + savesCidrs := schema.NewSet(schema.HashString, lcs) // convert cs cidrs to set - var csCidrs *schema.Set + var cslcs []interface{} if _, ok := cs["cidr_blocks"]; ok { - csCidrs = cs["cidr_blocks"].(*schema.Set) - } else { - csCidrs = schema.NewSet(schema.HashString, nil) + for _, c := range cs["cidr_blocks"].([]string) { + cslcs = append(cslcs, c) + } } + csCidrs := schema.NewSet(schema.HashString, cslcs) if csCidrs.Equal(savesCidrs) { log.Printf("\nmatched cidrs") diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index ef828db8c1ba..d159fb467d61 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -158,11 +158,11 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": true, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "10.0.0.1/32", "10.0.0.2/32", "10.0.0.3/32", - }), + }, }, map[string]interface{}{ "protocol": "tcp", @@ -170,10 +170,10 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with another description", "self": false, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "192.168.0.1/32", "192.168.0.2/32", - }), + }, }, map[string]interface{}{ "protocol": "-1", @@ -181,10 +181,10 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(8080), "description": "", "self": false, - "ipv6_cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "ipv6_cidr_blocks": []interface{}{ "fd00::1/128", "fd00::2/128", - }), + }, "security_groups": schema.NewSet(schema.HashString, []interface{}{ "sg-11111", "sg-22222", @@ -218,9 +218,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": false, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "10.0.0.1/32", - }), + }, }, map[string]interface{}{ "protocol": "tcp", @@ -228,9 +228,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": false, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "10.0.0.2/32", - }), + }, }, map[string]interface{}{ "protocol": "tcp", @@ -238,9 +238,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with description", "self": false, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "10.0.0.3/32", - }), + }, }, map[string]interface{}{ "protocol": "tcp", @@ -248,9 +248,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with another description", "self": false, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "192.168.0.1/32", - }), + }, }, map[string]interface{}{ "protocol": "tcp", @@ -258,9 +258,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(443), "description": "block with another description", "self": false, - "cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "cidr_blocks": []interface{}{ "192.168.0.2/32", - }), + }, }, map[string]interface{}{ "protocol": "-1", @@ -268,9 +268,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(8080), "description": "", "self": false, - "ipv6_cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "ipv6_cidr_blocks": []interface{}{ "fd00::1/128", - }), + }, }, map[string]interface{}{ "protocol": "-1", @@ -278,9 +278,9 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { "to_port": int(8080), "description": "", "self": false, - "ipv6_cidr_blocks": schema.NewSet(schema.HashString, []interface{}{ + "ipv6_cidr_blocks": []interface{}{ "fd00::2/128", - }), + }, }, map[string]interface{}{ "protocol": "-1", From 1f50e115006975ccb66d6f8906df4a3907435a1c Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 17:05:42 -0400 Subject: [PATCH 010/120] Revert "d/aws_security_group: more verbose error on dne" This reverts commit 1a5a1ded5ef764e2d2709def39ed67e051b2f072. --- aws/data_source_aws_security_group.go | 16 ++-------- aws/data_source_aws_security_group_test.go | 35 ---------------------- 2 files changed, 3 insertions(+), 48 deletions(-) diff --git a/aws/data_source_aws_security_group.go b/aws/data_source_aws_security_group.go index 06da6142e8b4..a3ffc8f52ef7 100644 --- a/aws/data_source_aws_security_group.go +++ b/aws/data_source_aws_security_group.go @@ -59,13 +59,10 @@ func dataSourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) er req.GroupIds = []*string{aws.String(id.(string))} } - group_name := d.Get("name").(string) - vpc_id := d.Get("vpc_id").(string) - req.Filters = buildEC2AttributeFilterList( map[string]string{ - "group-name": group_name, - "vpc-id": vpc_id, + "group-name": d.Get("name").(string), + "vpc-id": d.Get("vpc_id").(string), }, ) req.Filters = append(req.Filters, buildEC2TagFilterList( @@ -85,14 +82,7 @@ func dataSourceAwsSecurityGroupRead(d *schema.ResourceData, meta interface{}) er return err } if resp == nil || len(resp.SecurityGroups) == 0 { - - err_msg := "" - if group_name != "" && vpc_id != "" { - err_msg = fmt.Sprintf(": %s/%s", vpc_id, group_name) - } else if group_name != "" { - err_msg = fmt.Sprintf(": %s", group_name) - } - return fmt.Errorf("no matching SecurityGroup found%s", err_msg) + return fmt.Errorf("no matching SecurityGroup found") } if len(resp.SecurityGroups) > 1 { return fmt.Errorf("multiple Security Groups matched; use additional constraints to reduce matches to a single Security Group") diff --git a/aws/data_source_aws_security_group_test.go b/aws/data_source_aws_security_group_test.go index 86c5e7927904..75b6b2ce03ca 100644 --- a/aws/data_source_aws_security_group_test.go +++ b/aws/data_source_aws_security_group_test.go @@ -2,7 +2,6 @@ package aws import ( "fmt" - "regexp" "testing" "strings" @@ -33,23 +32,6 @@ func TestAccDataSourceAwsSecurityGroup_basic(t *testing.T) { }) } -func TestAccDataSourceAwsSecurityGroup_dne(t *testing.T) { - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourceAwsSecurityGroupConfigDne(), - ExpectError: regexp.MustCompile(`no matching SecurityGroup found: dne`), - }, - { - Config: testAccDataSourceAwsSecurityGroupConfigDneVpc(), - ExpectError: regexp.MustCompile(`no matching SecurityGroup found: vpc-xxxxxxx/dne`), - }, - }, - }) -} - func testAccDataSourceAwsSecurityGroupCheck(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] @@ -169,20 +151,3 @@ data "aws_security_group" "by_filter" { } `, rInt, rInt) } - -func testAccDataSourceAwsSecurityGroupConfigDne() string { - return ` -data "aws_security_group" "dne" { - name = "dne" -} -` -} - -func testAccDataSourceAwsSecurityGroupConfigDneVpc() string { - return ` -data "aws_security_group" "dne_vpc" { - name = "dne" - vpc_id = "vpc-xxxxxxx" -} -` -} From 7fb349674e967754715845fa9e80d91ef316e031 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 17:24:26 -0400 Subject: [PATCH 011/120] r/aws_security_group: Alphabetize attributes. --- internal/service/ec2/security_group.go | 149 ++++++++++--------------- 1 file changed, 62 insertions(+), 87 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index 7c94bf3b2ef2..176cab7f78b3 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -44,24 +44,10 @@ func ResourceSecurityGroup() *schema.Resource { MigrateState: SecurityGroupMigrateState, 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, - Computed: true, - ForceNew: true, - ConflictsWith: []string{"name"}, - ValidateFunc: validation.StringLenBetween(0, 100), + "arn": { + Type: schema.TypeString, + Computed: true, }, - "description": { Type: schema.TypeString, Optional: true, @@ -69,37 +55,13 @@ func ResourceSecurityGroup() *schema.Resource { Default: "Managed by Terraform", ValidateFunc: validation.StringLenBetween(0, 255), }, - - "vpc_id": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Computed: true, - }, - - "ingress": { + "egress": { Type: schema.TypeSet, Optional: true, Computed: true, ConfigMode: schema.SchemaConfigModeAttr, 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, @@ -108,7 +70,15 @@ func ResourceSecurityGroup() *schema.Resource { ValidateFunc: verify.ValidCIDRNetworkAddress, }, }, - + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validSecurityGroupRuleDescription, + }, + "from_port": { + Type: schema.TypeInt, + Required: true, + }, "ipv6_cidr_blocks": { Type: schema.TypeList, Optional: true, @@ -117,59 +87,42 @@ func ResourceSecurityGroup() *schema.Resource { ValidateFunc: verify.ValidCIDRNetworkAddress, }, }, - "prefix_list_ids": { Type: schema.TypeList, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - + "protocol": { + Type: schema.TypeString, + Required: true, + StateFunc: ProtocolStateFunc, + }, "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: validSecurityGroupRuleDescription, + "to_port": { + Type: schema.TypeInt, + Required: true, }, }, }, Set: SecurityGroupRuleHash, }, - - "egress": { + "ingress": { Type: schema.TypeSet, Optional: true, Computed: true, ConfigMode: schema.SchemaConfigModeAttr, 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, @@ -178,7 +131,15 @@ func ResourceSecurityGroup() *schema.Resource { ValidateFunc: verify.ValidCIDRNetworkAddress, }, }, - + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validSecurityGroupRuleDescription, + }, + "from_port": { + Type: schema.TypeInt, + Required: true, + }, "ipv6_cidr_blocks": { Type: schema.TypeList, Optional: true, @@ -187,54 +148,68 @@ func ResourceSecurityGroup() *schema.Resource { ValidateFunc: verify.ValidCIDRNetworkAddress, }, }, - "prefix_list_ids": { Type: schema.TypeList, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - + "protocol": { + Type: schema.TypeString, + Required: true, + StateFunc: ProtocolStateFunc, + }, "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: validSecurityGroupRuleDescription, + "to_port": { + Type: schema.TypeInt, + Required: true, }, }, }, Set: SecurityGroupRuleHash, }, - - "arn": { - Type: schema.TypeString, - Computed: true, + "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, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"name"}, + ValidateFunc: validation.StringLenBetween(0, 100), }, - "owner_id": { Type: schema.TypeString, Computed: true, }, - - "tags": tftags.TagsSchema(), - "tags_all": tftags.TagsSchemaComputed(), - "revoke_rules_on_delete": { Type: schema.TypeBool, Default: false, Optional: true, }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + "vpc_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, }, CustomizeDiff: verify.SetTagsDiff, From 4287bf494db949d859874c9d1a759e6c72c036a5 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 13 Mar 2022 17:33:17 -0400 Subject: [PATCH 012/120] r/aws_security_group: Extract 'securityGroupRuleResource'. --- internal/service/ec2/security_group.go | 190 +++++++++---------------- 1 file changed, 68 insertions(+), 122 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index 176cab7f78b3..54ac6bbc8476 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -24,6 +24,15 @@ import ( ) func ResourceSecurityGroup() *schema.Resource { + securityGroupRuleSetSchema := &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: securityGroupRuleResource, + Set: SecurityGroupRuleHash, + } + //lintignore:R011 return &schema.Resource{ Create: resourceSecurityGroupCreate, @@ -55,128 +64,8 @@ func ResourceSecurityGroup() *schema.Resource { Default: "Managed by Terraform", ValidateFunc: validation.StringLenBetween(0, 255), }, - "egress": { - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validSecurityGroupRuleDescription, - }, - "from_port": { - Type: schema.TypeInt, - Required: true, - }, - "ipv6_cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "prefix_list_ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "protocol": { - Type: schema.TypeString, - Required: true, - StateFunc: ProtocolStateFunc, - }, - "security_groups": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "self": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "to_port": { - Type: schema.TypeInt, - Required: true, - }, - }, - }, - Set: SecurityGroupRuleHash, - }, - "ingress": { - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validSecurityGroupRuleDescription, - }, - "from_port": { - Type: schema.TypeInt, - Required: true, - }, - "ipv6_cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "prefix_list_ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "protocol": { - Type: schema.TypeString, - Required: true, - StateFunc: ProtocolStateFunc, - }, - "security_groups": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "self": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "to_port": { - Type: schema.TypeInt, - Required: true, - }, - }, - }, - Set: SecurityGroupRuleHash, - }, + "egress": securityGroupRuleSetSchema, + "ingress": securityGroupRuleSetSchema, "name": { Type: schema.TypeString, Optional: true, @@ -216,6 +105,63 @@ func ResourceSecurityGroup() *schema.Resource { } } +// Security Group rule Resource definition. +// Used in aws_security_group and aws_default_security_group ingress and egress rule sets. +var securityGroupRuleResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidCIDRNetworkAddress, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validSecurityGroupRuleDescription, + }, + "from_port": { + Type: schema.TypeInt, + Required: true, + }, + "ipv6_cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidCIDRNetworkAddress, + }, + }, + "prefix_list_ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "protocol": { + Type: schema.TypeString, + Required: true, + StateFunc: ProtocolStateFunc, + }, + "security_groups": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "self": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "to_port": { + Type: schema.TypeInt, + Required: true, + }, + }, +} + func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig From 3fe6944765c5ad121a633c9c94f5e8b27c9c3fdf Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 14 Mar 2022 07:42:38 -0400 Subject: [PATCH 013/120] Use 'NestedBlock' rather than 'Resource' in rule schema variable names. --- internal/service/ec2/security_group.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index 54ac6bbc8476..d08849c64d70 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -24,12 +24,12 @@ import ( ) func ResourceSecurityGroup() *schema.Resource { - securityGroupRuleSetSchema := &schema.Schema{ + securityGroupRuleSetNestedBlock := &schema.Schema{ Type: schema.TypeSet, Optional: true, Computed: true, ConfigMode: schema.SchemaConfigModeAttr, - Elem: securityGroupRuleResource, + Elem: securityGroupRuleNestedBlock, Set: SecurityGroupRuleHash, } @@ -64,8 +64,8 @@ func ResourceSecurityGroup() *schema.Resource { Default: "Managed by Terraform", ValidateFunc: validation.StringLenBetween(0, 255), }, - "egress": securityGroupRuleSetSchema, - "ingress": securityGroupRuleSetSchema, + "egress": securityGroupRuleSetNestedBlock, + "ingress": securityGroupRuleSetNestedBlock, "name": { Type: schema.TypeString, Optional: true, @@ -105,9 +105,9 @@ func ResourceSecurityGroup() *schema.Resource { } } -// Security Group rule Resource definition. +// Security Group rule nested block definition. // Used in aws_security_group and aws_default_security_group ingress and egress rule sets. -var securityGroupRuleResource = &schema.Resource{ +var securityGroupRuleNestedBlock = &schema.Resource{ Schema: map[string]*schema.Schema{ "cidr_blocks": { Type: schema.TypeList, From 5f3457b35a9c66cac53589a4a068503b7170987f Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 14 Mar 2022 07:44:23 -0400 Subject: [PATCH 014/120] Use 'NestedBlock' rather than 'Resource' in rule schema variable names. --- internal/service/ec2/default_network_acl.go | 8 ++++---- internal/service/ec2/network_acl.go | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/service/ec2/default_network_acl.go b/internal/service/ec2/default_network_acl.go index fa0c554240da..1cfbf67694fd 100644 --- a/internal/service/ec2/default_network_acl.go +++ b/internal/service/ec2/default_network_acl.go @@ -21,10 +21,10 @@ const ( ) func ResourceDefaultNetworkACL() *schema.Resource { - networkACLRuleSetSchema := &schema.Schema{ + networkACLRuleSetNestedBlock := &schema.Schema{ Type: schema.TypeSet, Optional: true, - Elem: networkACLRuleResource, + Elem: networkACLRuleNestedBlock, Set: networkACLRuleHash, } @@ -60,8 +60,8 @@ func ResourceDefaultNetworkACL() *schema.Resource { // We want explicit management of Rules here, so we do not allow them to be // computed. Instead, an empty config will enforce just that; removal of the // rules - "egress": networkACLRuleSetSchema, - "ingress": networkACLRuleSetSchema, + "egress": networkACLRuleSetNestedBlock, + "ingress": networkACLRuleSetNestedBlock, "owner_id": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/ec2/network_acl.go b/internal/service/ec2/network_acl.go index 2a1d253d5286..648648429144 100644 --- a/internal/service/ec2/network_acl.go +++ b/internal/service/ec2/network_acl.go @@ -21,12 +21,12 @@ import ( ) func ResourceNetworkACL() *schema.Resource { - networkACLRuleSetSchema := &schema.Schema{ + networkACLRuleSetNestedBlock := &schema.Schema{ Type: schema.TypeSet, Optional: true, Computed: true, ConfigMode: schema.SchemaConfigModeAttr, - Elem: networkACLRuleResource, + Elem: networkACLRuleNestedBlock, Set: networkACLRuleHash, } @@ -61,8 +61,8 @@ func ResourceNetworkACL() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "egress": networkACLRuleSetSchema, - "ingress": networkACLRuleSetSchema, + "egress": networkACLRuleSetNestedBlock, + "ingress": networkACLRuleSetNestedBlock, "owner_id": { Type: schema.TypeString, Computed: true, @@ -86,9 +86,9 @@ func ResourceNetworkACL() *schema.Resource { } } -// NACL rule Resource definition. +// NACL rule nested block definition. // Used in aws_network_acl and aws_default_network_acl ingress and egress rule sets. -var networkACLRuleResource = &schema.Resource{ +var networkACLRuleNestedBlock = &schema.Resource{ Schema: map[string]*schema.Schema{ "action": { Type: schema.TypeString, From 7bac015a92e402b758069efa23546f2889f3d1c8 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 18 Mar 2022 16:46:17 -0400 Subject: [PATCH 015/120] r/aws_security_group: Start to tidy up acceptance tests. Acceptance test output: % make testacc TESTARGS='-run=TestAccEC2SecurityGroup_name\|TestAccEC2SecurityGroup_basic' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccEC2SecurityGroup_name\|TestAccEC2SecurityGroup_basic -timeout 180m === RUN TestAccEC2SecurityGroup_basic === PAUSE TestAccEC2SecurityGroup_basic === RUN TestAccEC2SecurityGroup_basicEC2Classic === PAUSE TestAccEC2SecurityGroup_basicEC2Classic === RUN TestAccEC2SecurityGroup_nameGenerated === PAUSE TestAccEC2SecurityGroup_nameGenerated === RUN TestAccEC2SecurityGroup_nameTerraformPrefix === PAUSE TestAccEC2SecurityGroup_nameTerraformPrefix === RUN TestAccEC2SecurityGroup_namePrefix === PAUSE TestAccEC2SecurityGroup_namePrefix === RUN TestAccEC2SecurityGroup_namePrefixTerraform === PAUSE TestAccEC2SecurityGroup_namePrefixTerraform === CONT TestAccEC2SecurityGroup_basic === CONT TestAccEC2SecurityGroup_nameTerraformPrefix --- PASS: TestAccEC2SecurityGroup_nameTerraformPrefix (21.73s) === CONT TestAccEC2SecurityGroup_namePrefixTerraform --- PASS: TestAccEC2SecurityGroup_basic (21.90s) === CONT TestAccEC2SecurityGroup_namePrefix --- PASS: TestAccEC2SecurityGroup_namePrefix (20.44s) === CONT TestAccEC2SecurityGroup_nameGenerated --- PASS: TestAccEC2SecurityGroup_namePrefixTerraform (20.92s) === CONT TestAccEC2SecurityGroup_basicEC2Classic --- PASS: TestAccEC2SecurityGroup_basicEC2Classic (12.75s) --- PASS: TestAccEC2SecurityGroup_nameGenerated (20.79s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 66.843s --- internal/service/ec2/errors.go | 1 + internal/service/ec2/security_group.go | 91 +- internal/service/ec2/security_group_test.go | 1477 ++++++++++--------- 3 files changed, 775 insertions(+), 794 deletions(-) diff --git a/internal/service/ec2/errors.go b/internal/service/ec2/errors.go index 06d900ae606e..eb10bb797d0e 100644 --- a/internal/service/ec2/errors.go +++ b/internal/service/ec2/errors.go @@ -31,6 +31,7 @@ const ( ErrCodeInvalidDhcpOptionIDNotFound = "InvalidDhcpOptionID.NotFound" ErrCodeInvalidFlowLogIdNotFound = "InvalidFlowLogId.NotFound" ErrCodeInvalidGatewayIDNotFound = "InvalidGatewayID.NotFound" + ErrCodeInvalidGroupInUse = "InvalidGroup.InUse" ErrCodeInvalidGroupNotFound = "InvalidGroup.NotFound" ErrCodeInvalidHostIDNotFound = "InvalidHostID.NotFound" ErrCodeInvalidInstanceIDNotFound = "InvalidInstanceID.NotFound" diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index d08849c64d70..32e736eb20e1 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -167,28 +166,28 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - groupName := create.Name(d.Get("name").(string), d.Get("name_prefix").(string)) + name := create.Name(d.Get("name").(string), d.Get("name_prefix").(string)) input := &ec2.CreateSecurityGroupInput{ - GroupName: aws.String(groupName), + GroupName: aws.String(name), } if v := d.Get("description"); v != nil { input.Description = aws.String(v.(string)) } - if len(tags) > 0 { - input.TagSpecifications = ec2TagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeSecurityGroup) - } - if v, ok := d.GetOk("vpc_id"); ok { input.VpcId = aws.String(v.(string)) } + if len(tags) > 0 { + input.TagSpecifications = ec2TagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeSecurityGroup) + } + log.Printf("[DEBUG] Creating Security Group: %s", input) output, err := conn.CreateSecurityGroup(input) if err != nil { - return fmt.Errorf("error creating Security Group (%s): %w", groupName, err) + return fmt.Errorf("error creating Security Group (%s): %w", name, err) } d.SetId(aws.StringValue(output.GroupId)) @@ -203,10 +202,8 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error // 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. if aws.StringValue(group.VpcId) != "" { - log.Printf("[DEBUG] Revoking default egress rule for Security Group for %s", d.Id()) - input := &ec2.RevokeSecurityGroupEgressInput{ - GroupId: output.GroupId, + GroupId: aws.String(d.Id()), IpPermissions: []*ec2.IpPermission{ { FromPort: aws.Int64(0), @@ -221,13 +218,12 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error }, } - if _, err = conn.RevokeSecurityGroupEgress(input); err != nil { - return fmt.Errorf("Error revoking default egress rule for Security Group (%s): %w", d.Id(), err) + if _, err := conn.RevokeSecurityGroupEgress(input); err != nil { + return fmt.Errorf("error revoking default egress rule for Security Group (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Revoking default IPv6 egress rule for Security Group for %s", d.Id()) input = &ec2.RevokeSecurityGroupEgressInput{ - GroupId: output.GroupId, + GroupId: aws.String(d.Id()), IpPermissions: []*ec2.IpPermission{ { FromPort: aws.Int64(0), @@ -242,12 +238,11 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error }, } - _, err = conn.RevokeSecurityGroupEgress(input) - if err != nil { + if _, err := conn.RevokeSecurityGroupEgress(input); 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 !tfawserr.ErrCodeEquals(err, ErrCodeInvalidPermissionNotFound) && !tfawserr.ErrMessageContains(err, ErrCodeInvalidParameterValue, "remote-ipv6-range") { - return fmt.Errorf("Error revoking default IPv6 egress rule for Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("error revoking default IPv6 egress rule for Security Group (%s): %w", d.Id(), err) } } @@ -284,19 +279,19 @@ func resourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { ingressRules := MatchRules("ingress", localIngressRules, remoteIngressRules) egressRules := MatchRules("egress", localEgressRules, remoteEgressRules) - sgArn := arn.ARN{ - AccountID: aws.StringValue(sg.OwnerId), + ownerID := aws.StringValue(sg.OwnerId) + arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Region: meta.(*conns.AWSClient).Region, - Resource: fmt.Sprintf("security-group/%s", aws.StringValue(sg.GroupId)), Service: ec2.ServiceName, + Region: meta.(*conns.AWSClient).Region, + AccountID: ownerID, + Resource: fmt.Sprintf("security-group/%s", d.Id()), } - - d.Set("arn", sgArn.String()) + d.Set("arn", arn.String()) d.Set("description", sg.Description) d.Set("name", sg.GroupName) d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(sg.GroupName))) - d.Set("owner_id", sg.OwnerId) + d.Set("owner_id", ownerID) d.Set("vpc_id", sg.VpcId) if err := d.Set("ingress", ingressRules); err != nil { @@ -355,8 +350,6 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - log.Printf("[DEBUG] Security Group destroy: %v", d.Id()) - if err := deleteLingeringLambdaENIs(conn, "group-id", d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return fmt.Errorf("error deleting Lambda ENIs using Security Group (%s): %w", d.Id(), err) } @@ -367,42 +360,26 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error return err } } - input := &ec2.DeleteSecurityGroupInput{ - GroupId: aws.String(d.Id()), - } - err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { - _, err := conn.DeleteSecurityGroup(input) - if err != nil { - if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { - return nil - } - - // If it is a dependency violation, we want to retry - if tfawserr.ErrMessageContains(err, "DependencyViolation", "has a dependent object") { - return resource.RetryableError(err) - } - - if tfawserr.ErrCodeEquals(err, "DependencyViolation") { - return resource.RetryableError(err) - } - if tfawserr.ErrCodeEquals(err, "InvalidGroup.InUse") { - return resource.RetryableError(err) - } + log.Printf("[DEBUG] Deleting Security Group: %s", d.Id()) + _, err := tfresource.RetryWhenAWSErrCodeEquals( + d.Timeout(schema.TimeoutDelete), + func() (interface{}, error) { + return conn.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{ + GroupId: aws.String(d.Id()), + }) + }, + ErrCodeDependencyViolation, ErrCodeInvalidGroupInUse, + ) - return resource.NonRetryableError(err) - } + if tfawserr.ErrCodeEquals(err, ErrCodeInvalidGroupNotFound) { return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.DeleteSecurityGroup(input) - if tfawserr.ErrCodeEquals(err, "InvalidGroup.NotFound") { - return nil - } } + if err != nil { - return fmt.Errorf("Error deleting security group: %w", err) + return fmt.Errorf("error deleting Security Group (%s): %w", d.Id(), err) } + return nil } diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index f07470b5ad96..3e6b6a3e3d0d 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -163,7 +163,7 @@ func TestProtocolForValue(t *testing.T) { } func calcSecurityGroupChecksum(rules []interface{}) int { - var sum int = 0 + sum := 0 for _, rule := range rules { sum += tfec2.SecurityGroupRuleHash(rule) } @@ -496,9 +496,10 @@ func TestSecurityGroupIPPermGather(t *testing.T) { } } -func TestAccEC2SecurityGroup_allowAll(t *testing.T) { +func TestAccEC2SecurityGroup_basic(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -507,9 +508,108 @@ func TestAccEC2SecurityGroup_allowAll(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_allowAll, + Config: testAccSecurityGroupNameConfig(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`security-group/.+$`)), + resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), + resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "revoke_rules_on_delete", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttrSet(resourceName, "vpc_id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + }, + }) +} + +func TestAccEC2SecurityGroup_basicEC2Classic(t *testing.T) { + var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupClassicDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupEC2ClassicConfig(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupClassicExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), + resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "revoke_rules_on_delete", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "vpc_id", ""), + ), + }, + { + Config: testAccSecurityGroupEC2ClassicConfig(rName), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + }, + }) +} + +func TestAccEC2SecurityGroup_disappears(t *testing.T) { + var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupNameConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), + acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSecurityGroup(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccEC2SecurityGroup_nameGenerated(t *testing.T) { + var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupNameGeneratedConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + create.TestCheckResourceAttrNameGenerated(resourceName, "name"), + resource.TestCheckResourceAttr(resourceName, "name_prefix", resource.UniqueIdPrefix), ), }, { @@ -522,9 +622,11 @@ func TestAccEC2SecurityGroup_allowAll(t *testing.T) { }) } -func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { +// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 +func TestAccEC2SecurityGroup_nameTerraformPrefix(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix("terraform-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -533,9 +635,11 @@ func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_sourceSecurityGroup, + Config: testAccSecurityGroupNameConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), ), }, { @@ -548,9 +652,10 @@ func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) { +func TestAccEC2SecurityGroup_namePrefix(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -559,9 +664,11 @@ func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules, + Config: testAccSecurityGroupNamePrefixConfig(rName, "tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), + create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), + resource.TestCheckResourceAttr(resourceName, "name_prefix", "tf-acc-test-prefix-"), ), }, { @@ -574,9 +681,11 @@ func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) }) } -func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { +// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 +func TestAccEC2SecurityGroup_namePrefixTerraform(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -585,9 +694,11 @@ func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_IPRangesWithSameRules, + Config: testAccSecurityGroupNamePrefixConfig(rName, "terraform-test"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), + create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "terraform-test"), + resource.TestCheckResourceAttr(resourceName, "name_prefix", "terraform-test"), ), }, { @@ -600,7 +711,7 @@ func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { }) } -func TestAccEC2SecurityGroup_basic(t *testing.T) { +func TestAccEC2SecurityGroup_allowAll(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -611,26 +722,9 @@ func TestAccEC2SecurityGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig, + Config: testAccSecurityGroupConfig_allowAll, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupAttributes(&group), - acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`security-group/.+$`)), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ - "cidr_blocks.#": "1", - "cidr_blocks.0": "10.0.0.0/8", - "description": "", - "from_port": "80", - "ipv6_cidr_blocks.#": "0", - "protocol": "tcp", - "security_groups.#": "0", - "self": "false", - "to_port": "8000", - }), ), }, { @@ -643,7 +737,7 @@ func TestAccEC2SecurityGroup_basic(t *testing.T) { }) } -func TestAccEC2SecurityGroup_disappears(t *testing.T) { +func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -654,12 +748,68 @@ func TestAccEC2SecurityGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig, + Config: testAccSecurityGroupConfig_sourceSecurityGroup, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSecurityGroup(), resourceName), ), - ExpectNonEmptyPlan: true, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + }, + }) +} + +func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) { + var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules, + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + }, + }) +} + +func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { + var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupConfig_IPRangesWithSameRules, + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1046,10 +1196,24 @@ func TestAccEC2SecurityGroup_ipv6(t *testing.T) { }) } -func TestAccEC2SecurityGroup_Name_generated(t *testing.T) { +func TestAccEC2SecurityGroup_self(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + checkSelf := func(s *terraform.State) (err error) { + defer func() { + if e := recover(); e != nil { + err = fmt.Errorf("bad: %#v", group) + } + }() + + if *group.IpPermissions[0].UserIdGroupPairs[0].GroupId != *group.GroupId { + return fmt.Errorf("bad: %#v", group) + } + + return nil + } + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -1057,11 +1221,18 @@ func TestAccEC2SecurityGroup_Name_generated(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_generatedName, + Config: testAccSecurityGroupSelfConfig, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - create.TestCheckResourceAttrNameGenerated(resourceName, "name"), - resource.TestCheckResourceAttr(resourceName, "name_prefix", "terraform-"), + resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), + resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "self": "true", + }), + checkSelf, ), }, { @@ -1074,8 +1245,7 @@ func TestAccEC2SecurityGroup_Name_generated(t *testing.T) { }) } -// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 -func TestAccEC2SecurityGroup_Name_terraformPrefix(t *testing.T) { +func TestAccEC2SecurityGroup_vpc(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -1086,11 +1256,27 @@ func TestAccEC2SecurityGroup_Name_terraformPrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameConfig("terraform-test"), + Config: testAccSecurityGroupVPCConfig, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform-test"), - resource.TestCheckResourceAttr(resourceName, "name_prefix", ""), + testAccCheckSecurityGroupAttributes(&group), + resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), + resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + testAccSecurityGroupCheckVPCIDExists(&group), ), }, { @@ -1103,7 +1289,7 @@ func TestAccEC2SecurityGroup_Name_terraformPrefix(t *testing.T) { }) } -func TestAccEC2SecurityGroup_namePrefix(t *testing.T) { +func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -1114,11 +1300,20 @@ func TestAccEC2SecurityGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNamePrefixConfig("tf-acc-test-prefix-"), + Config: testAccSecurityGroupVPCNegOneIngressConfig, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), - resource.TestCheckResourceAttr(resourceName, "name_prefix", "tf-acc-test-prefix-"), + testAccCheckSecurityGroupAttributesNegOneProtocol(&group), + resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), + resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "-1", + "from_port": "0", + "to_port": "0", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + testAccSecurityGroupCheckVPCIDExists(&group), ), }, { @@ -1131,8 +1326,7 @@ func TestAccEC2SecurityGroup_namePrefix(t *testing.T) { }) } -// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 -func TestAccEC2SecurityGroup_NamePrefix_terraformPrefix(t *testing.T) { +func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -1143,165 +1337,7 @@ func TestAccEC2SecurityGroup_NamePrefix_terraformPrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNamePrefixConfig("terraform-test"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "terraform-test"), - resource.TestCheckResourceAttr(resourceName, "name_prefix", "terraform-test"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - }, - }) -} - -func TestAccEC2SecurityGroup_self(t *testing.T) { - var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - - checkSelf := func(s *terraform.State) (err error) { - defer func() { - if e := recover(); e != nil { - err = fmt.Errorf("bad: %#v", group) - } - }() - - if *group.IpPermissions[0].UserIdGroupPairs[0].GroupId != *group.GroupId { - return fmt.Errorf("bad: %#v", group) - } - - return nil - } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupSelfConfig, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ - "protocol": "tcp", - "from_port": "80", - "to_port": "8000", - "self": "true", - }), - checkSelf, - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - }, - }) -} - -func TestAccEC2SecurityGroup_vpc(t *testing.T) { - var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupVPCConfig, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupAttributes(&group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ - "protocol": "tcp", - "from_port": "80", - "to_port": "8000", - "cidr_blocks.#": "1", - "cidr_blocks.0": "10.0.0.0/8", - }), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ - "protocol": "tcp", - "from_port": "80", - "to_port": "8000", - "cidr_blocks.#": "1", - "cidr_blocks.0": "10.0.0.0/8", - }), - testAccSecurityGroupCheckVPCIDExists(&group), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - }, - }) -} - -func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { - var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupVPCNegOneIngressConfig, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupAttributesNegOneProtocol(&group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ - "protocol": "-1", - "from_port": "0", - "to_port": "0", - "cidr_blocks.#": "1", - "cidr_blocks.0": "10.0.0.0/8", - }), - testAccSecurityGroupCheckVPCIDExists(&group), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - }, - }) -} - -func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { - var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupVPCProtoNumIngressConfig, + Config: testAccSecurityGroupVPCProtoNumIngressConfig, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), @@ -1523,34 +1559,6 @@ func TestAccEC2SecurityGroup_defaultEgressVPC(t *testing.T) { }) } -func TestAccEC2SecurityGroup_defaultEgressClassic(t *testing.T) { - var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupClassicDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupClassicConfig(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupClassicExists(resourceName, &group), - ), - }, - { - Config: testAccSecurityGroupClassicConfig(rName), - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - }, - }) -} - // Testing drift detection with groups containing the same port and types func TestAccEC2SecurityGroup_drift(t *testing.T) { resourceName := "aws_security_group.test" @@ -1985,63 +1993,316 @@ func TestAccEC2SecurityGroup_ipv4AndIPv6Egress(t *testing.T) { }) } -func testAccSecurityGroupCheckVPCIDExists(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(*terraform.State) error { - if aws.StringValue(group.VpcId) == "" { - return fmt.Errorf("should have vpc ID") - } - return nil - } -} +func TestAccEC2SecurityGroup_failWithDiffMismatch(t *testing.T) { + var group ec2.SecurityGroup -// cycleIpPermForGroup returns an IpPermission struct with a configured -// UserIdGroupPair for the groupid given. Used in -// TestAccAWSSecurityGroup_forceRevokeRules_should_fail to create a cyclic rule -// between 2 security groups -func cycleIpPermForGroup(groupId string) *ec2.IpPermission { - var perm ec2.IpPermission - perm.FromPort = aws.Int64(0) - perm.ToPort = aws.Int64(0) - perm.IpProtocol = aws.String("icmp") - perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, 1) - perm.UserIdGroupPairs[0] = &ec2.UserIdGroupPair{ - GroupId: aws.String(groupId), - } - return &perm -} + resourceName := "aws_security_group.nat" -// testAddRuleCycle returns a TestCheckFunc to use at the end of a test, such -// that a Security Group Rule cyclic dependency will be created between the two -// Security Groups. A companion function, testRemoveRuleCycle, will undo this. -func testAddRuleCycle(primary, secondary *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if primary.GroupId == nil { - return fmt.Errorf("Primary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") - } - if secondary.GroupId == nil { - return fmt.Errorf("Secondary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupConfig_failWithDiffMismatch, + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), + ), + }, + }, + }) +} - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn +func TestAccEC2SecurityGroup_ruleLimitExceededAppend(t *testing.T) { + ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() - // cycle from primary to secondary - perm1 := cycleIpPermForGroup(*secondary.GroupId) - // cycle from secondary to primary - perm2 := cycleIpPermForGroup(*primary.GroupId) + var group ec2.SecurityGroup - req1 := &ec2.AuthorizeSecurityGroupEgressInput{ - GroupId: primary.GroupId, - IpPermissions: []*ec2.IpPermission{perm1}, - } - req2 := &ec2.AuthorizeSecurityGroupEgressInput{ - GroupId: secondary.GroupId, - IpPermissions: []*ec2.IpPermission{perm2}, - } + resourceName := "aws_security_group.test" - var err error - _, err = conn.AuthorizeSecurityGroupEgress(req1) - if err != nil { - return fmt.Errorf("Error authorizing primary security group %s rules: %w", aws.StringValue(primary.GroupId), err) + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + // create a valid SG just under the limit + { + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), + resource.TestCheckResourceAttr(resourceName, "egress.#", strconv.Itoa(ruleLimit)), + ), + }, + // append a rule to step over the limit + { + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit+1), + ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), + }, + { + PreConfig: func() { + // should have the original rules still + err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, ruleLimit) + if err != nil { + t.Fatalf("PreConfig check failed: %s", err) + } + }, + // running the original config again now should restore the rules + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), + resource.TestCheckResourceAttr(resourceName, "egress.#", strconv.Itoa(ruleLimit)), + ), + }, + }, + }) +} + +func TestAccEC2SecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { + ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() + + var group ec2.SecurityGroup + + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + // create a valid SG just under the limit + { + Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, 1), + ), + }, + // append a rule to step over the limit + { + Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit+1), + ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), + }, + { + PreConfig: func() { + // should have the original cidr blocks still in 1 rule + err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, 1) + if err != nil { + t.Fatalf("PreConfig check failed: %s", err) + } + + id := aws.StringValue(group.GroupId) + + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn + + match, err := tfec2.FindSecurityGroupByID(conn, id) + if tfresource.NotFound(err) { + t.Fatalf("PreConfig check failed: Security Group (%s) not found: %s", id, err) + } + if err != nil { + t.Fatalf("PreConfig check failed: %s", err) + } + + if cidrCount := len(match.IpPermissionsEgress[0].IpRanges); cidrCount != ruleLimit { + t.Fatalf("PreConfig check failed: rule does not have previous IP ranges, has %d", cidrCount) + } + }, + // running the original config again now should restore the rules + Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, 1), + ), + }, + }, + }) +} + +func TestAccEC2SecurityGroup_ruleLimitExceededPrepend(t *testing.T) { + ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() + + var group ec2.SecurityGroup + + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + // create a valid SG just under the limit + { + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), + ), + }, + // prepend a rule to step over the limit + { + Config: testAccSecurityGroupRuleLimitConfig(1, ruleLimit+1), + ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), + }, + { + PreConfig: func() { + // should have the original rules still (limit - 1 because of the shift) + err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, ruleLimit-1) + if err != nil { + t.Fatalf("PreConfig check failed: %s", err) + } + }, + // running the original config again now should restore the rules + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), + ), + }, + }, + }) +} + +func TestAccEC2SecurityGroup_ruleLimitExceededAllNew(t *testing.T) { + ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() + + var group ec2.SecurityGroup + + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + // create a valid SG just under the limit + { + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), + ), + }, + // add a rule to step over the limit with entirely new rules + { + Config: testAccSecurityGroupRuleLimitConfig(100, ruleLimit+1), + ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), + }, + { + // all the rules should have been revoked and the add failed + PreConfig: func() { + err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, 0) + if err != nil { + t.Fatalf("PreConfig check failed: %s", err) + } + }, + // running the original config again now should restore the rules + Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), + ), + }, + }, + }) +} + +func TestAccEC2SecurityGroup_rulesDropOnError(t *testing.T) { + var group ec2.SecurityGroup + + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + // Create a valid security group with some rules and make sure it exists + { + Config: testAccSecurityGroupConfig_rulesDropOnError_Init, + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + ), + }, + // Add a bad rule to trigger API error + { + Config: testAccSecurityGroupConfig_rulesDropOnError_AddBadRule, + ExpectError: regexp.MustCompile("InvalidGroup.NotFound"), + }, + // All originally added rules must survive. This will return non-empty plan if anything changed. + { + Config: testAccSecurityGroupConfig_rulesDropOnError_Init, + PlanOnly: true, + }, + }, + }) +} + +func testAccSecurityGroupCheckVPCIDExists(group *ec2.SecurityGroup) resource.TestCheckFunc { + return func(*terraform.State) error { + if aws.StringValue(group.VpcId) == "" { + return fmt.Errorf("should have vpc ID") + } + return nil + } +} + +// cycleIpPermForGroup returns an IpPermission struct with a configured +// UserIdGroupPair for the groupid given. Used in +// TestAccAWSSecurityGroup_forceRevokeRules_should_fail to create a cyclic rule +// between 2 security groups +func cycleIpPermForGroup(groupId string) *ec2.IpPermission { + var perm ec2.IpPermission + perm.FromPort = aws.Int64(0) + perm.ToPort = aws.Int64(0) + perm.IpProtocol = aws.String("icmp") + perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, 1) + perm.UserIdGroupPairs[0] = &ec2.UserIdGroupPair{ + GroupId: aws.String(groupId), + } + return &perm +} + +// testAddRuleCycle returns a TestCheckFunc to use at the end of a test, such +// that a Security Group Rule cyclic dependency will be created between the two +// Security Groups. A companion function, testRemoveRuleCycle, will undo this. +func testAddRuleCycle(primary, secondary *ec2.SecurityGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + if primary.GroupId == nil { + return fmt.Errorf("Primary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") + } + if secondary.GroupId == nil { + return fmt.Errorf("Secondary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn + + // cycle from primary to secondary + perm1 := cycleIpPermForGroup(*secondary.GroupId) + // cycle from secondary to primary + perm2 := cycleIpPermForGroup(*primary.GroupId) + + req1 := &ec2.AuthorizeSecurityGroupEgressInput{ + GroupId: primary.GroupId, + IpPermissions: []*ec2.IpPermission{perm1}, + } + req2 := &ec2.AuthorizeSecurityGroupEgressInput{ + GroupId: secondary.GroupId, + IpPermissions: []*ec2.IpPermission{perm2}, + } + + var err error + _, err = conn.AuthorizeSecurityGroupEgress(req1) + if err != nil { + return fmt.Errorf("Error authorizing primary security group %s rules: %w", aws.StringValue(primary.GroupId), err) } _, err = conn.AuthorizeSecurityGroupEgress(req2) if err != nil { @@ -2271,121 +2532,12 @@ func testAccSecurityGroupRulesPerGroupLimitFromEnv() int { } if envLimitInt <= 50 { return defaultLimit - } - return envLimitInt -} - -func testAccCheckSecurityGroupSGandCIDRAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.GroupName != "terraform_acceptance_test_example" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - - if len(group.IpPermissions) != 2 { - return fmt.Errorf("Expected 2 ingress rules, got %d", len(group.IpPermissions)) - } - - for _, p := range group.IpPermissions { - if *p.FromPort == int64(22) { - if len(p.IpRanges) != 1 || p.UserIdGroupPairs != nil { - return fmt.Errorf("Found ip perm of 22, but not the right ipranges / pairs: %s", p) - } - continue - } else if *p.FromPort == int64(80) { - if len(p.IpRanges) != 1 || len(p.UserIdGroupPairs) != 1 { - return fmt.Errorf("Found ip perm of 80, but not the right ipranges / pairs: %s", p) - } - continue - } - return fmt.Errorf("Found a rouge rule") - } - - return nil - } -} - -func testAccCheckSecurityGroupEgressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.GroupName != "terraform_acceptance_test_prefix_list_egress" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - if len(group.IpPermissionsEgress) == 0 { - return fmt.Errorf("No egress IPPerms") - } - if len(group.IpPermissionsEgress) != 1 { - return fmt.Errorf("Expected 1 egress rule, got %d", len(group.IpPermissions)) - } - - p := group.IpPermissionsEgress[0] - - if len(p.PrefixListIds) != 1 { - return fmt.Errorf("Expected 1 prefix list, got %d", len(p.PrefixListIds)) - } - - return nil - } -} - -func testAccCheckSecurityGroupIngressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.GroupName != "terraform_acceptance_test_prefix_list_ingress" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - if len(group.IpPermissions) != 1 { - return fmt.Errorf("Expected 1 rule, got %d", len(group.IpPermissions)) - } - - p := group.IpPermissions[0] - - if len(p.PrefixListIds) != 1 { - return fmt.Errorf("Expected 1 prefix list, got %d", len(p.PrefixListIds)) - } - - return nil - } -} - -func testAccCheckSecurityGroupAttributesChanged(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - p := []*ec2.IpPermission{ - { - FromPort: aws.Int64(80), - ToPort: aws.Int64(9000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - }, - { - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{ - { - CidrIp: aws.String("0.0.0.0/0"), - }, - { - CidrIp: aws.String("10.0.0.0/8"), - }, - }, - }, - } + } + return envLimitInt +} +func testAccCheckSecurityGroupSGandCIDRAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { if *group.GroupName != "terraform_acceptance_test_example" { return fmt.Errorf("Bad name: %s", *group.GroupName) } @@ -2394,317 +2546,173 @@ func testAccCheckSecurityGroupAttributesChanged(group *ec2.SecurityGroup) resour return fmt.Errorf("Bad description: %s", *group.Description) } - // Compare our ingress - if len(group.IpPermissions) != 2 { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions, - p) + if len(group.IpPermissions) == 0 { + return fmt.Errorf("No IPPerms") } - if *group.IpPermissions[0].ToPort == 8000 { - group.IpPermissions[1], group.IpPermissions[0] = - group.IpPermissions[0], group.IpPermissions[1] + if len(group.IpPermissions) != 2 { + return fmt.Errorf("Expected 2 ingress rules, got %d", len(group.IpPermissions)) } - if len(group.IpPermissions[1].IpRanges) > 1 { - if *group.IpPermissions[1].IpRanges[0].CidrIp != "0.0.0.0/0" { - group.IpPermissions[1].IpRanges[0], group.IpPermissions[1].IpRanges[1] = - group.IpPermissions[1].IpRanges[1], group.IpPermissions[1].IpRanges[0] + for _, p := range group.IpPermissions { + if *p.FromPort == int64(22) { + if len(p.IpRanges) != 1 || p.UserIdGroupPairs != nil { + return fmt.Errorf("Found ip perm of 22, but not the right ipranges / pairs: %s", p) + } + continue + } else if *p.FromPort == int64(80) { + if len(p.IpRanges) != 1 || len(p.UserIdGroupPairs) != 1 { + return fmt.Errorf("Found ip perm of 80, but not the right ipranges / pairs: %s", p) + } + continue } - } - - if !reflect.DeepEqual(group.IpPermissions, p) { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions, - p) + return fmt.Errorf("Found a rouge rule") } return nil } } -func testAccCheckSecurityGroupExistsWithoutDefault(n string) resource.TestCheckFunc { +func testAccCheckSecurityGroupEgressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) + if *group.GroupName != "terraform_acceptance_test_prefix_list_egress" { + return fmt.Errorf("Bad name: %s", *group.GroupName) } - - if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group is set") + if *group.Description != "Used in the terraform acceptance tests" { + return fmt.Errorf("Bad description: %s", *group.Description) } - - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - group, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - if tfresource.NotFound(err) { - return fmt.Errorf("Security Group (%s) not found: %w", rs.Primary.ID, err) + if len(group.IpPermissionsEgress) == 0 { + return fmt.Errorf("No egress IPPerms") } - if err != nil { - return err + if len(group.IpPermissionsEgress) != 1 { + return fmt.Errorf("Expected 1 egress rule, got %d", len(group.IpPermissions)) } - if len(group.IpPermissionsEgress) != 1 { - return fmt.Errorf("Security Group should have only 1 egress rule, got %d", len(group.IpPermissionsEgress)) + p := group.IpPermissionsEgress[0] + + if len(p.PrefixListIds) != 1 { + return fmt.Errorf("Expected 1 prefix list, got %d", len(p.PrefixListIds)) } return nil } } -func TestAccEC2SecurityGroup_failWithDiffMismatch(t *testing.T) { - var group ec2.SecurityGroup - - resourceName := "aws_security_group.nat" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupConfig_failWithDiffMismatch, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), - ), - }, - }, - }) -} - -func TestAccEC2SecurityGroup_ruleLimitExceededAppend(t *testing.T) { - ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() - - var group ec2.SecurityGroup - - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - // create a valid SG just under the limit - { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), - resource.TestCheckResourceAttr(resourceName, "egress.#", strconv.Itoa(ruleLimit)), - ), - }, - // append a rule to step over the limit - { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit+1), - ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), - }, - { - PreConfig: func() { - // should have the original rules still - err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, ruleLimit) - if err != nil { - t.Fatalf("PreConfig check failed: %s", err) - } - }, - // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), - resource.TestCheckResourceAttr(resourceName, "egress.#", strconv.Itoa(ruleLimit)), - ), - }, - }, - }) -} - -func TestAccEC2SecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { - ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() - - var group ec2.SecurityGroup - - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - // create a valid SG just under the limit - { - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, 1), - ), - }, - // append a rule to step over the limit - { - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit+1), - ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), - }, - { - PreConfig: func() { - // should have the original cidr blocks still in 1 rule - err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, 1) - if err != nil { - t.Fatalf("PreConfig check failed: %s", err) - } - - id := aws.StringValue(group.GroupId) - - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - match, err := tfec2.FindSecurityGroupByID(conn, id) - if tfresource.NotFound(err) { - t.Fatalf("PreConfig check failed: Security Group (%s) not found: %s", id, err) - } - if err != nil { - t.Fatalf("PreConfig check failed: %s", err) - } - - if cidrCount := len(match.IpPermissionsEgress[0].IpRanges); cidrCount != ruleLimit { - t.Fatalf("PreConfig check failed: rule does not have previous IP ranges, has %d", cidrCount) - } - }, - // running the original config again now should restore the rules - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, 1), - ), - }, - }, - }) -} - -func TestAccEC2SecurityGroup_ruleLimitExceededPrepend(t *testing.T) { - ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() - - var group ec2.SecurityGroup - - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - // create a valid SG just under the limit - { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), - ), - }, - // prepend a rule to step over the limit - { - Config: testAccSecurityGroupRuleLimitConfig(1, ruleLimit+1), - ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), - }, - { - PreConfig: func() { - // should have the original rules still (limit - 1 because of the shift) - err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, ruleLimit-1) - if err != nil { - t.Fatalf("PreConfig check failed: %s", err) - } - }, - // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), - ), - }, - }, - }) -} +func testAccCheckSecurityGroupIngressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + if *group.GroupName != "terraform_acceptance_test_prefix_list_ingress" { + return fmt.Errorf("Bad name: %s", *group.GroupName) + } + if *group.Description != "Used in the terraform acceptance tests" { + return fmt.Errorf("Bad description: %s", *group.Description) + } + if len(group.IpPermissions) == 0 { + return fmt.Errorf("No IPPerms") + } + if len(group.IpPermissions) != 1 { + return fmt.Errorf("Expected 1 rule, got %d", len(group.IpPermissions)) + } -func TestAccEC2SecurityGroup_ruleLimitExceededAllNew(t *testing.T) { - ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() + p := group.IpPermissions[0] - var group ec2.SecurityGroup + if len(p.PrefixListIds) != 1 { + return fmt.Errorf("Expected 1 prefix list, got %d", len(p.PrefixListIds)) + } - resourceName := "aws_security_group.test" + return nil + } +} - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - // create a valid SG just under the limit - { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), - ), - }, - // add a rule to step over the limit with entirely new rules +func testAccCheckSecurityGroupAttributesChanged(group *ec2.SecurityGroup) resource.TestCheckFunc { + return func(s *terraform.State) error { + p := []*ec2.IpPermission{ { - Config: testAccSecurityGroupRuleLimitConfig(100, ruleLimit+1), - ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), + FromPort: aws.Int64(80), + ToPort: aws.Int64(9000), + IpProtocol: aws.String("tcp"), + IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, }, { - // all the rules should have been revoked and the add failed - PreConfig: func() { - err := testSecurityGroupRuleCount(aws.StringValue(group.GroupId), 0, 0) - if err != nil { - t.Fatalf("PreConfig check failed: %s", err) - } + FromPort: aws.Int64(80), + ToPort: aws.Int64(8000), + IpProtocol: aws.String("tcp"), + IpRanges: []*ec2.IpRange{ + { + CidrIp: aws.String("0.0.0.0/0"), + }, + { + CidrIp: aws.String("10.0.0.0/8"), + }, }, - // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), - ), }, - }, - }) + } + + if *group.GroupName != "terraform_acceptance_test_example" { + return fmt.Errorf("Bad name: %s", *group.GroupName) + } + + if *group.Description != "Used in the terraform acceptance tests" { + return fmt.Errorf("Bad description: %s", *group.Description) + } + + // Compare our ingress + if len(group.IpPermissions) != 2 { + return fmt.Errorf( + "Got:\n\n%#v\n\nExpected:\n\n%#v\n", + group.IpPermissions, + p) + } + + if *group.IpPermissions[0].ToPort == 8000 { + group.IpPermissions[1], group.IpPermissions[0] = + group.IpPermissions[0], group.IpPermissions[1] + } + + if len(group.IpPermissions[1].IpRanges) > 1 { + if *group.IpPermissions[1].IpRanges[0].CidrIp != "0.0.0.0/0" { + group.IpPermissions[1].IpRanges[0], group.IpPermissions[1].IpRanges[1] = + group.IpPermissions[1].IpRanges[1], group.IpPermissions[1].IpRanges[0] + } + } + + if !reflect.DeepEqual(group.IpPermissions, p) { + return fmt.Errorf( + "Got:\n\n%#v\n\nExpected:\n\n%#v\n", + group.IpPermissions, + p) + } + + return nil + } } -func TestAccEC2SecurityGroup_rulesDropOnError(t *testing.T) { - var group ec2.SecurityGroup +func testAccCheckSecurityGroupExistsWithoutDefault(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } - resourceName := "aws_security_group.test" + if rs.Primary.ID == "" { + return fmt.Errorf("No Security Group is set") + } - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - // Create a valid security group with some rules and make sure it exists - { - Config: testAccSecurityGroupConfig_rulesDropOnError_Init, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - ), - }, - // Add a bad rule to trigger API error - { - Config: testAccSecurityGroupConfig_rulesDropOnError_AddBadRule, - ExpectError: regexp.MustCompile("InvalidGroup.NotFound"), - }, - // All originally added rules must survive. This will return non-empty plan if anything changed. - { - Config: testAccSecurityGroupConfig_rulesDropOnError_Init, - PlanOnly: true, - }, - }, - }) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn + + group, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if tfresource.NotFound(err) { + return fmt.Errorf("Security Group (%s) not found: %w", rs.Primary.ID, err) + } + if err != nil { + return err + } + + if len(group.IpPermissionsEgress) != 1 { + return fmt.Errorf("Security Group should have only 1 egress rule, got %d", len(group.IpPermissionsEgress)) + } + + return nil + } } func testAccCheckSecurityGroupRuleCount(group *ec2.SecurityGroup, expectedIngressCount, expectedEgressCount int) resource.TestCheckFunc { @@ -2736,6 +2744,64 @@ func testSecurityGroupRuleCount(id string, expectedIngressCount, expectedEgressC return nil } +func testAccSecurityGroupNameConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id +} +`, rName) +} + +func testAccSecurityGroupEC2ClassicConfig(rName string) string { + return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q +} +`, rName)) +} + +func testAccSecurityGroupNameGeneratedConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + vpc_id = aws_vpc.test.id +} +`, rName) +} + +func testAccSecurityGroupNamePrefixConfig(rName, namePrefix string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + name_prefix = %[2]q + vpc_id = aws_vpc.test.id +} +`, rName, namePrefix) +} + func testAccSecurityGroupRuleLimitConfig(egressStartIndex, egressRulesCount int) string { var egressRules strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { @@ -3303,24 +3369,6 @@ resource "aws_security_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -const testAccSecurityGroupConfig_generatedName = ` -resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-security-group-generated-name" - } -} - -resource "aws_security_group" "test" { - vpc_id = aws_vpc.foo.id - - tags = { - Name = "tf-acc-test" - } -} -` - const testAccSecurityGroupDefaultEgressConfig = ` resource "aws_vpc" "tf_sg_egress_test" { cidr_block = "10.0.0.0/16" @@ -3344,51 +3392,6 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupClassicConfig(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigEC2ClassicRegionProvider(), - fmt.Sprintf(` -resource "aws_security_group" "test" { - name = %[1]q - description = "Used in the terraform acceptance tests" -} -`, rName)) -} - -func testAccSecurityGroupNameConfig(name string) string { - return fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" - - tags = { - Name = "tf-acc-test-security-group-name" - } -} - -resource "aws_security_group" "test" { - name = %[1]q - vpc_id = aws_vpc.test.id -} -`, name) -} - -func testAccSecurityGroupNamePrefixConfig(namePrefix string) string { - return fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" - - tags = { - Name = "tf-acc-test-security-group-name-prefix" - } -} - -resource "aws_security_group" "test" { - name_prefix = %[1]q - vpc_id = aws_vpc.test.id -} -`, namePrefix) -} - func testAccSecurityGroupConfig_drift() string { return fmt.Sprintf(` resource "aws_security_group" "test" { From 505f61668c0fab4c8aecad8199f3c0f91d8680f5 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 28 Mar 2022 13:45:53 -0400 Subject: [PATCH 016/120] Tidy up 'forceRevokeSecurityGroupRules'. --- internal/service/ec2/security_group.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index 32e736eb20e1..6ecd085b9575 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -356,7 +356,11 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error // 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 { + if err := forceRevokeSecurityGroupRules(conn, d.Id()); err != nil { + if tfawserr.ErrCodeEquals(err, ErrCodeInvalidGroupNotFound) { + return nil + } + return err } } @@ -383,11 +387,12 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error return nil } -// Revoke all ingress/egress rules that a Security Group has -func forceRevokeSecurityGroupRules(conn *ec2.EC2, d *schema.ResourceData) error { - group, err := FindSecurityGroupByID(conn, d.Id()) +// forceRevokeSecurityGroupRules revokes all of the specified Security Group's ingress & egress rules. +func forceRevokeSecurityGroupRules(conn *ec2.EC2, id string) error { + group, err := FindSecurityGroupByID(conn, id) + if err != nil { - return err + return fmt.Errorf("error reading Security Group (%s): %w", id, err) } if len(group.IpPermissions) > 0 { @@ -402,7 +407,7 @@ func forceRevokeSecurityGroupRules(conn *ec2.EC2, d *schema.ResourceData) error _, err = conn.RevokeSecurityGroupIngress(req) if err != nil { - return fmt.Errorf("error revoking Security Group (%s) rules: %w", aws.StringValue(group.GroupId), err) + return fmt.Errorf("error revoking Security Group (%s) ingress rules: %w", id, err) } } @@ -414,7 +419,7 @@ func forceRevokeSecurityGroupRules(conn *ec2.EC2, d *schema.ResourceData) error _, err = conn.RevokeSecurityGroupEgress(req) if err != nil { - return fmt.Errorf("error revoking Security Group (%s) rules: %w", aws.StringValue(group.GroupId), err) + return fmt.Errorf("error revoking Security Group (%s) egress rules: %w", id, err) } } From 734568539addab64b42faf14c9beea56aa482fa7 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 28 Mar 2022 14:20:15 -0400 Subject: [PATCH 017/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_allowAll'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_allowAll PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run='TestAccEC2SecurityGroup_allowAll' -timeout 180m === RUN TestAccEC2SecurityGroup_allowAll === PAUSE TestAccEC2SecurityGroup_allowAll === CONT TestAccEC2SecurityGroup_allowAll --- PASS: TestAccEC2SecurityGroup_allowAll (24.83s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.634s --- internal/service/ec2/security_group_test.go | 244 ++++++++++---------- 1 file changed, 123 insertions(+), 121 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 3e6b6a3e3d0d..57ac2fa16b81 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -542,12 +542,12 @@ func TestAccEC2SecurityGroup_basicEC2Classic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupClassicDestroy, + CheckDestroy: testAccCheckSecurityGroupEC2ClassicDestroy, Steps: []resource.TestStep{ { Config: testAccSecurityGroupEC2ClassicConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckSecurityGroupClassicExists(resourceName, &group), + testAccCheckSecurityGroupEC2ClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -711,9 +711,56 @@ func TestAccEC2SecurityGroup_namePrefixTerraform(t *testing.T) { }) } +func TestAccEC2SecurityGroup_tags(t *testing.T) { + var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + { + Config: testAccSecurityGroupConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccSecurityGroupConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func TestAccEC2SecurityGroup_allowAll(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -722,7 +769,7 @@ func TestAccEC2SecurityGroup_allowAll(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_allowAll, + Config: testAccSecurityGroupAllowAllConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1719,52 +1766,6 @@ func TestAccEC2SecurityGroup_invalidCIDRBlock(t *testing.T) { }) } -func TestAccEC2SecurityGroup_tags(t *testing.T) { - var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupTags1Config(rName, "key1", "value1"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - { - Config: testAccSecurityGroupTags2Config(rName, "key1", "value1updated", "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - ), - }, - { - Config: testAccSecurityGroupTags1Config(rName, "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - ), - }, - }, - }) -} - func TestAccEC2SecurityGroup_cidrAndGroups(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -1853,12 +1854,12 @@ func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupClassicDestroy, + CheckDestroy: testAccCheckSecurityGroupEC2ClassicDestroy, Steps: []resource.TestStep{ { Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupClassicExists(resourceName, &group), + testAccCheckSecurityGroupEC2ClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ @@ -2361,9 +2362,11 @@ func testAccCheckSecurityGroupDestroy(s *terraform.State) error { } _, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if tfresource.NotFound(err) { continue } + if err != nil { return err } @@ -2374,7 +2377,7 @@ func testAccCheckSecurityGroupDestroy(s *terraform.State) error { return nil } -func testAccCheckSecurityGroupClassicDestroy(s *terraform.State) error { +func testAccCheckSecurityGroupEC2ClassicDestroy(s *terraform.State) error { conn := acctest.ProviderEC2Classic.Meta().(*conns.AWSClient).EC2Conn for _, rs := range s.RootModule().Resources { @@ -2383,20 +2386,22 @@ func testAccCheckSecurityGroupClassicDestroy(s *terraform.State) error { } _, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if tfresource.NotFound(err) { continue } + if err != nil { return err } - return fmt.Errorf("Security Group (%s) still exists.", rs.Primary.ID) + return fmt.Errorf("EC2 Classic Security Group (%s) still exists.", rs.Primary.ID) } return nil } -func testAccCheckSecurityGroupExists(n string, group *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -2404,26 +2409,24 @@ func testAccCheckSecurityGroupExists(n string, group *ec2.SecurityGroup) resourc } if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group is set") + return fmt.Errorf("No Security Group ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - sg, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - if tfresource.NotFound(err) { - return fmt.Errorf("Security Group (%s) not found: %w", rs.Primary.ID, err) - } + output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if err != nil { return err } - *group = *sg + *v = *output return nil } } -func testAccCheckSecurityGroupClassicExists(n string, group *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckSecurityGroupEC2ClassicExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -2431,20 +2434,18 @@ func testAccCheckSecurityGroupClassicExists(n string, group *ec2.SecurityGroup) } if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group is set") + return fmt.Errorf("No EC2 Classic Security Group ID is set") } conn := acctest.ProviderEC2Classic.Meta().(*conns.AWSClient).EC2Conn - sg, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - if tfresource.NotFound(err) { - return fmt.Errorf("Security Group (%s) not found: %w", rs.Primary.ID, err) - } + output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if err != nil { return err } - *group = *sg + *v = *output return nil } @@ -2802,6 +2803,49 @@ resource "aws_security_group" "test" { `, rName, namePrefix) } +func testAccSecurityGroupConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccSecurityGroupConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} + func testAccSecurityGroupRuleLimitConfig(egressStartIndex, egressRulesCount int) string { var egressRules strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { @@ -3324,51 +3368,6 @@ resource "aws_security_group" "test2" { } ` -func testAccSecurityGroupTags1Config(rName, tagKey1, tagValue1 string) string { - return fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = %[1]q - } -} - -resource "aws_security_group" "test" { - name = %[1]q - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.test.id - - tags = { - %[2]q = %[3]q - } -} -`, rName, tagKey1, tagValue1) -} - -func testAccSecurityGroupTags2Config(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return fmt.Sprintf(` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = %[1]q - } -} - -resource "aws_security_group" "test" { - name = %[1]q - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.test.id - - tags = { - %[2]q = %[3]q - %[4]q = %[5]q - } -} -`, rName, tagKey1, tagValue1, tagKey2, tagValue2) -} - const testAccSecurityGroupDefaultEgressConfig = ` resource "aws_vpc" "tf_sg_egress_test" { cidr_block = "10.0.0.0/16" @@ -3660,9 +3659,7 @@ resource "aws_security_group" "test" { ` func testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName string) string { - return acctest.ConfigCompose( - acctest.ConfigEC2ClassicRegionProvider(), - fmt.Sprintf(` + return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_security_group" "test2" { name = "%[1]s-2" description = "Used in the terraform acceptance tests" @@ -3748,19 +3745,23 @@ resource "aws_security_group" "nat" { } ` -const testAccSecurityGroupConfig_allowAll = ` +func testAccSecurityGroupAllowAllConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-allow-all" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "allow_all" - description = "Allow all inbound traffic" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.foo.id + + tags = { + Name = %[1]q + } } resource "aws_security_group_rule" "allow_all" { @@ -3782,7 +3783,8 @@ resource "aws_security_group_rule" "allow_all-1" { self = true security_group_id = aws_security_group.test.id } -` +`, rName) +} const testAccSecurityGroupConfig_sourceSecurityGroup = ` resource "aws_vpc" "foo" { From 188f116b08acf269eb4bf0b5323bf4d442cec2ff Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 28 Mar 2022 14:42:06 -0400 Subject: [PATCH 018/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_sourceSecurityGroup'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_sourceSecurityGroup PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run='TestAccEC2SecurityGroup_sourceSecurityGroup' -timeout 180m === RUN TestAccEC2SecurityGroup_sourceSecurityGroup === PAUSE TestAccEC2SecurityGroup_sourceSecurityGroup === CONT TestAccEC2SecurityGroup_sourceSecurityGroup --- PASS: TestAccEC2SecurityGroup_sourceSecurityGroup (23.02s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 26.803s --- internal/service/ec2/security_group_test.go | 37 +++++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 57ac2fa16b81..e135f0363300 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -787,6 +787,7 @@ func TestAccEC2SecurityGroup_allowAll(t *testing.T) { func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -795,7 +796,7 @@ func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_sourceSecurityGroup, + Config: testAccSecurityGroupSourceSecurityGroupConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -3786,28 +3787,41 @@ resource "aws_security_group_rule" "allow_all-1" { `, rName) } -const testAccSecurityGroupConfig_sourceSecurityGroup = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupSourceSecurityGroupConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-source-sg" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "test group 1" - vpc_id = aws_vpc.foo.id + name = "%[1]s-1" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test2" { - name = "test group 2" - vpc_id = aws_vpc.foo.id + name = "%[1]s-2" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test3" { - name = "test group 3" - vpc_id = aws_vpc.foo.id + name = "%[1]s-3" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group_rule" "allow_test2" { @@ -3829,7 +3843,8 @@ resource "aws_security_group_rule" "allow_test3" { source_security_group_id = aws_security_group.test.id security_group_id = aws_security_group.test3.id } -` +`, rName) +} const testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules = ` resource "aws_vpc" "foo" { From 505a700d5b34066a33a4571304b471eae16e646f Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 28 Mar 2022 14:52:22 -0400 Subject: [PATCH 019/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run='TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules' -timeout 180m === RUN TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules === PAUSE TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules === CONT TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules --- PASS: TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules (26.71s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 30.458s --- internal/service/ec2/security_group_test.go | 37 +++++++++++++-------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index e135f0363300..980843d1b1b4 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -814,6 +814,7 @@ func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -822,7 +823,7 @@ func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules, + Config: testAccSecurityGroupIPRangeAndSecurityGroupWithSameRulesConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -3846,24 +3847,33 @@ resource "aws_security_group_rule" "allow_test3" { `, rName) } -const testAccSecurityGroupConfig_IPRangeAndSecurityGroupWithSameRules = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupIPRangeAndSecurityGroupWithSameRulesConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-import-ip-range-and-sg" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "test group 1" - vpc_id = aws_vpc.foo.id -} - -resource "aws_security_group" "test2" { - name = "test group 2" - vpc_id = aws_vpc.foo.id -} + name = "%[1]s-1" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } + } + + resource "aws_security_group" "test2" { + name = "%[1]s-2" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } + } resource "aws_security_group_rule" "allow_security_group" { type = "ingress" @@ -3894,7 +3904,8 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { ipv6_cidr_blocks = ["::/0"] security_group_id = aws_security_group.test.id } -` +`, rName) +} const testAccSecurityGroupConfig_IPRangesWithSameRules = ` resource "aws_vpc" "foo" { From b141b9f16a4c7bc304eda97b55d16d25f229effa Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 28 Mar 2022 14:59:04 -0400 Subject: [PATCH 020/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_ipRangesWithSameRules'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_ipRangesWithSameRules PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run='TestAccEC2SecurityGroup_ipRangesWithSameRules' -timeout 180m === RUN TestAccEC2SecurityGroup_ipRangesWithSameRules === PAUSE TestAccEC2SecurityGroup_ipRangesWithSameRules === CONT TestAccEC2SecurityGroup_ipRangesWithSameRules --- PASS: TestAccEC2SecurityGroup_ipRangesWithSameRules (24.28s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.137s --- internal/service/ec2/security_group_test.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 980843d1b1b4..33ae98cd7b76 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -841,6 +841,7 @@ func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -849,7 +850,7 @@ func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_IPRangesWithSameRules, + Config: testAccSecurityGroupIPRangesWithSameRulesConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -3907,18 +3908,23 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { `, rName) } -const testAccSecurityGroupConfig_IPRangesWithSameRules = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupIPRangesWithSameRulesConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-import-ip-ranges" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "test group 1" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group_rule" "allow_cidr_block" { @@ -3940,7 +3946,8 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { ipv6_cidr_blocks = ["::/0"] security_group_id = aws_security_group.test.id } -` +`, rName) +} const testAccSecurityGroupIPv4andIpv6EgressConfig = ` resource "aws_vpc" "foo" { From 37abfd0d6716dcf6d48b926354a576b45378eab6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 28 Mar 2022 15:13:32 -0400 Subject: [PATCH 021/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_egressMode' and 'TestAccEC2SecurityGroup_ingressMode'. Acceptance test output: % make testacc TESTARGS='-run=TestAccEC2SecurityGroup_egressMode\|TestAccEC2SecurityGroup_ingressMode' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccEC2SecurityGroup_egressMode\|TestAccEC2SecurityGroup_ingressMode -timeout 180m === RUN TestAccEC2SecurityGroup_egressMode === PAUSE TestAccEC2SecurityGroup_egressMode === RUN TestAccEC2SecurityGroup_ingressMode === PAUSE TestAccEC2SecurityGroup_ingressMode === CONT TestAccEC2SecurityGroup_egressMode === CONT TestAccEC2SecurityGroup_ingressMode --- PASS: TestAccEC2SecurityGroup_ingressMode (49.02s) --- PASS: TestAccEC2SecurityGroup_egressMode (52.66s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 56.406s --- internal/service/ec2/security_group_test.go | 90 ++++++++++++--------- 1 file changed, 52 insertions(+), 38 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 33ae98cd7b76..3dc8d3d34831 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -868,6 +868,7 @@ func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { func TestAccEC2SecurityGroup_egressMode(t *testing.T) { var securityGroup1, securityGroup2, securityGroup3 ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -876,7 +877,7 @@ func TestAccEC2SecurityGroup_egressMode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupEgressModeBlocksConfig(), + Config: testAccSecurityGroupEgressModeBlocksConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup1), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -889,14 +890,14 @@ func TestAccEC2SecurityGroup_egressMode(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupEgressModeNoBlocksConfig(), + Config: testAccSecurityGroupEgressModeNoBlocksConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup2), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), ), }, { - Config: testAccSecurityGroupEgressModeZeroedConfig(), + Config: testAccSecurityGroupEgressModeZeroedConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup3), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -909,6 +910,7 @@ func TestAccEC2SecurityGroup_egressMode(t *testing.T) { func TestAccEC2SecurityGroup_ingressMode(t *testing.T) { var securityGroup1, securityGroup2, securityGroup3 ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -917,7 +919,7 @@ func TestAccEC2SecurityGroup_ingressMode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIngressModeBlocksConfig(), + Config: testAccSecurityGroupIngressModeBlocksConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup1), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), @@ -930,14 +932,14 @@ func TestAccEC2SecurityGroup_ingressMode(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupIngressModeNoBlocksConfig(), + Config: testAccSecurityGroupIngressModeNoBlocksConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup2), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), ), }, { - Config: testAccSecurityGroupIngressModeZeroedConfig(), + Config: testAccSecurityGroupIngressModeZeroedConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup3), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -4286,19 +4288,21 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupEgressModeBlocksConfig() string { - return ` +func testAccSecurityGroupEgressModeBlocksConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-egress-config-mode" + Name = %[1]q } } resource "aws_security_group" "test" { + name = %[1]q + tags = { - Name = "terraform-testacc-security-group-egress-config-mode" + Name = %[1]q } vpc_id = aws_vpc.test.id @@ -4317,64 +4321,70 @@ resource "aws_security_group" "test" { to_port = 0 } } -` +`, rName) } -func testAccSecurityGroupEgressModeNoBlocksConfig() string { - return ` +func testAccSecurityGroupEgressModeNoBlocksConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-egress-config-mode" + Name = %[1]q } } resource "aws_security_group" "test" { + name = %[1]q + tags = { - Name = "terraform-testacc-security-group-egress-config-mode" + Name = %[1]q } vpc_id = aws_vpc.test.id } -` +`, rName) } -func testAccSecurityGroupEgressModeZeroedConfig() string { - return ` +func testAccSecurityGroupEgressModeZeroedConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-egress-config-mode" + Name = %[1]q } } resource "aws_security_group" "test" { - egress = [] + name = %[1]q tags = { - Name = "terraform-testacc-security-group-egress-config-mode" + Name = %[1]q } + egress = [] + vpc_id = aws_vpc.test.id } -` +`, rName) } -func testAccSecurityGroupIngressModeBlocksConfig() string { - return ` +func testAccSecurityGroupIngressModeBlocksConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-ingress-config-mode" + Name = %[1]q } } resource "aws_security_group" "test" { + name = %[1]q + tags = { - Name = "terraform-testacc-security-group-ingress-config-mode" + Name = %[1]q } vpc_id = aws_vpc.test.id @@ -4393,47 +4403,51 @@ resource "aws_security_group" "test" { to_port = 0 } } -` +`, rName) } -func testAccSecurityGroupIngressModeNoBlocksConfig() string { - return ` +func testAccSecurityGroupIngressModeNoBlocksConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-ingress-config-mode" + Name = %[1]q } } resource "aws_security_group" "test" { + name = %[1]q + tags = { - Name = "terraform-testacc-security-group-ingress-config-mode" + Name = %[1]q } vpc_id = aws_vpc.test.id } -` +`, rName) } -func testAccSecurityGroupIngressModeZeroedConfig() string { - return ` +func testAccSecurityGroupIngressModeZeroedConfig(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-ingress-config-mode" + Name = %[1]q } } resource "aws_security_group" "test" { - ingress = [] + name = %[1]q tags = { - Name = "terraform-testacc-security-group-ingress-config-mode" + Name = %[1]q } + ingress = [] + vpc_id = aws_vpc.test.id } -` +`, rName) } From a70a00b9e60df29cc61ec671b55316817c142e7b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 31 Mar 2022 14:39:01 -0400 Subject: [PATCH 022/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_ruleGathering'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_ruleGathering PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_ruleGathering' -timeout 180m === RUN TestAccEC2SecurityGroup_ruleGathering === PAUSE TestAccEC2SecurityGroup_ruleGathering === CONT TestAccEC2SecurityGroup_ruleGathering --- PASS: TestAccEC2SecurityGroup_ruleGathering (39.16s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 42.926s --- internal/service/ec2/security_group_test.go | 55 +++++++++++++-------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 3dc8d3d34831..21a88bb25d0e 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -951,7 +951,7 @@ func TestAccEC2SecurityGroup_ingressMode(t *testing.T) { func TestAccEC2SecurityGroup_ruleGathering(t *testing.T) { var group ec2.SecurityGroup - sgName := fmt.Sprintf("tf-acc-security-group-%s", sdkacctest.RandString(7)) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -961,10 +961,10 @@ func TestAccEC2SecurityGroup_ruleGathering(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ruleGathering(sgName), + Config: testAccSecurityGroupRuleGatheringConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "name", sgName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "egress.#", "3"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ "cidr_blocks.#": "0", @@ -4082,30 +4082,30 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupConfig_ruleGathering(sgName string) string { +func testAccSecurityGroupRuleGatheringConfig(rName string) string { return fmt.Sprintf(` -variable "name" { - default = "%s" -} - data "aws_region" "current" {} resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = var.name + Name = %[1]q } } -resource "aws_route_table" "default" { +resource "aws_route_table" "test" { vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_vpc_endpoint" "test" { vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" - route_table_ids = [aws_route_table.default.id] + route_table_ids = [aws_route_table.test.id] policy = < Date: Thu, 31 Mar 2022 15:08:17 -0400 Subject: [PATCH 023/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_forceRevokeRulesTrue' and 'TestAccEC2SecurityGroup_forceRevokeRulesFalse'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_forceRevokeRules PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_forceRevokeRules' -timeout 180m === RUN TestAccEC2SecurityGroup_forceRevokeRulesTrue === PAUSE TestAccEC2SecurityGroup_forceRevokeRulesTrue === RUN TestAccEC2SecurityGroup_forceRevokeRulesFalse === PAUSE TestAccEC2SecurityGroup_forceRevokeRulesFalse === CONT TestAccEC2SecurityGroup_forceRevokeRulesTrue === CONT TestAccEC2SecurityGroup_forceRevokeRulesFalse --- PASS: TestAccEC2SecurityGroup_forceRevokeRulesFalse (955.43s) --- PASS: TestAccEC2SecurityGroup_forceRevokeRulesTrue (986.31s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 990.273s --- internal/service/ec2/security_group_test.go | 105 ++++++++++---------- 1 file changed, 54 insertions(+), 51 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 21a88bb25d0e..1d1522c85e62 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1057,6 +1057,7 @@ func TestAccEC2SecurityGroup_ruleGathering(t *testing.T) { func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { var primary ec2.SecurityGroup var secondary ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.primary" resourceName2 := "aws_security_group.secondary" @@ -1075,7 +1076,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { // create the configuration with 2 security groups, then create a // dependency cycle such that they cannot be deleted { - Config: testAccSecurityGroupConfig_revoke_base, + Config: testAccSecurityGroupRevokeBaseConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1092,14 +1093,13 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { // groups removed. Terraform tries to destroy them but cannot. Expect a // DependencyViolation error { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), ExpectError: regexp.MustCompile("DependencyViolation"), }, // Restore the config (a no-op plan) but also remove the dependencies // between the groups with testRemoveCycle { - Config: testAccSecurityGroupConfig_revoke_base, - // ExpectError: regexp.MustCompile("DependencyViolation"), + Config: testAccSecurityGroupRevokeBaseConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1108,7 +1108,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { }, // Again try to apply the config with the sgs removed; it should work { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), }, //// // now test with revoke_rules_on_delete @@ -1118,7 +1118,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { // configuration, each Security Group has `revoke_rules_on_delete` // specified, and should delete with no issue { - Config: testAccSecurityGroupConfig_revoke_true, + Config: testAccSecurityGroupRevokeTrueConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1128,7 +1128,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { // Again try to apply the config with the sgs removed; it should work, // because we've told the SGs to forcefully revoke their rules first { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), }, }, }) @@ -1137,6 +1137,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { var primary ec2.SecurityGroup var secondary ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.primary" resourceName2 := "aws_security_group.secondary" @@ -1157,7 +1158,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { // Groups are configured to explicitly not revoke rules on delete, // `revoke_rules_on_delete = false` { - Config: testAccSecurityGroupConfig_revoke_false, + Config: testAccSecurityGroupRevokeFalseConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1175,13 +1176,13 @@ func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { // Terraform tries to destroy them but cannot. Expect a // DependencyViolation error { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), ExpectError: regexp.MustCompile("DependencyViolation"), }, // Restore the config (a no-op plan) but also remove the dependencies // between the groups with testRemoveCycle { - Config: testAccSecurityGroupConfig_revoke_false, + Config: testAccSecurityGroupRevokeFalseConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1190,7 +1191,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { }, // Again try to apply the config with the sgs removed; it should work { - Config: testAccSecurityGroupConfig_revoke_base_removed, + Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), }, }, }) @@ -3020,113 +3021,115 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupConfig_revoke_base_removed = ` -resource "aws_vpc" "sg-race-revoke" { +func testAccSecurityGroupRevokeBaseRemovedConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-revoke" + Name = %[1]q } } -` +`, rName) +} -const testAccSecurityGroupConfig_revoke_base = ` -resource "aws_vpc" "sg-race-revoke" { +func testAccSecurityGroupRevokeBaseConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-revoke" + Name = %[1]q } } resource "aws_security_group" "primary" { - name = "tf-acc-sg-race-revoke-primary" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.sg-race-revoke.id + name = "%[1]s-primary" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-revoke-test-primary" + Name = %[1]q } } resource "aws_security_group" "secondary" { - name = "tf-acc-sg-race-revoke-secondary" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.sg-race-revoke.id + name = "%[1]s-secondary" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-revoke-test-secondary" + Name = %[1]q } } -` +`, rName) +} -const testAccSecurityGroupConfig_revoke_false = ` -resource "aws_vpc" "sg-race-revoke" { +func testAccSecurityGroupRevokeFalseConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-revoke" + Name = %[1]q } } resource "aws_security_group" "primary" { - name = "tf-acc-sg-race-revoke-primary" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.sg-race-revoke.id + name = "%[1]s-primary" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-revoke-test-primary" + Name = %[1]q } revoke_rules_on_delete = false } resource "aws_security_group" "secondary" { - name = "tf-acc-sg-race-revoke-secondary" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.sg-race-revoke.id + name = "%[1]s-secondary" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-revoke-test-secondary" + Name = %[1]q } revoke_rules_on_delete = false } -` +`, rName) +} -const testAccSecurityGroupConfig_revoke_true = ` -resource "aws_vpc" "sg-race-revoke" { +func testAccSecurityGroupRevokeTrueConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-revoke" + Name = %[1]q } } resource "aws_security_group" "primary" { - name = "tf-acc-sg-race-revoke-primary" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.sg-race-revoke.id + name = "%[1]s-primary" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-revoke-test-primary" + Name = %[1]q } revoke_rules_on_delete = true } resource "aws_security_group" "secondary" { - name = "tf-acc-sg-race-revoke-secondary" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.sg-race-revoke.id + name = "%[1]s-secondary" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-revoke-test-secondary" + Name = %[1]q } revoke_rules_on_delete = true } -` +`, rName) +} const testAccSecurityGroupChangeConfig = ` resource "aws_vpc" "foo" { From e2282f062603304b15fd4822170af3c6072efdc6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 31 Mar 2022 15:42:46 -0400 Subject: [PATCH 024/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_change' and 'TestAccEC2SecurityGroup_ipv6'. Acceptance test output: % make testacc TESTARGS='-run=TestAccEC2SecurityGroup_change\|TestAccEC2SecurityGroup_ipv6' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccEC2SecurityGroup_change\|TestAccEC2SecurityGroup_ipv6 -timeout 180m === RUN TestAccEC2SecurityGroup_ipv6 === PAUSE TestAccEC2SecurityGroup_ipv6 === RUN TestAccEC2SecurityGroup_change === PAUSE TestAccEC2SecurityGroup_change === CONT TestAccEC2SecurityGroup_ipv6 === CONT TestAccEC2SecurityGroup_change --- PASS: TestAccEC2SecurityGroup_ipv6 (21.42s) --- PASS: TestAccEC2SecurityGroup_change (35.39s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 39.100s --- internal/service/ec2/security_group_test.go | 166 +++++++++----------- 1 file changed, 75 insertions(+), 91 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 1d1522c85e62..715865807d05 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1199,6 +1199,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { func TestAccEC2SecurityGroup_ipv6(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -1208,11 +1209,10 @@ func TestAccEC2SecurityGroup_ipv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIPv6Config, + Config: testAccSecurityGroupIPv6Config(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ "cidr_blocks.#": "0", @@ -1443,6 +1443,7 @@ func TestAccEC2SecurityGroup_multiIngress(t *testing.T) { func TestAccEC2SecurityGroup_change(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -1452,7 +1453,7 @@ func TestAccEC2SecurityGroup_change(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig, + Config: testAccSecurityGroupConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1464,10 +1465,45 @@ func TestAccEC2SecurityGroup_change(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupChangeConfig, + Config: testAccSecurityGroupChangeConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupAttributesChanged(&group), + resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "9000", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "2", + "cidr_blocks.0": "0.0.0.0/0", + "cidr_blocks.1": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, }, @@ -2630,69 +2666,6 @@ func testAccCheckSecurityGroupIngressPrefixListAttributes(group *ec2.SecurityGro } } -func testAccCheckSecurityGroupAttributesChanged(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - p := []*ec2.IpPermission{ - { - FromPort: aws.Int64(80), - ToPort: aws.Int64(9000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - }, - { - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{ - { - CidrIp: aws.String("0.0.0.0/0"), - }, - { - CidrIp: aws.String("10.0.0.0/8"), - }, - }, - }, - } - - if *group.GroupName != "terraform_acceptance_test_example" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - - // Compare our ingress - if len(group.IpPermissions) != 2 { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions, - p) - } - - if *group.IpPermissions[0].ToPort == 8000 { - group.IpPermissions[1], group.IpPermissions[0] = - group.IpPermissions[0], group.IpPermissions[1] - } - - if len(group.IpPermissions[1].IpRanges) > 1 { - if *group.IpPermissions[1].IpRanges[0].CidrIp != "0.0.0.0/0" { - group.IpPermissions[1].IpRanges[0], group.IpPermissions[1].IpRanges[1] = - group.IpPermissions[1].IpRanges[1], group.IpPermissions[1].IpRanges[0] - } - } - - if !reflect.DeepEqual(group.IpPermissions, p) { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions, - p) - } - - return nil - } -} - func testAccCheckSecurityGroupExistsWithoutDefault(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -2964,19 +2937,19 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupIPv6Config = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupIPv6Config(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-ipv6" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "6" @@ -2993,24 +2966,25 @@ resource "aws_security_group" "test" { } tags = { - Name = "tf-acc-test" + Name = %[1]q } } -` +`, rName) +} -const testAccSecurityGroupConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "6" @@ -3018,8 +2992,13 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` func testAccSecurityGroupRevokeBaseRemovedConfig(rName string) string { return fmt.Sprintf(` @@ -3131,19 +3110,19 @@ resource "aws_security_group" "secondary" { `, rName) } -const testAccSecurityGroupChangeConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupChangeConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-change" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "tcp" @@ -3165,8 +3144,13 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` func testAccSecurityGroupRuleDescriptionConfig(egressDescription, ingressDescription string) string { return fmt.Sprintf(` From 4f922baad20b73096dfc9dba14ce7519eb226ca0 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 31 Mar 2022 15:56:03 -0400 Subject: [PATCH 025/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_self'. Acceptance test output: % make testacc TESTARGS='-run=TestAccEC2SecurityGroup_self' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccEC2SecurityGroup_self -timeout 180m === RUN TestAccEC2SecurityGroup_self === PAUSE TestAccEC2SecurityGroup_self === CONT TestAccEC2SecurityGroup_self --- PASS: TestAccEC2SecurityGroup_self (21.21s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 24.862s --- internal/service/ec2/security_group_test.go | 34 +++++++++------------ 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 715865807d05..a4efe46e3e40 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1251,20 +1251,17 @@ func TestAccEC2SecurityGroup_ipv6(t *testing.T) { func TestAccEC2SecurityGroup_self(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" checkSelf := func(s *terraform.State) (err error) { - defer func() { - if e := recover(); e != nil { - err = fmt.Errorf("bad: %#v", group) - } - }() - - if *group.IpPermissions[0].UserIdGroupPairs[0].GroupId != *group.GroupId { - return fmt.Errorf("bad: %#v", group) + if len(group.IpPermissions) > 0 && + len(group.IpPermissions[0].UserIdGroupPairs) > 0 && + aws.StringValue(group.IpPermissions[0].UserIdGroupPairs[0].GroupId) == aws.StringValue(group.GroupId) { + return nil } - return nil + return fmt.Errorf("Security Group does not contain \"self\" rule: %#v", group) } resource.ParallelTest(t, resource.TestCase{ @@ -1274,11 +1271,9 @@ func TestAccEC2SecurityGroup_self(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupSelfConfig, + Config: testAccSecurityGroupSelfConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ "protocol": "tcp", "from_port": "80", @@ -3190,19 +3185,19 @@ resource "aws_security_group" "test" { `, ingressDescription, egressDescription) } -const testAccSecurityGroupSelfConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupSelfConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-self" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "tcp" @@ -3218,7 +3213,8 @@ resource "aws_security_group" "test" { cidr_blocks = ["10.0.0.0/8"] } } -` +`, rName) +} const testAccSecurityGroupVPCConfig = ` resource "aws_vpc" "foo" { From 2ea0a227f37caeb7bbffc2da157f0d5e337925f6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 31 Mar 2022 17:35:58 -0400 Subject: [PATCH 026/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_vpc*'. Acceptance test output: % make testacc TESTARGS='-run=TestAccEC2SecurityGroup_vpc' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccEC2SecurityGroup_vpc -timeout 180m === RUN TestAccEC2SecurityGroup_vpc === PAUSE TestAccEC2SecurityGroup_vpc === RUN TestAccEC2SecurityGroup_vpcNegOneIngress === PAUSE TestAccEC2SecurityGroup_vpcNegOneIngress === RUN TestAccEC2SecurityGroup_vpcProtoNumIngress === PAUSE TestAccEC2SecurityGroup_vpcProtoNumIngress === CONT TestAccEC2SecurityGroup_vpc === CONT TestAccEC2SecurityGroup_vpcNegOneIngress === CONT TestAccEC2SecurityGroup_vpcProtoNumIngress --- PASS: TestAccEC2SecurityGroup_vpcProtoNumIngress (24.76s) --- PASS: TestAccEC2SecurityGroup_vpc (24.98s) --- PASS: TestAccEC2SecurityGroup_vpcNegOneIngress (25.09s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.597s --- internal/service/ec2/security_group_test.go | 129 ++++++++------------ 1 file changed, 54 insertions(+), 75 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index a4efe46e3e40..f01de9327a64 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1274,6 +1274,7 @@ func TestAccEC2SecurityGroup_self(t *testing.T) { Config: testAccSecurityGroupSelfConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ "protocol": "tcp", "from_port": "80", @@ -1295,6 +1296,7 @@ func TestAccEC2SecurityGroup_self(t *testing.T) { func TestAccEC2SecurityGroup_vpc(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -1304,12 +1306,10 @@ func TestAccEC2SecurityGroup_vpc(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCConfig, + Config: testAccSecurityGroupVPCConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupAttributes(&group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ "protocol": "tcp", "from_port": "80", @@ -1317,6 +1317,7 @@ func TestAccEC2SecurityGroup_vpc(t *testing.T) { "cidr_blocks.#": "1", "cidr_blocks.0": "10.0.0.0/8", }), + resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ "protocol": "tcp", "from_port": "80", @@ -1324,7 +1325,7 @@ func TestAccEC2SecurityGroup_vpc(t *testing.T) { "cidr_blocks.#": "1", "cidr_blocks.0": "10.0.0.0/8", }), - testAccSecurityGroupCheckVPCIDExists(&group), + resource.TestCheckResourceAttrSet(resourceName, "vpc_id"), ), }, { @@ -1339,6 +1340,7 @@ func TestAccEC2SecurityGroup_vpc(t *testing.T) { func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -1348,12 +1350,10 @@ func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCNegOneIngressConfig, + Config: testAccSecurityGroupVPCNegOneIngressConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupAttributesNegOneProtocol(&group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ "protocol": "-1", "from_port": "0", @@ -1361,7 +1361,7 @@ func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { "cidr_blocks.#": "1", "cidr_blocks.0": "10.0.0.0/8", }), - testAccSecurityGroupCheckVPCIDExists(&group), + resource.TestCheckResourceAttrSet(resourceName, "vpc_id"), ), }, { @@ -1376,6 +1376,7 @@ func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -1385,11 +1386,10 @@ func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCProtoNumIngressConfig, + Config: testAccSecurityGroupVPCProtoNumIngressConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ "protocol": "50", "from_port": "0", @@ -1397,7 +1397,7 @@ func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { "cidr_blocks.#": "1", "cidr_blocks.0": "10.0.0.0/8", }), - testAccSecurityGroupCheckVPCIDExists(&group), + resource.TestCheckResourceAttrSet(resourceName, "vpc_id"), ), }, { @@ -2284,15 +2284,6 @@ func TestAccEC2SecurityGroup_rulesDropOnError(t *testing.T) { }) } -func testAccSecurityGroupCheckVPCIDExists(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(*terraform.State) error { - if aws.StringValue(group.VpcId) == "" { - return fmt.Errorf("should have vpc ID") - } - return nil - } -} - // cycleIpPermForGroup returns an IpPermission struct with a configured // UserIdGroupPair for the groupid given. Used in // TestAccAWSSecurityGroup_forceRevokeRules_should_fail to create a cyclic rule @@ -2521,37 +2512,6 @@ func testAccCheckSecurityGroupAttributes(group *ec2.SecurityGroup) resource.Test } } -func testAccCheckSecurityGroupAttributesNegOneProtocol(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - p := &ec2.IpPermission{ - IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - } - - if *group.GroupName != "terraform_acceptance_test_example" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - - // Compare our ingress - if !reflect.DeepEqual(group.IpPermissions[0], p) { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions[0], - p) - } - - return nil - } -} - // testAccSecurityGroupRulesPerGroupLimitFromEnv returns security group rules per group limit // Currently this information is not available from any EC2 or Trusted Advisor API // Prefers the EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT environment variable or defaults to 50 @@ -3212,23 +3172,27 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } } `, rName) } -const testAccSecurityGroupVPCConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupVPCConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-vpc" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "tcp" @@ -3243,22 +3207,27 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` -const testAccSecurityGroupVPCNegOneIngressConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupVPCNegOneIngressConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-vpc-neg-one-ingress" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "-1" @@ -3266,22 +3235,27 @@ resource "aws_security_group" "test" { to_port = 0 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` -const testAccSecurityGroupVPCProtoNumIngressConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupVPCProtoNumIngressConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-vpc-proto-num-ingress" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "50" @@ -3289,8 +3263,13 @@ resource "aws_security_group" "test" { to_port = 0 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` const testAccSecurityGroupMultiIngressConfig = ` resource "aws_vpc" "foo" { From abb4892cc015bf3c1d797ba9d1648f388b8fdd21 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 16:29:39 -0400 Subject: [PATCH 027/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_multiIngress'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_multiIngress PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_multiIngress' -timeout 180m === RUN TestAccEC2SecurityGroup_multiIngress === PAUSE TestAccEC2SecurityGroup_multiIngress === CONT TestAccEC2SecurityGroup_multiIngress --- PASS: TestAccEC2SecurityGroup_multiIngress (26.84s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 30.623s --- internal/service/ec2/security_group_test.go | 173 ++++++++++---------- 1 file changed, 91 insertions(+), 82 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index f01de9327a64..97e4f1506856 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1197,6 +1197,75 @@ func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { }) } +func TestAccEC2SecurityGroup_change(t *testing.T) { + var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccSecurityGroupConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + { + Config: testAccSecurityGroupChangeConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "9000", + }), + resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "2", + "cidr_blocks.0": "0.0.0.0/0", + "cidr_blocks.1": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), + ), + }, + }, + }) +} + func TestAccEC2SecurityGroup_ipv6(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1412,34 +1481,8 @@ func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { func TestAccEC2SecurityGroup_multiIngress(t *testing.T) { var group ec2.SecurityGroup - resourceName := "aws_security_group.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccSecurityGroupMultiIngressConfig, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, - }, - }, - }) -} - -func TestAccEC2SecurityGroup_change(t *testing.T) { - var group ec2.SecurityGroup + resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1448,7 +1491,7 @@ func TestAccEC2SecurityGroup_change(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig(rName), + Config: testAccSecurityGroupMultiIngressConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1459,48 +1502,6 @@ func TestAccEC2SecurityGroup_change(t *testing.T) { ImportStateVerify: true, ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, - { - Config: testAccSecurityGroupChangeConfig(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ - "cidr_blocks.#": "1", - "cidr_blocks.0": "10.0.0.0/8", - "description": "", - "from_port": "80", - "ipv6_cidr_blocks.#": "0", - "protocol": "tcp", - "security_groups.#": "0", - "self": "false", - "to_port": "8000", - }), - resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ - "cidr_blocks.#": "1", - "cidr_blocks.0": "10.0.0.0/8", - "description": "", - "from_port": "80", - "ipv6_cidr_blocks.#": "0", - "protocol": "tcp", - "security_groups.#": "0", - "self": "false", - "to_port": "9000", - }), - resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ - "cidr_blocks.#": "2", - "cidr_blocks.0": "0.0.0.0/0", - "cidr_blocks.1": "10.0.0.0/8", - "description": "", - "from_port": "80", - "ipv6_cidr_blocks.#": "0", - "protocol": "tcp", - "security_groups.#": "0", - "self": "false", - "to_port": "8000", - }), - ), - }, }, }) } @@ -3271,19 +3272,19 @@ resource "aws_security_group" "test" { `, rName) } -const testAccSecurityGroupMultiIngressConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupMultiIngressConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-multi-ingress" + Name = %[1]q } } -resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example_1" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test1" { + name = "%[1]s-1" + vpc_id = aws_vpc.test.id ingress { protocol = "tcp" @@ -3298,12 +3299,15 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test2" { - name = "terraform_acceptance_test_example_2" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = "%[1]s-2" + vpc_id = aws_vpc.test.id ingress { protocol = "tcp" @@ -3323,7 +3327,7 @@ resource "aws_security_group" "test2" { protocol = "tcp" from_port = 80 to_port = 8000 - security_groups = [aws_security_group.test.id] + security_groups = [aws_security_group.test1.id] } egress { @@ -3332,8 +3336,13 @@ resource "aws_security_group" "test2" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` const testAccSecurityGroupDefaultEgressConfig = ` resource "aws_vpc" "tf_sg_egress_test" { From c5203488ff65d2e8266421bd9c5c409f253b6c02 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 16:36:15 -0400 Subject: [PATCH 028/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_ruleDescription'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_ruleDescription PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_ruleDescription' -timeout 180m === RUN TestAccEC2SecurityGroup_ruleDescription === PAUSE TestAccEC2SecurityGroup_ruleDescription === CONT TestAccEC2SecurityGroup_ruleDescription --- PASS: TestAccEC2SecurityGroup_ruleDescription (50.01s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 53.756s --- internal/service/ec2/security_group_test.go | 43 +++++++++++---------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 97e4f1506856..ed01f40869f3 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1509,6 +1509,7 @@ func TestAccEC2SecurityGroup_multiIngress(t *testing.T) { func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1517,7 +1518,7 @@ func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleDescriptionConfig("Egress description", "Ingress description"), + Config: testAccSecurityGroupRuleDescriptionConfig(rName, "Egress description", "Ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1555,7 +1556,7 @@ func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { }, // Change just the rule descriptions. { - Config: testAccSecurityGroupRuleDescriptionConfig("New egress description", "New ingress description"), + Config: testAccSecurityGroupRuleDescriptionConfig(rName, "New egress description", "New ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1587,7 +1588,7 @@ func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { }, // Remove just the rule descriptions. { - Config: testAccSecurityGroupEmptyRuleDescriptionConfig, + Config: testAccSecurityGroupEmptyRuleDescriptionConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -2857,19 +2858,19 @@ resource "aws_security_group" "test" { `, cidrBlocks.String()) } -const testAccSecurityGroupEmptyRuleDescriptionConfig = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupEmptyRuleDescriptionConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-empty-rule-description" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_desc_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "6" @@ -2888,10 +2889,11 @@ resource "aws_security_group" "test" { } tags = { - Name = "tf-acc-test" + Name = %[1]q } } -` +`, rName) +} func testAccSecurityGroupIPv6Config(rName string) string { return fmt.Sprintf(` @@ -3108,27 +3110,26 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupRuleDescriptionConfig(egressDescription, ingressDescription string) string { +func testAccSecurityGroupRuleDescriptionConfig(rName, egressDescription, ingressDescription string) string { return fmt.Sprintf(` -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-description" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id ingress { protocol = "6" from_port = 80 to_port = 8000 cidr_blocks = ["10.0.0.0/8"] - description = "%s" + description = %[2]q } egress { @@ -3136,14 +3137,14 @@ resource "aws_security_group" "test" { from_port = 80 to_port = 8000 cidr_blocks = ["10.0.0.0/8"] - description = "%s" + description = %[3]q } tags = { - Name = "tf-acc-test" + Name = %[1]q } } -`, ingressDescription, egressDescription) +`, rName, ingressDescription, egressDescription) } func testAccSecurityGroupSelfConfig(rName string) string { From 7c97dcf9cbd2d43b00ebac1505ed10e1f97edf53 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 16:42:03 -0400 Subject: [PATCH 029/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_defaultEgressVPC'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_defaultEgressVPC PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_defaultEgressVPC' -timeout 180m === RUN TestAccEC2SecurityGroup_defaultEgressVPC === PAUSE TestAccEC2SecurityGroup_defaultEgressVPC === CONT TestAccEC2SecurityGroup_defaultEgressVPC --- PASS: TestAccEC2SecurityGroup_defaultEgressVPC (20.76s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 24.835s --- internal/service/ec2/security_group_test.go | 57 +++++++-------------- 1 file changed, 18 insertions(+), 39 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index ed01f40869f3..2e22728cf38e 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1620,9 +1620,10 @@ func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { } func TestAccEC2SecurityGroup_defaultEgressVPC(t *testing.T) { + var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - // VPC resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -1630,9 +1631,11 @@ func TestAccEC2SecurityGroup_defaultEgressVPC(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupDefaultEgressConfig, + Config: testAccSecurityGroupDefaultEgressConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExistsWithoutDefault(resourceName), + testAccCheckSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), ), }, { @@ -2623,35 +2626,6 @@ func testAccCheckSecurityGroupIngressPrefixListAttributes(group *ec2.SecurityGro } } -func testAccCheckSecurityGroupExistsWithoutDefault(n string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group is set") - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - group, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - if tfresource.NotFound(err) { - return fmt.Errorf("Security Group (%s) not found: %w", rs.Primary.ID, err) - } - if err != nil { - return err - } - - if len(group.IpPermissionsEgress) != 1 { - return fmt.Errorf("Security Group should have only 1 egress rule, got %d", len(group.IpPermissionsEgress)) - } - - return nil - } -} - func testAccCheckSecurityGroupRuleCount(group *ec2.SecurityGroup, expectedIngressCount, expectedEgressCount int) resource.TestCheckFunc { return func(s *terraform.State) error { id := aws.StringValue(group.GroupId) @@ -3345,19 +3319,19 @@ resource "aws_security_group" "test2" { `, rName) } -const testAccSecurityGroupDefaultEgressConfig = ` -resource "aws_vpc" "tf_sg_egress_test" { +func testAccSecurityGroupDefaultEgressConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-default-egress" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example_1" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.tf_sg_egress_test.id + name = %[1]q + vpc_id = aws_vpc.test.id egress { protocol = "tcp" @@ -3365,8 +3339,13 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` func testAccSecurityGroupConfig_drift() string { return fmt.Sprintf(` From 9bad5b5342c7d5e2d3020187eb2cdbc43a0a2827 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 16:52:25 -0400 Subject: [PATCH 030/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_drift*'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_drift PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_drift' -timeout 180m === RUN TestAccEC2SecurityGroup_drift === PAUSE TestAccEC2SecurityGroup_drift === RUN TestAccEC2SecurityGroup_driftComplex === PAUSE TestAccEC2SecurityGroup_driftComplex === CONT TestAccEC2SecurityGroup_drift === CONT TestAccEC2SecurityGroup_driftComplex --- PASS: TestAccEC2SecurityGroup_drift (17.87s) --- PASS: TestAccEC2SecurityGroup_driftComplex (25.76s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 29.534s --- internal/service/ec2/security_group_test.go | 41 ++++++++++----------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 2e22728cf38e..12676fdf7d8d 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1650,8 +1650,9 @@ func TestAccEC2SecurityGroup_defaultEgressVPC(t *testing.T) { // Testing drift detection with groups containing the same port and types func TestAccEC2SecurityGroup_drift(t *testing.T) { - resourceName := "aws_security_group.test" var group ec2.SecurityGroup + resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1660,10 +1661,9 @@ func TestAccEC2SecurityGroup_drift(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_drift(), + Config: testAccSecurityGroupDriftConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ @@ -1705,7 +1705,8 @@ func TestAccEC2SecurityGroup_drift(t *testing.T) { func TestAccEC2SecurityGroup_driftComplex(t *testing.T) { var group ec2.SecurityGroup - resourceName := "aws_security_group.test" + resourceName := "aws_security_group.test1" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1714,10 +1715,9 @@ func TestAccEC2SecurityGroup_driftComplex(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_drift_complex(), + Config: testAccSecurityGroupDriftComplexConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckResourceAttr(resourceName, "egress.#", "3"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ "cidr_blocks.#": "1", @@ -3347,11 +3347,10 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupConfig_drift() string { +func testAccSecurityGroupDriftConfig(rName string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { - name = "tf_acc_%d" - description = "Used in the terraform acceptance tests" + name = %[1]q ingress { protocol = "tcp" @@ -3368,32 +3367,30 @@ resource "aws_security_group" "test" { } tags = { - Name = "tf-acc-test" + Name = %[1]q } } -`, sdkacctest.RandInt()) +`, rName) } -func testAccSecurityGroupConfig_drift_complex() string { +func testAccSecurityGroupDriftComplexConfig(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-drift-complex" + Name = %[1]q } } resource "aws_security_group" "test2" { - name = "tf_acc_%d" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = "%[1]s-2" + vpc_id = aws_vpc.test.id } -resource "aws_security_group" "test" { - name = "tf_acc_%d" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test1" { + name = "%[1]s-1" + vpc_id = aws_vpc.test.id ingress { protocol = "tcp" @@ -3441,7 +3438,7 @@ resource "aws_security_group" "test" { Name = "tf-acc-test" } } -`, sdkacctest.RandInt(), sdkacctest.RandInt()) +`, rName) } const testAccSecurityGroupInvalidIngressCIDR = ` From 74d75b848f1f7ae5a851384845bf6a5a0d848b26 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 16:55:49 -0400 Subject: [PATCH 031/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_invalidCIDRBlock*'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_invalidCIDRBlock PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_invalidCIDRBlock' -timeout 180m === RUN TestAccEC2SecurityGroup_invalidCIDRBlock === PAUSE TestAccEC2SecurityGroup_invalidCIDRBlock === CONT TestAccEC2SecurityGroup_invalidCIDRBlock --- PASS: TestAccEC2SecurityGroup_invalidCIDRBlock (3.87s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 7.662s --- internal/service/ec2/security_group_test.go | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 12676fdf7d8d..74f7c0af74d6 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -3443,9 +3443,6 @@ resource "aws_security_group" "test1" { const testAccSecurityGroupInvalidIngressCIDR = ` resource "aws_security_group" "test" { - name = "testing-foo" - description = "foo-testing" - ingress { from_port = 0 to_port = 0 @@ -3457,9 +3454,6 @@ resource "aws_security_group" "test" { const testAccSecurityGroupInvalidEgressCIDR = ` resource "aws_security_group" "test" { - name = "testing-foo" - description = "foo-testing" - egress { from_port = 0 to_port = 0 @@ -3471,9 +3465,6 @@ resource "aws_security_group" "test" { const testAccSecurityGroupInvalidIPv6IngressCIDR = ` resource "aws_security_group" "test" { - name = "testing-foo" - description = "foo-testing" - ingress { from_port = 0 to_port = 0 @@ -3485,9 +3476,6 @@ resource "aws_security_group" "test" { const testAccSecurityGroupInvalidIPv6EgressCIDR = ` resource "aws_security_group" "test" { - name = "testing-foo" - description = "foo-testing" - egress { from_port = 0 to_port = 0 From bf1c1c39114e9f082eef526dbc546e5878b75215 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 17:05:13 -0400 Subject: [PATCH 032/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_cidrAndGroups*'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_cidrAndGroups PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_cidrAndGroups' -timeout 180m === RUN TestAccEC2SecurityGroup_cidrAndGroups === PAUSE TestAccEC2SecurityGroup_cidrAndGroups === CONT TestAccEC2SecurityGroup_cidrAndGroups --- PASS: TestAccEC2SecurityGroup_cidrAndGroups (25.71s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 29.457s --- internal/service/ec2/security_group_test.go | 60 +++++++++++---------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index 74f7c0af74d6..cc10bbcf0806 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1810,7 +1810,8 @@ func TestAccEC2SecurityGroup_invalidCIDRBlock(t *testing.T) { func TestAccEC2SecurityGroup_cidrAndGroups(t *testing.T) { var group ec2.SecurityGroup - resourceName := "aws_security_group.test" + resourceName := "aws_security_group.test1" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1819,10 +1820,9 @@ func TestAccEC2SecurityGroup_cidrAndGroups(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupCombindCIDRandGroups, + Config: testAccSecurityGroupCombinedCIDRAndGroupsConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - // testAccCheckSecurityGroupAttributes(&group), ), }, { @@ -3485,45 +3485,50 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupCombindCIDRandGroups = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupCombinedCIDRAndGroupsConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-combine-rand-groups" + Name = %[1]q } } -resource "aws_security_group" "two" { - name = "tf-test-1" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test2" { + name = "%[1]s-2" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-test-1" + Name = %[1]q } } -resource "aws_security_group" "one" { - name = "tf-test-2" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test3" { + name = "%[1]s-3" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-test-w" + Name = %[1]q } } -resource "aws_security_group" "three" { - name = "tf-test-3" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test4" { + name = "%[1]s-4" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-test-3" + Name = %[1]q } } -resource "aws_security_group" "test" { - name = "tf-mix-test" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test1" { + name = "%[1]s-1" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } ingress { from_port = 80 @@ -3532,17 +3537,14 @@ resource "aws_security_group" "test" { cidr_blocks = ["10.0.0.0/16", "10.1.0.0/16", "10.7.0.0/16"] security_groups = [ - aws_security_group.one.id, - aws_security_group.two.id, - aws_security_group.three.id, + aws_security_group.test2.id, + aws_security_group.test3.id, + aws_security_group.test4.id, ] } - - tags = { - Name = "tf-mix-test" - } } -` +`, rName) +} const testAccSecurityGroupConfig_ingressWithCIDRAndSGs = ` resource "aws_vpc" "foo" { From eb5baf5835beedf51b78c50bfbc8d75b9f93b36c Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 17:07:09 -0400 Subject: [PATCH 033/120] r/aws_security_group: Tweak acceptance test configuration names. --- internal/service/ec2/security_group_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index cc10bbcf0806..d21f1b3422f1 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1789,19 +1789,19 @@ func TestAccEC2SecurityGroup_invalidCIDRBlock(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupInvalidIngressCIDR, + Config: testAccSecurityGroupInvalidIngressCIDRConfig, ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupInvalidEgressCIDR, + Config: testAccSecurityGroupInvalidEgressCIDRConfig, ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupInvalidIPv6IngressCIDR, + Config: testAccSecurityGroupInvalidIPv6IngressCIDRConfig, ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, { - Config: testAccSecurityGroupInvalidIPv6EgressCIDR, + Config: testAccSecurityGroupInvalidIPv6EgressCIDRConfig, ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, }, @@ -3441,7 +3441,7 @@ resource "aws_security_group" "test1" { `, rName) } -const testAccSecurityGroupInvalidIngressCIDR = ` +const testAccSecurityGroupInvalidIngressCIDRConfig = ` resource "aws_security_group" "test" { ingress { from_port = 0 @@ -3452,7 +3452,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidEgressCIDR = ` +const testAccSecurityGroupInvalidEgressCIDRConfig = ` resource "aws_security_group" "test" { egress { from_port = 0 @@ -3463,7 +3463,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidIPv6IngressCIDR = ` +const testAccSecurityGroupInvalidIPv6IngressCIDRConfig = ` resource "aws_security_group" "test" { ingress { from_port = 0 @@ -3474,7 +3474,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidIPv6EgressCIDR = ` +const testAccSecurityGroupInvalidIPv6EgressCIDRConfig = ` resource "aws_security_group" "test" { egress { from_port = 0 From c71a07efa88aae64fb4615a1b3945e834b91f54e Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Apr 2022 17:14:43 -0400 Subject: [PATCH 034/120] r/aws_security_group: Tidy up 'TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC'. Acceptance test output: % make testacc TESTS=TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run='TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC' -timeout 180m === RUN TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC === PAUSE TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC === CONT TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC --- PASS: TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC (26.22s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 30.000s --- internal/service/ec2/security_group_test.go | 40 ++++++++++----------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index d21f1b3422f1..6f1b524e80b4 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -1837,7 +1837,8 @@ func TestAccEC2SecurityGroup_cidrAndGroups(t *testing.T) { func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { var group ec2.SecurityGroup - resourceName := "aws_security_group.test" + resourceName := "aws_security_group.test1" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1846,10 +1847,9 @@ func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs, + Config: testAccSecurityGroupIngressWithCIDRAndSGsConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupSGandCIDRAttributes(&group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ "cidr_blocks.#": "1", @@ -1889,7 +1889,7 @@ func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { var group ec2.SecurityGroup - resourceName := "aws_security_group.test" + resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ @@ -3546,29 +3546,32 @@ resource "aws_security_group" "test1" { `, rName) } -const testAccSecurityGroupConfig_ingressWithCIDRAndSGs = ` -resource "aws_vpc" "foo" { +func testAccSecurityGroupIngressWithCIDRAndSGsConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-ingress-w-cidr-and-sg" + Name = %[1]q } } resource "aws_security_group" "test2" { - name = "tf_other_acc_tests" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = "%[1]s-2" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test1" { + name = "%[1]s-1" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } ingress { protocol = "tcp" @@ -3594,12 +3597,9 @@ resource "aws_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } - - tags = { - Name = "tf-acc-test" - } } -` +`, rName) +} func testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName string) string { return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` From d4843842c5ba3dec7ab0bb57d885fc638ca0fb4b Mon Sep 17 00:00:00 2001 From: Ian Blenke Date: Thu, 21 Apr 2022 10:56:16 -0400 Subject: [PATCH 035/120] Change 5 minute timeout to 60 minute timeout when creating security_group_rules --- internal/service/ec2/security_group_rule.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/ec2/security_group_rule.go b/internal/service/ec2/security_group_rule.go index ec5f80f79f07..bd77b87e1ea2 100644 --- a/internal/service/ec2/security_group_rule.go +++ b/internal/service/ec2/security_group_rule.go @@ -227,7 +227,7 @@ information and instructions for recovery. Error: %w`, sg_id, autherr) id := IPPermissionIDHash(sg_id, ruleType, perm) log.Printf("[DEBUG] Computed group rule ID %s", id) - err = resource.Retry(5*time.Minute, func() *resource.RetryError { + err = resource.Retry(60*time.Minute, func() *resource.RetryError { sg, err := FindSecurityGroupByID(conn, sg_id) if err != nil { From 5d5e1eafe9b8305984516c27f5cbe68a906bf6f5 Mon Sep 17 00:00:00 2001 From: Andreas Kohn Date: Mon, 27 Jun 2022 19:40:11 +0200 Subject: [PATCH 036/120] Match IPv6 CIDRs as lower-case AWS reports IPv6 CIDRs in security groups using lower-case hexadecimal (matching the SHOULD recommendation in RFC5952), but it is possible that the rule we're trying to match uses upper-case hexadecimal, leading to a non-match. Fix this problem by lower-casing the CIDR in the permission before matching. See https://www.rfc-editor.org/rfc/rfc5952#section-4.3 --- .../service/ec2/vpc_security_group_rule.go | 8 ++- .../vpc_security_group_rules_matching_test.go | 60 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 1d114b450423..25b3c8d3a628 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -452,11 +452,15 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * remaining = len(p.Ipv6Ranges) for _, ipv6 := range p.Ipv6Ranges { + if ipv6.CidrIpv6 == nil { + continue + } + expectedCidrIpv6 := strings.ToLower(aws.StringValue(ipv6.CidrIpv6)) for _, ipv6ip := range r.Ipv6Ranges { - if ipv6.CidrIpv6 == nil || ipv6ip.CidrIpv6 == nil { + if ipv6ip.CidrIpv6 == nil { continue } - if aws.StringValue(ipv6.CidrIpv6) == aws.StringValue(ipv6ip.CidrIpv6) { + if expectedCidrIpv6 == aws.StringValue(ipv6ip.CidrIpv6) { remaining-- } } diff --git a/internal/service/ec2/vpc_security_group_rules_matching_test.go b/internal/service/ec2/vpc_security_group_rules_matching_test.go index 058f08a19830..681b4111f8eb 100644 --- a/internal/service/ec2/vpc_security_group_rules_matching_test.go +++ b/internal/service/ec2/vpc_security_group_rules_matching_test.go @@ -585,6 +585,66 @@ func TestRulesMixedMatching(t *testing.T) { }, }, }, + // ipv6 + { + local: []interface{}{ + map[string]interface{}{ + "from_port": 80, + "to_port": 8000, + "protocol": "tcp", + "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, + "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), + }, + }, + remote: []map[string]interface{}{ + { + "from_port": int64(80), + "to_port": int64(8000), + "protocol": "tcp", + "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, + "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), + }, + }, + saves: []map[string]interface{}{ + { + "from_port": 80, + "to_port": 8000, + "protocol": "tcp", + "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, + "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), + }, + }, + }, + // ipv6: local/remote differ in capitalization + { + local: []interface{}{ + map[string]interface{}{ + "from_port": 80, + "to_port": 8000, + "protocol": "tcp", + "cidr_ipv6_blocks": []interface{}{"2001:0DB8:85A3:0000::/64"}, + "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), + }, + }, + remote: []map[string]interface{}{ + { + "from_port": int64(80), + "to_port": int64(8000), + "protocol": "tcp", + "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, + "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), + }, + }, + saves: []map[string]interface{}{ + { + "from_port": 80, + "to_port": 8000, + "protocol": "tcp", + "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, + "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), + }, + }, + }, } for i, c := range cases { saves := tfec2.MatchRules("ingress", c.local, c.remote) From 1402459b3765913d349423ca0030f12bee3739eb Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 09:41:18 -0400 Subject: [PATCH 037/120] 'TestAccEC2SecurityGroup_' -> 'TestAccVPCSecurityGroup_'. --- .../service/ec2/vpc_security_group_test.go | 82 +++++++++---------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 6f1b524e80b4..a484ca9de57f 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -496,7 +496,7 @@ func TestSecurityGroupIPPermGather(t *testing.T) { } } -func TestAccEC2SecurityGroup_basic(t *testing.T) { +func TestAccVPCSecurityGroup_basic(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -533,7 +533,7 @@ func TestAccEC2SecurityGroup_basic(t *testing.T) { }) } -func TestAccEC2SecurityGroup_basicEC2Classic(t *testing.T) { +func TestAccVPCSecurityGroup_basicEC2Classic(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -570,7 +570,7 @@ func TestAccEC2SecurityGroup_basicEC2Classic(t *testing.T) { }) } -func TestAccEC2SecurityGroup_disappears(t *testing.T) { +func TestAccVPCSecurityGroup_disappears(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -593,7 +593,7 @@ func TestAccEC2SecurityGroup_disappears(t *testing.T) { }) } -func TestAccEC2SecurityGroup_nameGenerated(t *testing.T) { +func TestAccVPCSecurityGroup_nameGenerated(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -623,7 +623,7 @@ func TestAccEC2SecurityGroup_nameGenerated(t *testing.T) { } // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 -func TestAccEC2SecurityGroup_nameTerraformPrefix(t *testing.T) { +func TestAccVPCSecurityGroup_nameTerraformPrefix(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix("terraform-test") @@ -652,7 +652,7 @@ func TestAccEC2SecurityGroup_nameTerraformPrefix(t *testing.T) { }) } -func TestAccEC2SecurityGroup_namePrefix(t *testing.T) { +func TestAccVPCSecurityGroup_namePrefix(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -682,7 +682,7 @@ func TestAccEC2SecurityGroup_namePrefix(t *testing.T) { } // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 -func TestAccEC2SecurityGroup_namePrefixTerraform(t *testing.T) { +func TestAccVPCSecurityGroup_namePrefixTerraform(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -711,7 +711,7 @@ func TestAccEC2SecurityGroup_namePrefixTerraform(t *testing.T) { }) } -func TestAccEC2SecurityGroup_tags(t *testing.T) { +func TestAccVPCSecurityGroup_tags(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -757,7 +757,7 @@ func TestAccEC2SecurityGroup_tags(t *testing.T) { }) } -func TestAccEC2SecurityGroup_allowAll(t *testing.T) { +func TestAccVPCSecurityGroup_allowAll(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -784,7 +784,7 @@ func TestAccEC2SecurityGroup_allowAll(t *testing.T) { }) } -func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { +func TestAccVPCSecurityGroup_sourceSecurityGroup(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -811,7 +811,7 @@ func TestAccEC2SecurityGroup_sourceSecurityGroup(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) { +func TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -838,7 +838,7 @@ func TestAccEC2SecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) }) } -func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { +func TestAccVPCSecurityGroup_ipRangesWithSameRules(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -865,7 +865,7 @@ func TestAccEC2SecurityGroup_ipRangesWithSameRules(t *testing.T) { }) } -func TestAccEC2SecurityGroup_egressMode(t *testing.T) { +func TestAccVPCSecurityGroup_egressMode(t *testing.T) { var securityGroup1, securityGroup2, securityGroup3 ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -907,7 +907,7 @@ func TestAccEC2SecurityGroup_egressMode(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ingressMode(t *testing.T) { +func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { var securityGroup1, securityGroup2, securityGroup3 ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -949,7 +949,7 @@ func TestAccEC2SecurityGroup_ingressMode(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ruleGathering(t *testing.T) { +func TestAccVPCSecurityGroup_ruleGathering(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1054,7 +1054,7 @@ func TestAccEC2SecurityGroup_ruleGathering(t *testing.T) { // 'aws_vpc' and 'aws_security_group' that cleans these up, however, the test is // written to allow Terraform to clean it up because we do go and revoke the // cyclic rules that were added. -func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { +func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { var primary ec2.SecurityGroup var secondary ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1134,7 +1134,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesTrue(t *testing.T) { }) } -func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { +func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { var primary ec2.SecurityGroup var secondary ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1197,7 +1197,7 @@ func TestAccEC2SecurityGroup_forceRevokeRulesFalse(t *testing.T) { }) } -func TestAccEC2SecurityGroup_change(t *testing.T) { +func TestAccVPCSecurityGroup_change(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1266,7 +1266,7 @@ func TestAccEC2SecurityGroup_change(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ipv6(t *testing.T) { +func TestAccVPCSecurityGroup_ipv6(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1318,7 +1318,7 @@ func TestAccEC2SecurityGroup_ipv6(t *testing.T) { }) } -func TestAccEC2SecurityGroup_self(t *testing.T) { +func TestAccVPCSecurityGroup_self(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1363,7 +1363,7 @@ func TestAccEC2SecurityGroup_self(t *testing.T) { }) } -func TestAccEC2SecurityGroup_vpc(t *testing.T) { +func TestAccVPCSecurityGroup_vpc(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1407,7 +1407,7 @@ func TestAccEC2SecurityGroup_vpc(t *testing.T) { }) } -func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { +func TestAccVPCSecurityGroup_vpcNegOneIngress(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1443,7 +1443,7 @@ func TestAccEC2SecurityGroup_vpcNegOneIngress(t *testing.T) { }) } -func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { +func TestAccVPCSecurityGroup_vpcProtoNumIngress(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1479,7 +1479,7 @@ func TestAccEC2SecurityGroup_vpcProtoNumIngress(t *testing.T) { }) } -func TestAccEC2SecurityGroup_multiIngress(t *testing.T) { +func TestAccVPCSecurityGroup_multiIngress(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1506,7 +1506,7 @@ func TestAccEC2SecurityGroup_multiIngress(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { +func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1619,7 +1619,7 @@ func TestAccEC2SecurityGroup_ruleDescription(t *testing.T) { }) } -func TestAccEC2SecurityGroup_defaultEgressVPC(t *testing.T) { +func TestAccVPCSecurityGroup_defaultEgressVPC(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1649,7 +1649,7 @@ func TestAccEC2SecurityGroup_defaultEgressVPC(t *testing.T) { } // Testing drift detection with groups containing the same port and types -func TestAccEC2SecurityGroup_drift(t *testing.T) { +func TestAccVPCSecurityGroup_drift(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1703,7 +1703,7 @@ func TestAccEC2SecurityGroup_drift(t *testing.T) { }) } -func TestAccEC2SecurityGroup_driftComplex(t *testing.T) { +func TestAccVPCSecurityGroup_driftComplex(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1781,7 +1781,7 @@ func TestAccEC2SecurityGroup_driftComplex(t *testing.T) { }) } -func TestAccEC2SecurityGroup_invalidCIDRBlock(t *testing.T) { +func TestAccVPCSecurityGroup_invalidCIDRBlock(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -1808,7 +1808,7 @@ func TestAccEC2SecurityGroup_invalidCIDRBlock(t *testing.T) { }) } -func TestAccEC2SecurityGroup_cidrAndGroups(t *testing.T) { +func TestAccVPCSecurityGroup_cidrAndGroups(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1835,7 +1835,7 @@ func TestAccEC2SecurityGroup_cidrAndGroups(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { +func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1887,7 +1887,7 @@ func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { +func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1928,7 +1928,7 @@ func TestAccEC2SecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { }) } -func TestAccEC2SecurityGroup_egressWithPrefixList(t *testing.T) { +func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -1956,7 +1956,7 @@ func TestAccEC2SecurityGroup_egressWithPrefixList(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ingressWithPrefixList(t *testing.T) { +func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -1984,7 +1984,7 @@ func TestAccEC2SecurityGroup_ingressWithPrefixList(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ipv4AndIPv6Egress(t *testing.T) { +func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" @@ -2036,7 +2036,7 @@ func TestAccEC2SecurityGroup_ipv4AndIPv6Egress(t *testing.T) { }) } -func TestAccEC2SecurityGroup_failWithDiffMismatch(t *testing.T) { +func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.nat" @@ -2059,7 +2059,7 @@ func TestAccEC2SecurityGroup_failWithDiffMismatch(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ruleLimitExceededAppend(t *testing.T) { +func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup @@ -2106,7 +2106,7 @@ func TestAccEC2SecurityGroup_ruleLimitExceededAppend(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { +func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup @@ -2167,7 +2167,7 @@ func TestAccEC2SecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ruleLimitExceededPrepend(t *testing.T) { +func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup @@ -2212,7 +2212,7 @@ func TestAccEC2SecurityGroup_ruleLimitExceededPrepend(t *testing.T) { }) } -func TestAccEC2SecurityGroup_ruleLimitExceededAllNew(t *testing.T) { +func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup @@ -2257,7 +2257,7 @@ func TestAccEC2SecurityGroup_ruleLimitExceededAllNew(t *testing.T) { }) } -func TestAccEC2SecurityGroup_rulesDropOnError(t *testing.T) { +func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" From 7e3d9bc8fe14d36fd17f257917bf68f21ebee5db Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 10:49:21 -0400 Subject: [PATCH 038/120] r/aws_security_group: Rename Config functions. --- .../service/ec2/vpc_security_group_test.go | 244 +++++++++--------- 1 file changed, 122 insertions(+), 122 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index a484ca9de57f..68ac9bf5e690 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -508,7 +508,7 @@ func TestAccVPCSecurityGroup_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameConfig(rName), + Config: testAccVPCSecurityGroupConfig_name(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`security-group/.+$`)), @@ -545,7 +545,7 @@ func TestAccVPCSecurityGroup_basicEC2Classic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupEC2ClassicDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupEC2ClassicConfig(rName), + Config: testAccVPCSecurityGroupConfig_ec2Classic(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupEC2ClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), @@ -560,7 +560,7 @@ func TestAccVPCSecurityGroup_basicEC2Classic(t *testing.T) { ), }, { - Config: testAccSecurityGroupEC2ClassicConfig(rName), + Config: testAccVPCSecurityGroupConfig_ec2Classic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -582,7 +582,7 @@ func TestAccVPCSecurityGroup_disappears(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameConfig(rName), + Config: testAccVPCSecurityGroupConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), acctest.CheckResourceDisappears(acctest.Provider, tfec2.ResourceSecurityGroup(), resourceName), @@ -605,7 +605,7 @@ func TestAccVPCSecurityGroup_nameGenerated(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameGeneratedConfig(rName), + Config: testAccVPCSecurityGroupConfig_nameGenerated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), create.TestCheckResourceAttrNameGenerated(resourceName, "name"), @@ -635,7 +635,7 @@ func TestAccVPCSecurityGroup_nameTerraformPrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNameConfig(rName), + Config: testAccVPCSecurityGroupConfig_name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -664,7 +664,7 @@ func TestAccVPCSecurityGroup_namePrefix(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNamePrefixConfig(rName, "tf-acc-test-prefix-"), + Config: testAccVPCSecurityGroupConfig_namePrefix(rName, "tf-acc-test-prefix-"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), @@ -694,7 +694,7 @@ func TestAccVPCSecurityGroup_namePrefixTerraform(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupNamePrefixConfig(rName, "terraform-test"), + Config: testAccVPCSecurityGroupConfig_namePrefix(rName, "terraform-test"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), create.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "terraform-test"), @@ -723,7 +723,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfigTags1(rName, "key1", "value1"), + Config: testAccVPCSecurityGroupConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -737,7 +737,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccVPCSecurityGroupConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -746,7 +746,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { ), }, { - Config: testAccSecurityGroupConfigTags1(rName, "key2", "value2"), + Config: testAccVPCSecurityGroupConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -769,7 +769,7 @@ func TestAccVPCSecurityGroup_allowAll(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupAllowAllConfig(rName), + Config: testAccVPCSecurityGroupConfig_allowAll(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -796,7 +796,7 @@ func TestAccVPCSecurityGroup_sourceSecurityGroup(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupSourceSecurityGroupConfig(rName), + Config: testAccVPCSecurityGroupConfig_sourceSecurityGroup(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -823,7 +823,7 @@ func TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIPRangeAndSecurityGroupWithSameRulesConfig(rName), + Config: testAccVPCSecurityGroupConfig_ipRangeAndSecurityGroupWithSameRules(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -850,7 +850,7 @@ func TestAccVPCSecurityGroup_ipRangesWithSameRules(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIPRangesWithSameRulesConfig(rName), + Config: testAccVPCSecurityGroupConfig_ipRangesWithSameRules(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -877,7 +877,7 @@ func TestAccVPCSecurityGroup_egressMode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupEgressModeBlocksConfig(rName), + Config: testAccVPCSecurityGroupConfig_egressModeBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup1), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -890,14 +890,14 @@ func TestAccVPCSecurityGroup_egressMode(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupEgressModeNoBlocksConfig(rName), + Config: testAccVPCSecurityGroupConfig_egressModeNoBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup2), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), ), }, { - Config: testAccSecurityGroupEgressModeZeroedConfig(rName), + Config: testAccVPCSecurityGroupConfig_egressModeZeroed(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup3), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -919,7 +919,7 @@ func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIngressModeBlocksConfig(rName), + Config: testAccVPCSecurityGroupConfig_ingressModeBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup1), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), @@ -932,14 +932,14 @@ func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupIngressModeNoBlocksConfig(rName), + Config: testAccVPCSecurityGroupConfig_ingressModeNoBlocks(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup2), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), ), }, { - Config: testAccSecurityGroupIngressModeZeroedConfig(rName), + Config: testAccVPCSecurityGroupConfig_ingressModeZeroed(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &securityGroup3), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), @@ -961,7 +961,7 @@ func TestAccVPCSecurityGroup_ruleGathering(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleGatheringConfig(rName), + Config: testAccVPCSecurityGroupConfig_ruleGathering(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -1076,7 +1076,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // create the configuration with 2 security groups, then create a // dependency cycle such that they cannot be deleted { - Config: testAccSecurityGroupRevokeBaseConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBase(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1093,13 +1093,13 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // groups removed. Terraform tries to destroy them but cannot. Expect a // DependencyViolation error { - Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved(rName), ExpectError: regexp.MustCompile("DependencyViolation"), }, // Restore the config (a no-op plan) but also remove the dependencies // between the groups with testRemoveCycle { - Config: testAccSecurityGroupRevokeBaseConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBase(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1108,7 +1108,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { }, // Again try to apply the config with the sgs removed; it should work { - Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved(rName), }, //// // now test with revoke_rules_on_delete @@ -1118,7 +1118,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // configuration, each Security Group has `revoke_rules_on_delete` // specified, and should delete with no issue { - Config: testAccSecurityGroupRevokeTrueConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeTrue(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1128,7 +1128,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { // Again try to apply the config with the sgs removed; it should work, // because we've told the SGs to forcefully revoke their rules first { - Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved(rName), }, }, }) @@ -1158,7 +1158,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { // Groups are configured to explicitly not revoke rules on delete, // `revoke_rules_on_delete = false` { - Config: testAccSecurityGroupRevokeFalseConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeFalse(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1176,13 +1176,13 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { // Terraform tries to destroy them but cannot. Expect a // DependencyViolation error { - Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved(rName), ExpectError: regexp.MustCompile("DependencyViolation"), }, // Restore the config (a no-op plan) but also remove the dependencies // between the groups with testRemoveCycle { - Config: testAccSecurityGroupRevokeFalseConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeFalse(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &primary), testAccCheckSecurityGroupExists(resourceName2, &secondary), @@ -1191,7 +1191,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { }, // Again try to apply the config with the sgs removed; it should work { - Config: testAccSecurityGroupRevokeBaseRemovedConfig(rName), + Config: testAccVPCSecurityGroupConfig_revokeBaseRemoved(rName), }, }, }) @@ -1209,7 +1209,7 @@ func TestAccVPCSecurityGroup_change(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig(rName), + Config: testAccVPCSecurityGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1221,7 +1221,7 @@ func TestAccVPCSecurityGroup_change(t *testing.T) { ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { - Config: testAccSecurityGroupChangeConfig(rName), + Config: testAccVPCSecurityGroupConfig_changed(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1278,7 +1278,7 @@ func TestAccVPCSecurityGroup_ipv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIPv6Config(rName), + Config: testAccVPCSecurityGroupConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -1340,7 +1340,7 @@ func TestAccVPCSecurityGroup_self(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupSelfConfig(rName), + Config: testAccVPCSecurityGroupConfig_self(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), @@ -1375,7 +1375,7 @@ func TestAccVPCSecurityGroup_vpc(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCConfig(rName), + Config: testAccVPCSecurityGroupConfig_vpc(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), @@ -1419,7 +1419,7 @@ func TestAccVPCSecurityGroup_vpcNegOneIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCNegOneIngressConfig(rName), + Config: testAccVPCSecurityGroupConfig_vpcNegativeOneIngress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), @@ -1455,7 +1455,7 @@ func TestAccVPCSecurityGroup_vpcProtoNumIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupVPCProtoNumIngressConfig(rName), + Config: testAccVPCSecurityGroupConfig_vpcProtocolNumberIngress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), @@ -1491,7 +1491,7 @@ func TestAccVPCSecurityGroup_multiIngress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupMultiIngressConfig(rName), + Config: testAccVPCSecurityGroupConfig_multiIngress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1518,7 +1518,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupRuleDescriptionConfig(rName, "Egress description", "Ingress description"), + Config: testAccVPCSecurityGroupConfig_ruleDescription(rName, "Egress description", "Ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1556,7 +1556,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { }, // Change just the rule descriptions. { - Config: testAccSecurityGroupRuleDescriptionConfig(rName, "New egress description", "New ingress description"), + Config: testAccVPCSecurityGroupConfig_ruleDescription(rName, "New egress description", "New ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1588,7 +1588,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { }, // Remove just the rule descriptions. { - Config: testAccSecurityGroupEmptyRuleDescriptionConfig(rName), + Config: testAccVPCSecurityGroupConfig_emptyRuleDescription(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1631,7 +1631,7 @@ func TestAccVPCSecurityGroup_defaultEgressVPC(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupDefaultEgressConfig(rName), + Config: testAccVPCSecurityGroupConfig_defaultEgress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1661,7 +1661,7 @@ func TestAccVPCSecurityGroup_drift(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupDriftConfig(rName), + Config: testAccVPCSecurityGroupConfig_drift(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -1715,7 +1715,7 @@ func TestAccVPCSecurityGroup_driftComplex(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupDriftComplexConfig(rName), + Config: testAccVPCSecurityGroupConfig_driftComplex(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "3"), @@ -1789,19 +1789,19 @@ func TestAccVPCSecurityGroup_invalidCIDRBlock(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupInvalidIngressCIDRConfig, + Config: testAccVPCSecurityGroupConfig_invalidIngressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupInvalidEgressCIDRConfig, + Config: testAccVPCSecurityGroupConfig_invalidEgressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccSecurityGroupInvalidIPv6IngressCIDRConfig, + Config: testAccVPCSecurityGroupConfig_invalidIPv6IngressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, { - Config: testAccSecurityGroupInvalidIPv6EgressCIDRConfig, + Config: testAccVPCSecurityGroupConfig_invalidIPv6EgressCIDR, ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, }, @@ -1820,7 +1820,7 @@ func TestAccVPCSecurityGroup_cidrAndGroups(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupCombinedCIDRAndGroupsConfig(rName), + Config: testAccVPCSecurityGroupConfig_combinedCIDRAndGroups(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), @@ -1847,7 +1847,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIngressWithCIDRAndSGsConfig(rName), + Config: testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGs(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), @@ -1899,7 +1899,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupEC2ClassicDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName), + Config: testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGsEC2Classic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupEC2ClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -1918,7 +1918,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { ), }, { - Config: testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName), + Config: testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGsEC2Classic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1939,7 +1939,7 @@ func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupPrefixListEgressConfig, + Config: testAccVPCSecurityGroupConfig_prefixListEgress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupEgressPrefixListAttributes(&group), @@ -1967,7 +1967,7 @@ func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupPrefixListIngressConfig, + Config: testAccVPCSecurityGroupConfig_prefixListIngress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupIngressPrefixListAttributes(&group), @@ -1995,7 +1995,7 @@ func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupIPv4andIpv6EgressConfig, + Config: testAccVPCSecurityGroupConfig_ipv4andIPv6Egress, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -2048,7 +2048,7 @@ func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccSecurityGroupConfig_failWithDiffMismatch, + Config: testAccVPCSecurityGroupConfig_failWithDiffMismatch, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -2074,7 +2074,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2083,7 +2083,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { }, // append a rule to step over the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2095,7 +2095,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2121,7 +2121,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, 1), @@ -2129,7 +2129,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { }, // append a rule to step over the limit { - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2157,7 +2157,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupCIDRBlockRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, 1), @@ -2182,7 +2182,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2190,7 +2190,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { }, // prepend a rule to step over the limit { - Config: testAccSecurityGroupRuleLimitConfig(1, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(1, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2202,7 +2202,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2227,7 +2227,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2235,7 +2235,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { }, // add a rule to step over the limit with entirely new rules { - Config: testAccSecurityGroupRuleLimitConfig(100, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(100, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2247,7 +2247,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccSecurityGroupRuleLimitConfig(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2270,19 +2270,19 @@ func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { Steps: []resource.TestStep{ // Create a valid security group with some rules and make sure it exists { - Config: testAccSecurityGroupConfig_rulesDropOnError_Init, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit, Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), }, // Add a bad rule to trigger API error { - Config: testAccSecurityGroupConfig_rulesDropOnError_AddBadRule, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule, ExpectError: regexp.MustCompile("InvalidGroup.NotFound"), }, // All originally added rules must survive. This will return non-empty plan if anything changed. { - Config: testAccSecurityGroupConfig_rulesDropOnError_Init, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit, PlanOnly: true, }, }, @@ -2655,7 +2655,7 @@ func testSecurityGroupRuleCount(id string, expectedIngressCount, expectedEgressC return nil } -func testAccSecurityGroupNameConfig(rName string) string { +func testAccVPCSecurityGroupConfig_name(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -2672,7 +2672,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupEC2ClassicConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ec2Classic(rName string) string { return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -2680,7 +2680,7 @@ resource "aws_security_group" "test" { `, rName)) } -func testAccSecurityGroupNameGeneratedConfig(rName string) string { +func testAccVPCSecurityGroupConfig_nameGenerated(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2696,7 +2696,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupNamePrefixConfig(rName, namePrefix string) string { +func testAccVPCSecurityGroupConfig_namePrefix(rName, namePrefix string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -2713,7 +2713,7 @@ resource "aws_security_group" "test" { `, rName, namePrefix) } -func testAccSecurityGroupConfigTags1(rName, tagKey1, tagValue1 string) string { +func testAccVPCSecurityGroupConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2734,7 +2734,7 @@ resource "aws_security_group" "test" { `, rName, tagKey1, tagValue1) } -func testAccSecurityGroupConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccVPCSecurityGroupConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2756,7 +2756,7 @@ resource "aws_security_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccSecurityGroupRuleLimitConfig(egressStartIndex, egressRulesCount int) string { +func testAccVPCSecurityGroupConfig_ruleLimit(egressStartIndex, egressRulesCount int) string { var egressRules strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { fmt.Fprintf(&egressRules, ` @@ -2793,7 +2793,7 @@ resource "aws_security_group" "test" { `, egressRules.String()) } -func testAccSecurityGroupCIDRBlockRuleLimitConfig(egressStartIndex, egressRulesCount int) string { +func testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(egressStartIndex, egressRulesCount int) string { var cidrBlocks strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { fmt.Fprintf(&cidrBlocks, ` @@ -2832,7 +2832,7 @@ resource "aws_security_group" "test" { `, cidrBlocks.String()) } -func testAccSecurityGroupEmptyRuleDescriptionConfig(rName string) string { +func testAccVPCSecurityGroupConfig_emptyRuleDescription(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2869,7 +2869,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupIPv6Config(rName string) string { +func testAccVPCSecurityGroupConfig_ipv6(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2904,7 +2904,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupConfig(rName string) string { +func testAccVPCSecurityGroupConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2932,7 +2932,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupRevokeBaseRemovedConfig(rName string) string { +func testAccVPCSecurityGroupConfig_revokeBaseRemoved(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2944,7 +2944,7 @@ resource "aws_vpc" "test" { `, rName) } -func testAccSecurityGroupRevokeBaseConfig(rName string) string { +func testAccVPCSecurityGroupConfig_revokeBase(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -2974,7 +2974,7 @@ resource "aws_security_group" "secondary" { `, rName) } -func testAccSecurityGroupRevokeFalseConfig(rName string) string { +func testAccVPCSecurityGroupConfig_revokeFalse(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3008,7 +3008,7 @@ resource "aws_security_group" "secondary" { `, rName) } -func testAccSecurityGroupRevokeTrueConfig(rName string) string { +func testAccVPCSecurityGroupConfig_revokeTrue(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3042,7 +3042,7 @@ resource "aws_security_group" "secondary" { `, rName) } -func testAccSecurityGroupChangeConfig(rName string) string { +func testAccVPCSecurityGroupConfig_changed(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3084,7 +3084,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupRuleDescriptionConfig(rName, egressDescription, ingressDescription string) string { +func testAccVPCSecurityGroupConfig_ruleDescription(rName, egressDescription, ingressDescription string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3121,7 +3121,7 @@ resource "aws_security_group" "test" { `, rName, ingressDescription, egressDescription) } -func testAccSecurityGroupSelfConfig(rName string) string { +func testAccVPCSecurityGroupConfig_self(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3156,7 +3156,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupVPCConfig(rName string) string { +func testAccVPCSecurityGroupConfig_vpc(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3191,7 +3191,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupVPCNegOneIngressConfig(rName string) string { +func testAccVPCSecurityGroupConfig_vpcNegativeOneIngress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3219,7 +3219,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupVPCProtoNumIngressConfig(rName string) string { +func testAccVPCSecurityGroupConfig_vpcProtocolNumberIngress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3247,7 +3247,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupMultiIngressConfig(rName string) string { +func testAccVPCSecurityGroupConfig_multiIngress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3319,7 +3319,7 @@ resource "aws_security_group" "test2" { `, rName) } -func testAccSecurityGroupDefaultEgressConfig(rName string) string { +func testAccVPCSecurityGroupConfig_defaultEgress(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -3347,7 +3347,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupDriftConfig(rName string) string { +func testAccVPCSecurityGroupConfig_drift(rName string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -3373,7 +3373,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupDriftComplexConfig(rName string) string { +func testAccVPCSecurityGroupConfig_driftComplex(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3441,7 +3441,7 @@ resource "aws_security_group" "test1" { `, rName) } -const testAccSecurityGroupInvalidIngressCIDRConfig = ` +const testAccVPCSecurityGroupConfig_invalidIngressCIDR = ` resource "aws_security_group" "test" { ingress { from_port = 0 @@ -3452,7 +3452,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidEgressCIDRConfig = ` +const testAccVPCSecurityGroupConfig_invalidEgressCIDR = ` resource "aws_security_group" "test" { egress { from_port = 0 @@ -3463,7 +3463,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidIPv6IngressCIDRConfig = ` +const testAccVPCSecurityGroupConfig_invalidIPv6IngressCIDR = ` resource "aws_security_group" "test" { ingress { from_port = 0 @@ -3474,7 +3474,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupInvalidIPv6EgressCIDRConfig = ` +const testAccVPCSecurityGroupConfig_invalidIPv6EgressCIDR = ` resource "aws_security_group" "test" { egress { from_port = 0 @@ -3485,7 +3485,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupCombinedCIDRAndGroupsConfig(rName string) string { +func testAccVPCSecurityGroupConfig_combinedCIDRAndGroups(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3546,7 +3546,7 @@ resource "aws_security_group" "test1" { `, rName) } -func testAccSecurityGroupIngressWithCIDRAndSGsConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGs(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3601,7 +3601,7 @@ resource "aws_security_group" "test1" { `, rName) } -func testAccSecurityGroupConfig_ingressWithCIDRAndSGs_classic(rName string) string { +func testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGsEC2Classic(rName string) string { return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_security_group" "test2" { name = "%[1]s-2" @@ -3643,7 +3643,7 @@ resource "aws_security_group" "test" { // fails to apply in one pass with the error "diffs didn't match during apply" // GH-2027 -const testAccSecurityGroupConfig_failWithDiffMismatch = ` +const testAccVPCSecurityGroupConfig_failWithDiffMismatch = ` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" @@ -3688,7 +3688,7 @@ resource "aws_security_group" "nat" { } ` -func testAccSecurityGroupAllowAllConfig(rName string) string { +func testAccVPCSecurityGroupConfig_allowAll(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" @@ -3729,7 +3729,7 @@ resource "aws_security_group_rule" "allow_all-1" { `, rName) } -func testAccSecurityGroupSourceSecurityGroupConfig(rName string) string { +func testAccVPCSecurityGroupConfig_sourceSecurityGroup(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3788,7 +3788,7 @@ resource "aws_security_group_rule" "allow_test3" { `, rName) } -func testAccSecurityGroupIPRangeAndSecurityGroupWithSameRulesConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ipRangeAndSecurityGroupWithSameRules(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3848,7 +3848,7 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { `, rName) } -func testAccSecurityGroupIPRangesWithSameRulesConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ipRangesWithSameRules(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -3889,7 +3889,7 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { `, rName) } -const testAccSecurityGroupIPv4andIpv6EgressConfig = ` +const testAccVPCSecurityGroupConfig_ipv4andIPv6Egress = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" assign_generated_ipv6_cidr_block = true @@ -3920,7 +3920,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupPrefixListEgressConfig = ` +const testAccVPCSecurityGroupConfig_prefixListEgress = ` data "aws_region" "current" {} resource "aws_vpc" "tf_sg_prefix_list_egress_test" { @@ -3970,7 +3970,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupPrefixListIngressConfig = ` +const testAccVPCSecurityGroupConfig_prefixListIngress = ` data "aws_region" "current" {} resource "aws_vpc" "tf_sg_prefix_list_ingress_test" { @@ -4020,7 +4020,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupRuleGatheringConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ruleGathering(rName string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -4158,7 +4158,7 @@ resource "aws_security_group" "test" { `, rName) } -const testAccSecurityGroupConfig_rulesDropOnError_Init = ` +const testAccVPCSecurityGroupConfig_rulesDropOnErrorInit = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4198,7 +4198,7 @@ resource "aws_security_group" "test" { } ` -const testAccSecurityGroupConfig_rulesDropOnError_AddBadRule = ` +const testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4239,7 +4239,7 @@ resource "aws_security_group" "test" { } ` -func testAccSecurityGroupEgressModeBlocksConfig(rName string) string { +func testAccVPCSecurityGroupConfig_egressModeBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4275,7 +4275,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupEgressModeNoBlocksConfig(rName string) string { +func testAccVPCSecurityGroupConfig_egressModeNoBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4297,7 +4297,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupEgressModeZeroedConfig(rName string) string { +func testAccVPCSecurityGroupConfig_egressModeZeroed(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4321,7 +4321,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupIngressModeBlocksConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ingressModeBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4357,7 +4357,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupIngressModeNoBlocksConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ingressModeNoBlocks(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4379,7 +4379,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccSecurityGroupIngressModeZeroedConfig(rName string) string { +func testAccVPCSecurityGroupConfig_ingressModeZeroed(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" From 1f84678a3aa0649a033abab5abec7d778ac205c1 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 10:52:25 -0400 Subject: [PATCH 039/120] Remove unused functions. --- .../service/ec2/vpc_security_group_test.go | 70 ------------------- 1 file changed, 70 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 68ac9bf5e690..e60c77854b18 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -2484,39 +2484,6 @@ func testAccCheckSecurityGroupEC2ClassicExists(n string, v *ec2.SecurityGroup) r } } -func testAccCheckSecurityGroupAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - p := &ec2.IpPermission{ - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - } - - if *group.GroupName != "terraform_acceptance_test_example" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - - // Compare our ingress - if !reflect.DeepEqual(group.IpPermissions[0], p) { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions[0], - p) - } - - return nil - } -} - // testAccSecurityGroupRulesPerGroupLimitFromEnv returns security group rules per group limit // Currently this information is not available from any EC2 or Trusted Advisor API // Prefers the EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT environment variable or defaults to 50 @@ -2539,43 +2506,6 @@ func testAccSecurityGroupRulesPerGroupLimitFromEnv() int { return envLimitInt } -func testAccCheckSecurityGroupSGandCIDRAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.GroupName != "terraform_acceptance_test_example" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - - if len(group.IpPermissions) != 2 { - return fmt.Errorf("Expected 2 ingress rules, got %d", len(group.IpPermissions)) - } - - for _, p := range group.IpPermissions { - if *p.FromPort == int64(22) { - if len(p.IpRanges) != 1 || p.UserIdGroupPairs != nil { - return fmt.Errorf("Found ip perm of 22, but not the right ipranges / pairs: %s", p) - } - continue - } else if *p.FromPort == int64(80) { - if len(p.IpRanges) != 1 || len(p.UserIdGroupPairs) != 1 { - return fmt.Errorf("Found ip perm of 80, but not the right ipranges / pairs: %s", p) - } - continue - } - return fmt.Errorf("Found a rouge rule") - } - - return nil - } -} - func testAccCheckSecurityGroupEgressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { if *group.GroupName != "terraform_acceptance_test_prefix_list_egress" { From ac7ee0773a4ad456b3875223d57cf8c82573a0f4 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 10:57:28 -0400 Subject: [PATCH 040/120] r/aws_security_group: 'acctest.Providers' -> 'acctest.ProviderFactories'. --- .../service/ec2/vpc_security_group_test.go | 312 +++++++++--------- 1 file changed, 156 insertions(+), 156 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index e60c77854b18..b1a7b8820fb3 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -502,10 +502,10 @@ func TestAccVPCSecurityGroup_basic(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_name(rName), @@ -576,10 +576,10 @@ func TestAccVPCSecurityGroup_disappears(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_name(rName), @@ -599,10 +599,10 @@ func TestAccVPCSecurityGroup_nameGenerated(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_nameGenerated(rName), @@ -629,10 +629,10 @@ func TestAccVPCSecurityGroup_nameTerraformPrefix(t *testing.T) { rName := sdkacctest.RandomWithPrefix("terraform-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_name(rName), @@ -658,10 +658,10 @@ func TestAccVPCSecurityGroup_namePrefix(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_namePrefix(rName, "tf-acc-test-prefix-"), @@ -688,10 +688,10 @@ func TestAccVPCSecurityGroup_namePrefixTerraform(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_namePrefix(rName, "terraform-test"), @@ -717,10 +717,10 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_tags1(rName, "key1", "value1"), @@ -763,10 +763,10 @@ func TestAccVPCSecurityGroup_allowAll(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_allowAll(rName), @@ -790,10 +790,10 @@ func TestAccVPCSecurityGroup_sourceSecurityGroup(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_sourceSecurityGroup(rName), @@ -817,10 +817,10 @@ func TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ipRangeAndSecurityGroupWithSameRules(rName), @@ -844,10 +844,10 @@ func TestAccVPCSecurityGroup_ipRangesWithSameRules(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ipRangesWithSameRules(rName), @@ -871,10 +871,10 @@ func TestAccVPCSecurityGroup_egressMode(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckNetworkACLDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_egressModeBlocks(rName), @@ -913,10 +913,10 @@ func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckNetworkACLDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckNetworkACLDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ingressModeBlocks(rName), @@ -955,10 +955,10 @@ func TestAccVPCSecurityGroup_ruleGathering(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ruleGathering(rName), @@ -1068,10 +1068,10 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { testRemoveCycle := testRemoveRuleCycle(&primary, &secondary) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // create the configuration with 2 security groups, then create a // dependency cycle such that they cannot be deleted @@ -1148,10 +1148,10 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { testRemoveCycle := testRemoveRuleCycle(&primary, &secondary) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // create the configuration with 2 security groups, then create a // dependency cycle such that they cannot be deleted. These Security @@ -1203,10 +1203,10 @@ func TestAccVPCSecurityGroup_change(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_basic(rName), @@ -1272,10 +1272,10 @@ func TestAccVPCSecurityGroup_ipv6(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ipv6(rName), @@ -1334,10 +1334,10 @@ func TestAccVPCSecurityGroup_self(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_self(rName), @@ -1369,10 +1369,10 @@ func TestAccVPCSecurityGroup_vpc(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_vpc(rName), @@ -1413,10 +1413,10 @@ func TestAccVPCSecurityGroup_vpcNegOneIngress(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_vpcNegativeOneIngress(rName), @@ -1449,10 +1449,10 @@ func TestAccVPCSecurityGroup_vpcProtoNumIngress(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_vpcProtocolNumberIngress(rName), @@ -1485,10 +1485,10 @@ func TestAccVPCSecurityGroup_multiIngress(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_multiIngress(rName), @@ -1512,10 +1512,10 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ruleDescription(rName, "Egress description", "Ingress description"), @@ -1625,10 +1625,10 @@ func TestAccVPCSecurityGroup_defaultEgressVPC(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_defaultEgress(rName), @@ -1655,10 +1655,10 @@ func TestAccVPCSecurityGroup_drift(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_drift(rName), @@ -1709,10 +1709,10 @@ func TestAccVPCSecurityGroup_driftComplex(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_driftComplex(rName), @@ -1783,10 +1783,10 @@ func TestAccVPCSecurityGroup_driftComplex(t *testing.T) { func TestAccVPCSecurityGroup_invalidCIDRBlock(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_invalidIngressCIDR, @@ -1814,10 +1814,10 @@ func TestAccVPCSecurityGroup_cidrAndGroups(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_combinedCIDRAndGroups(rName), @@ -1841,10 +1841,10 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGs(rName), @@ -1933,10 +1933,10 @@ func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_prefixListEgress, @@ -1961,10 +1961,10 @@ func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_prefixListIngress, @@ -1989,10 +1989,10 @@ func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_ipv4andIPv6Egress, @@ -2042,10 +2042,10 @@ func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { resourceName := "aws_security_group.nat" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupConfig_failWithDiffMismatch, @@ -2067,10 +2067,10 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // create a valid SG just under the limit { @@ -2114,10 +2114,10 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // create a valid SG just under the limit { @@ -2175,10 +2175,10 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // create a valid SG just under the limit { @@ -2220,10 +2220,10 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // create a valid SG just under the limit { @@ -2263,10 +2263,10 @@ func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - Providers: acctest.Providers, - CheckDestroy: testAccCheckSecurityGroupDestroy, + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ // Create a valid security group with some rules and make sure it exists { From 59b68e00d4eb1089ba981dc013f489eb92b44678 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 10:59:02 -0400 Subject: [PATCH 041/120] Fix semgrep 'prefer-aws-go-sdk-pointer-conversion-assignment' errors. --- internal/service/ec2/vpc_security_group.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index d039c1201ba5..a1a2db93edc7 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -1303,10 +1303,10 @@ func deleteLingeringLambdaENIs(conn *ec2.EC2, filterName, resourceId string, tim func initSecurityGroupRule(ruleMap map[string]map[string]interface{}, perm *ec2.IpPermission, desc string) map[string]interface{} { var fromPort, toPort int64 if v := perm.FromPort; v != nil { - fromPort = *v + fromPort = aws.Int64Value(v) } if v := perm.ToPort; v != nil { - toPort = *v + toPort = aws.Int64Value(v) } k := fmt.Sprintf("%s-%d-%d-%s", *perm.IpProtocol, fromPort, toPort, desc) rule, ok := ruleMap[k] @@ -1314,7 +1314,7 @@ func initSecurityGroupRule(ruleMap map[string]map[string]interface{}, perm *ec2. rule = make(map[string]interface{}) ruleMap[k] = rule } - rule["protocol"] = *perm.IpProtocol + rule["protocol"] = aws.StringValue(perm.IpProtocol) rule["from_port"] = fromPort rule["to_port"] = toPort if desc != "" { From 3828569bc6ba330f53ee8bbe8b1a879e7fb632d9 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:00:48 -0400 Subject: [PATCH 042/120] Fix semgrep 'prefer-aws-go-sdk-pointer-conversion-conditional' errors. --- internal/service/ec2/vpc_security_group.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index a1a2db93edc7..95a80babe136 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -550,7 +550,7 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, rule := initSecurityGroupRule(ruleMap, perm, desc) - if *g.GroupId == groupId { + if aws.StringValue(g.GroupId) == groupId { rule["self"] = true continue } @@ -633,7 +633,7 @@ func resourceSecurityGroupUpdateRules( GroupId: group.GroupId, IpPermissions: remove, } - if group.VpcId == nil || *group.VpcId == "" { + if aws.StringValue(group.VpcId) == "" { req.GroupId = nil req.GroupName = group.GroupName } @@ -660,7 +660,7 @@ func resourceSecurityGroupUpdateRules( GroupId: group.GroupId, IpPermissions: add, } - if group.VpcId == nil || *group.VpcId == "" { + if aws.StringValue(group.VpcId) == "" { req.GroupId = nil req.GroupName = group.GroupName } From c3bf562231b6df8c2b0fb598233ec5f2235a5d9c Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:08:41 -0400 Subject: [PATCH 043/120] Fix semgrep naming errors. --- internal/service/ec2/vpc_security_group_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index b1a7b8820fb3..741d49c321a2 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -2289,11 +2289,11 @@ func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { }) } -// cycleIpPermForGroup returns an IpPermission struct with a configured +// cycleIPPermForGroup returns an IpPermission struct with a configured // UserIdGroupPair for the groupid given. Used in // TestAccAWSSecurityGroup_forceRevokeRules_should_fail to create a cyclic rule // between 2 security groups -func cycleIpPermForGroup(groupId string) *ec2.IpPermission { +func cycleIPPermForGroup(groupId string) *ec2.IpPermission { var perm ec2.IpPermission perm.FromPort = aws.Int64(0) perm.ToPort = aws.Int64(0) @@ -2320,9 +2320,9 @@ func testAddRuleCycle(primary, secondary *ec2.SecurityGroup) resource.TestCheckF conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn // cycle from primary to secondary - perm1 := cycleIpPermForGroup(*secondary.GroupId) + perm1 := cycleIPPermForGroup(aws.StringValue(secondary.GroupId)) // cycle from secondary to primary - perm2 := cycleIpPermForGroup(*primary.GroupId) + perm2 := cycleIPPermForGroup(aws.StringValue(primary.GroupId)) req1 := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: primary.GroupId, @@ -2410,7 +2410,7 @@ func testAccCheckSecurityGroupDestroy(s *terraform.State) error { return nil } -func testAccCheckSecurityGroupEC2ClassicDestroy(s *terraform.State) error { +func testAccCheckSecurityGroupEC2ClassicDestroy(s *terraform.State) error { // nosemgrep:ec2-in-func-name conn := acctest.ProviderEC2Classic.Meta().(*conns.AWSClient).EC2Conn for _, rs := range s.RootModule().Resources { @@ -2459,7 +2459,7 @@ func testAccCheckSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.Te } } -func testAccCheckSecurityGroupEC2ClassicExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckSecurityGroupEC2ClassicExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { // nosemgrep:ec2-in-func-name return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -2602,7 +2602,7 @@ resource "aws_security_group" "test" { `, rName) } -func testAccVPCSecurityGroupConfig_ec2Classic(rName string) string { +func testAccVPCSecurityGroupConfig_ec2Classic(rName string) string { // nosemgrep:ec2-in-func-name return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_security_group" "test" { name = %[1]q @@ -3531,7 +3531,7 @@ resource "aws_security_group" "test1" { `, rName) } -func testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGsEC2Classic(rName string) string { +func testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGsEC2Classic(rName string) string { // nosemgrep:ec2-in-func-name return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_security_group" "test2" { name = "%[1]s-2" From 48879a866d1fe2c050e58ce7b2aff86733dc425d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:14:03 -0400 Subject: [PATCH 044/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic -timeout 180m === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic (15.42s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 20.061s --- internal/service/ec2/vpc_security_group_test.go | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 741d49c321a2..9a5475cb888a 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -3534,17 +3534,15 @@ resource "aws_security_group" "test1" { func testAccVPCSecurityGroupConfig_ingressWithCIDRAndSGsEC2Classic(rName string) string { // nosemgrep:ec2-in-func-name return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_security_group" "test2" { - name = "%[1]s-2" - description = "Used in the terraform acceptance tests" + name = "%[1]s-2" tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group" "test" { - name = %[1]q - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test1" { + name = "%[1]s-1" ingress { protocol = "tcp" @@ -3565,7 +3563,7 @@ resource "aws_security_group" "test" { } tags = { - Name = "tf-acc-test" + Name = %[1]q } } `, rName)) From 261263999d58eed381c613fd3495d9543d567599 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:21:23 -0400 Subject: [PATCH 045/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_failWithDiffMismatch'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_failWithDiffMismatch' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_failWithDiffMismatch -timeout 180m === RUN TestAccVPCSecurityGroup_failWithDiffMismatch === PAUSE TestAccVPCSecurityGroup_failWithDiffMismatch === CONT TestAccVPCSecurityGroup_failWithDiffMismatch --- PASS: TestAccVPCSecurityGroup_failWithDiffMismatch (23.78s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.280s --- .../service/ec2/vpc_security_group_test.go | 48 +++++++++++-------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 9a5475cb888a..b364fad66df2 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -2038,8 +2038,8 @@ func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { var group ec2.SecurityGroup - - resourceName := "aws_security_group.nat" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group.test1" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -2048,7 +2048,7 @@ func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupConfig_failWithDiffMismatch, + Config: testAccVPCSecurityGroupConfig_failWithDiffMismatch(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), @@ -3571,50 +3571,58 @@ resource "aws_security_group" "test1" { // fails to apply in one pass with the error "diffs didn't match during apply" // GH-2027 -const testAccVPCSecurityGroupConfig_failWithDiffMismatch = ` +func testAccVPCSecurityGroupConfig_failWithDiffMismatch(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-fail-w-diff-mismatch" + Name = %[1]q } } -resource "aws_security_group" "ssh_base" { - name = "test-ssh-base" +resource "aws_security_group" "test3" { vpc_id = aws_vpc.main.id -} + name = "%[1]s-3" -resource "aws_security_group" "jump" { - name = "test-jump" - vpc_id = aws_vpc.main.id + tags = { + Name = %[1]q + } } -resource "aws_security_group" "provision" { - name = "test-provision" +resource "aws_security_group" "test2" { vpc_id = aws_vpc.main.id + name = "%[1]s-2" + + tags = { + Name = %[1]q + } } -resource "aws_security_group" "nat" { - vpc_id = aws_vpc.main.id - name = "nat" - description = "For nat servers " +resource "aws_security_group" "test1" { + vpc_id = aws_vpc.main.id + name = "%[1]s-1" ingress { from_port = 22 to_port = 22 protocol = "tcp" - security_groups = [aws_security_group.jump.id] + security_groups = [aws_security_group.test2.id] } ingress { from_port = 22 to_port = 22 protocol = "tcp" - security_groups = [aws_security_group.provision.id] + security_groups = [aws_security_group.test3.id] + } + + tags = { + Name = %[1]q } } -` +`, rName) +} func testAccVPCSecurityGroupConfig_allowAll(rName string) string { return fmt.Sprintf(` From a6bfea5796053133f4133741ccd25da40d6e8047 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:24:29 -0400 Subject: [PATCH 046/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_allowAll'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_allowAll' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_allowAll -timeout 180m === RUN TestAccVPCSecurityGroup_allowAll === PAUSE TestAccVPCSecurityGroup_allowAll === CONT TestAccVPCSecurityGroup_allowAll --- PASS: TestAccVPCSecurityGroup_allowAll (29.32s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 33.379s --- internal/service/ec2/vpc_security_group_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index b364fad66df2..cd522639ffc0 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -3626,7 +3626,7 @@ resource "aws_security_group" "test1" { func testAccVPCSecurityGroupConfig_allowAll(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { @@ -3636,14 +3636,14 @@ resource "aws_vpc" "foo" { resource "aws_security_group" "test" { name = %[1]q - vpc_id = aws_vpc.foo.id + vpc_id = aws_vpc.test.id tags = { Name = %[1]q } } -resource "aws_security_group_rule" "allow_all" { +resource "aws_security_group_rule" "allow_all-1" { type = "ingress" from_port = 0 to_port = 65535 @@ -3653,7 +3653,7 @@ resource "aws_security_group_rule" "allow_all" { security_group_id = aws_security_group.test.id } -resource "aws_security_group_rule" "allow_all-1" { +resource "aws_security_group_rule" "allow_all-2" { type = "ingress" from_port = 65534 to_port = 65535 From 73704989880e3af1c2e5180c93cb0c4e1d94ae88 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:30:16 -0400 Subject: [PATCH 047/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_driftComplex'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_driftComplex' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_driftComplex -timeout 180m === RUN TestAccVPCSecurityGroup_driftComplex === PAUSE TestAccVPCSecurityGroup_driftComplex === CONT TestAccVPCSecurityGroup_driftComplex --- PASS: TestAccVPCSecurityGroup_driftComplex (25.12s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 29.228s --- internal/service/ec2/vpc_security_group_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index cd522639ffc0..9f44e9d08974 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -3316,6 +3316,10 @@ resource "aws_vpc" "test" { resource "aws_security_group" "test2" { name = "%[1]s-2" vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test1" { @@ -3365,7 +3369,7 @@ resource "aws_security_group" "test1" { } tags = { - Name = "tf-acc-test" + Name = %[1]q } } `, rName) From bc9905a115a958aa86fd6955d5bfdcf7694b7b20 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:34:40 -0400 Subject: [PATCH 048/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_ipv4AndIPv6Egress'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_ipv4AndIPv6Egress' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_ipv4AndIPv6Egress -timeout 180m === RUN TestAccVPCSecurityGroup_ipv4AndIPv6Egress === PAUSE TestAccVPCSecurityGroup_ipv4AndIPv6Egress === CONT TestAccVPCSecurityGroup_ipv4AndIPv6Egress --- PASS: TestAccVPCSecurityGroup_ipv4AndIPv6Egress (32.17s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 36.381s --- .../service/ec2/vpc_security_group_test.go | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 9f44e9d08974..ed5ed77de33c 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -1987,6 +1987,7 @@ func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1995,7 +1996,7 @@ func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupConfig_ipv4andIPv6Egress, + Config: testAccVPCSecurityGroupConfig_ipv4andIPv6Egress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), @@ -3829,20 +3830,20 @@ resource "aws_security_group_rule" "allow_ipv6_cidr_block" { `, rName) } -const testAccVPCSecurityGroupConfig_ipv4andIPv6Egress = ` -resource "aws_vpc" "foo" { +func testAccVPCSecurityGroupConfig_ipv4andIPv6Egress(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" assign_generated_ipv6_cidr_block = true tags = { - Name = "terraform-testacc-security-group-ipv4-and-ipv6-egress" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_example" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.foo.id + name = %[1]q + vpc_id = aws_vpc.test.id egress { from_port = 0 @@ -3857,8 +3858,13 @@ resource "aws_security_group" "test" { protocol = "-1" ipv6_cidr_blocks = ["::/0"] } + + tags = { + Name = %[1]q + } +} +`, rName) } -` const testAccVPCSecurityGroupConfig_prefixListEgress = ` data "aws_region" "current" {} From a1078809414879057f745c63123c6c7d31e8a076 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 11:40:18 -0400 Subject: [PATCH 049/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_egressWithPrefixList'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_egressWithPrefixList' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_egressWithPrefixList -timeout 180m === RUN TestAccVPCSecurityGroup_egressWithPrefixList === PAUSE TestAccVPCSecurityGroup_egressWithPrefixList === CONT TestAccVPCSecurityGroup_egressWithPrefixList --- PASS: TestAccVPCSecurityGroup_egressWithPrefixList (37.09s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 40.987s --- .../service/ec2/vpc_security_group_test.go | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index ed5ed77de33c..240195f8d75c 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -1931,6 +1931,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic(t *testing.T) { func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1939,10 +1940,9 @@ func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupConfig_prefixListEgress, + Config: testAccVPCSecurityGroupConfig_prefixListEgress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupEgressPrefixListAttributes(&group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), ), }, @@ -3866,25 +3866,34 @@ resource "aws_security_group" "test" { `, rName) } -const testAccVPCSecurityGroupConfig_prefixListEgress = ` +func testAccVPCSecurityGroupConfig_prefixListEgress(rName string) string { + return fmt.Sprintf(` data "aws_region" "current" {} -resource "aws_vpc" "tf_sg_prefix_list_egress_test" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-prefix-list-egress" + Name = %[1]q } } -resource "aws_route_table" "default" { - vpc_id = aws_vpc.tf_sg_prefix_list_egress_test.id +resource "aws_route_table" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_vpc_endpoint" "test" { - vpc_id = aws_vpc.tf_sg_prefix_list_egress_test.id + vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" - route_table_ids = [aws_route_table.default.id] + route_table_ids = [aws_route_table.test.id] + + tags = { + Name = %[1]q + } policy = < Date: Tue, 28 Jun 2022 11:44:31 -0400 Subject: [PATCH 050/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_ingressWithPrefixList'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_ingressWithPrefixList' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_ingressWithPrefixList -timeout 180m === RUN TestAccVPCSecurityGroup_ingressWithPrefixList === PAUSE TestAccVPCSecurityGroup_ingressWithPrefixList === CONT TestAccVPCSecurityGroup_ingressWithPrefixList --- PASS: TestAccVPCSecurityGroup_ingressWithPrefixList (36.24s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 40.245s --- .../service/ec2/vpc_security_group_test.go | 89 ++++++------------- 1 file changed, 26 insertions(+), 63 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 240195f8d75c..c24240114c4c 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -1959,6 +1959,7 @@ func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_security_group.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1967,10 +1968,9 @@ func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupConfig_prefixListIngress, + Config: testAccVPCSecurityGroupConfig_prefixListIngress(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), - testAccCheckSecurityGroupIngressPrefixListAttributes(&group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), ), }, @@ -2507,56 +2507,6 @@ func testAccSecurityGroupRulesPerGroupLimitFromEnv() int { return envLimitInt } -func testAccCheckSecurityGroupEgressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.GroupName != "terraform_acceptance_test_prefix_list_egress" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - if len(group.IpPermissionsEgress) == 0 { - return fmt.Errorf("No egress IPPerms") - } - if len(group.IpPermissionsEgress) != 1 { - return fmt.Errorf("Expected 1 egress rule, got %d", len(group.IpPermissions)) - } - - p := group.IpPermissionsEgress[0] - - if len(p.PrefixListIds) != 1 { - return fmt.Errorf("Expected 1 prefix list, got %d", len(p.PrefixListIds)) - } - - return nil - } -} - -func testAccCheckSecurityGroupIngressPrefixListAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *group.GroupName != "terraform_acceptance_test_prefix_list_ingress" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - if *group.Description != "Used in the terraform acceptance tests" { - return fmt.Errorf("Bad description: %s", *group.Description) - } - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - if len(group.IpPermissions) != 1 { - return fmt.Errorf("Expected 1 rule, got %d", len(group.IpPermissions)) - } - - p := group.IpPermissions[0] - - if len(p.PrefixListIds) != 1 { - return fmt.Errorf("Expected 1 prefix list, got %d", len(p.PrefixListIds)) - } - - return nil - } -} - func testAccCheckSecurityGroupRuleCount(group *ec2.SecurityGroup, expectedIngressCount, expectedEgressCount int) resource.TestCheckFunc { return func(s *terraform.State) error { id := aws.StringValue(group.GroupId) @@ -3929,25 +3879,34 @@ resource "aws_security_group" "test" { `, rName) } -const testAccVPCSecurityGroupConfig_prefixListIngress = ` +func testAccVPCSecurityGroupConfig_prefixListIngress(rName string) string { + return fmt.Sprintf(` data "aws_region" "current" {} -resource "aws_vpc" "tf_sg_prefix_list_ingress_test" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-prefix-list-ingress" + Name = %[1]q } } -resource "aws_route_table" "default" { - vpc_id = aws_vpc.tf_sg_prefix_list_ingress_test.id +resource "aws_route_table" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_vpc_endpoint" "test" { - vpc_id = aws_vpc.tf_sg_prefix_list_ingress_test.id + vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" - route_table_ids = [aws_route_table.default.id] + route_table_ids = [aws_route_table.test.id] + + tags = { + Name = %[1]q + } policy = < Date: Tue, 28 Jun 2022 11:52:08 -0400 Subject: [PATCH 051/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_rulesDropOnError'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_rulesDropOnError' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_rulesDropOnError -timeout 180m === RUN TestAccVPCSecurityGroup_rulesDropOnError === PAUSE TestAccVPCSecurityGroup_rulesDropOnError === CONT TestAccVPCSecurityGroup_rulesDropOnError --- PASS: TestAccVPCSecurityGroup_rulesDropOnError (39.98s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 44.538s --- .../service/ec2/vpc_security_group_test.go | 64 ++++++++++++------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index c24240114c4c..895c8d079e03 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -2260,7 +2260,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { var group ec2.SecurityGroup - + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -2271,19 +2271,19 @@ func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { Steps: []resource.TestStep{ // Create a valid security group with some rules and make sure it exists { - Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), ), }, // Add a bad rule to trigger API error { - Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule, - ExpectError: regexp.MustCompile("InvalidGroup.NotFound"), + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule(rName), + ExpectError: regexp.MustCompile("InvalidGroupId.Malformed"), }, // All originally added rules must survive. This will return non-empty plan if anything changed. { - Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit, + Config: testAccVPCSecurityGroupConfig_rulesDropOnErrorInit(rName), PlanOnly: true, }, }, @@ -4080,32 +4080,40 @@ resource "aws_security_group" "test" { `, rName) } -const testAccVPCSecurityGroupConfig_rulesDropOnErrorInit = ` +func testAccVPCSecurityGroupConfig_rulesDropOnErrorInit(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-drop-rules-test" + Name = %[1]q } } resource "aws_security_group" "test_ref0" { - name = "terraform_acceptance_test_drop_rules_ref0" + name = "%[1]s-ref0" vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test_ref1" { - name = "terraform_acceptance_test_drop_rules_ref1" + name = "%[1]s-ref1" vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_drop_rules" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.test.id + name = %[1]q + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test" + Name = %[1]q } ingress { @@ -4118,34 +4126,43 @@ resource "aws_security_group" "test" { ] } } -` +`, rName) +} -const testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule = ` +func testAccVPCSecurityGroupConfig_rulesDropOnErrorAddBadRule(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-drop-rules-test" + Name = %[1]q } } resource "aws_security_group" "test_ref0" { - name = "terraform_acceptance_test_drop_rules_ref0" + name = "%[1]s-ref0" vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test_ref1" { - name = "terraform_acceptance_test_drop_rules_ref1" + name = "%[1]s-ref1" vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_drop_rules" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.test.id + name = %[1]q + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test" + Name = %[1]q } ingress { @@ -4159,7 +4176,8 @@ resource "aws_security_group" "test" { ] } } -` +`, rName) +} func testAccVPCSecurityGroupConfig_egressModeBlocks(rName string) string { return fmt.Sprintf(` From b93e77d0e2c173d973308761a1fd31db64140342 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 14:30:31 -0400 Subject: [PATCH 052/120] r/aws_security_group: Tidy up 'TestAccVPCSecurityGroup_ruleLimit*'. Acceptance test output: % EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT=60 make testacc TESTARGS='-run=TestAccVPCSecurityGroup_ruleLimit' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroup_ruleLimit -timeout 180m === RUN TestAccVPCSecurityGroup_ruleLimitExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitExceededPrepend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededPrepend === RUN TestAccVPCSecurityGroup_ruleLimitExceededAllNew === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAllNew === CONT TestAccVPCSecurityGroup_ruleLimitExceededAppend === CONT TestAccVPCSecurityGroup_ruleLimitExceededPrepend === CONT TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === CONT TestAccVPCSecurityGroup_ruleLimitExceededAllNew --- PASS: TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend (40.21s) --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededAppend (49.41s) --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededAllNew (51.95s) --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededPrepend (52.56s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 57.300s --- .../service/ec2/vpc_security_group_test.go | 62 +++++++++---------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 895c8d079e03..36c1257cc706 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -2064,7 +2064,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup - + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -2075,7 +2075,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2084,7 +2084,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { }, // append a rule to step over the limit { - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2096,7 +2096,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAppend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2111,7 +2111,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup - + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -2122,7 +2122,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, 1), @@ -2130,7 +2130,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { }, // append a rule to step over the limit { - Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(rName, 0, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2158,7 +2158,7 @@ func TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, 1), @@ -2172,7 +2172,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup - + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -2183,7 +2183,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2191,7 +2191,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { }, // prepend a rule to step over the limit { - Config: testAccVPCSecurityGroupConfig_ruleLimit(1, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 1, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2203,7 +2203,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededPrepend(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2217,7 +2217,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { ruleLimit := testAccSecurityGroupRulesPerGroupLimitFromEnv() var group ec2.SecurityGroup - + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -2228,7 +2228,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { Steps: []resource.TestStep{ // create a valid SG just under the limit { - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2236,7 +2236,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { }, // add a rule to step over the limit with entirely new rules { - Config: testAccVPCSecurityGroupConfig_ruleLimit(100, ruleLimit+1), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 100, ruleLimit+1), ExpectError: regexp.MustCompile("RulesPerSecurityGroupLimitExceeded"), }, { @@ -2248,7 +2248,7 @@ func TestAccVPCSecurityGroup_ruleLimitExceededAllNew(t *testing.T) { } }, // running the original config again now should restore the rules - Config: testAccVPCSecurityGroupConfig_ruleLimit(0, ruleLimit), + Config: testAccVPCSecurityGroupConfig_ruleLimit(rName, 0, ruleLimit), Check: resource.ComposeTestCheckFunc( testAccCheckSecurityGroupExists(resourceName, &group), testAccCheckSecurityGroupRuleCount(&group, 0, ruleLimit), @@ -2637,7 +2637,7 @@ resource "aws_security_group" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } -func testAccVPCSecurityGroupConfig_ruleLimit(egressStartIndex, egressRulesCount int) string { +func testAccVPCSecurityGroupConfig_ruleLimit(rName string, egressStartIndex, egressRulesCount int) string { var egressRules strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { fmt.Fprintf(&egressRules, ` @@ -2655,26 +2655,25 @@ resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-limit" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_rule_limit" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.test.id + name = %[1]q + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test" + Name = %[1]q } # egress rules to exhaust the limit - %[1]s + %[2]s } -`, egressRules.String()) +`, rName, egressRules.String()) } -func testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(egressStartIndex, egressRulesCount int) string { +func testAccVPCSecurityGroupConfig_cidrBlockRuleLimit(rName string, egressStartIndex, egressRulesCount int) string { var cidrBlocks strings.Builder for i := egressStartIndex; i < egressRulesCount+egressStartIndex; i++ { fmt.Fprintf(&cidrBlocks, ` @@ -2687,17 +2686,16 @@ resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-limit" + Name = %[1]q } } resource "aws_security_group" "test" { - name = "terraform_acceptance_test_rule_limit" - description = "Used in the terraform acceptance tests" - vpc_id = aws_vpc.test.id + name = %[1]q + vpc_id = aws_vpc.test.id tags = { - Name = "tf-acc-test" + Name = %[1]q } egress { @@ -2706,11 +2704,11 @@ resource "aws_security_group" "test" { to_port = "80" # cidr_blocks to exhaust the limit cidr_blocks = [ - %s + %[2]s ] } } -`, cidrBlocks.String()) +`, rName, cidrBlocks.String()) } func testAccVPCSecurityGroupConfig_emptyRuleDescription(rName string) string { From 522edb1b08a9b9a67b77d75d20303f042fadee67 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 28 Jun 2022 15:05:52 -0400 Subject: [PATCH 053/120] Acceptance test output: % EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT=60 make testacc TESTARGS='-run=TestAccVPCSecurityGroup_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroup_ -timeout 180m === RUN TestAccVPCSecurityGroup_basic === PAUSE TestAccVPCSecurityGroup_basic === RUN TestAccVPCSecurityGroup_basicEC2Classic === PAUSE TestAccVPCSecurityGroup_basicEC2Classic === RUN TestAccVPCSecurityGroup_disappears === PAUSE TestAccVPCSecurityGroup_disappears === RUN TestAccVPCSecurityGroup_nameGenerated === PAUSE TestAccVPCSecurityGroup_nameGenerated === RUN TestAccVPCSecurityGroup_nameTerraformPrefix === PAUSE TestAccVPCSecurityGroup_nameTerraformPrefix === RUN TestAccVPCSecurityGroup_namePrefix === PAUSE TestAccVPCSecurityGroup_namePrefix === RUN TestAccVPCSecurityGroup_namePrefixTerraform === PAUSE TestAccVPCSecurityGroup_namePrefixTerraform === RUN TestAccVPCSecurityGroup_tags === PAUSE TestAccVPCSecurityGroup_tags === RUN TestAccVPCSecurityGroup_allowAll === PAUSE TestAccVPCSecurityGroup_allowAll === RUN TestAccVPCSecurityGroup_sourceSecurityGroup === PAUSE TestAccVPCSecurityGroup_sourceSecurityGroup === RUN TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules === PAUSE TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules === RUN TestAccVPCSecurityGroup_ipRangesWithSameRules === PAUSE TestAccVPCSecurityGroup_ipRangesWithSameRules === RUN TestAccVPCSecurityGroup_egressMode === PAUSE TestAccVPCSecurityGroup_egressMode === RUN TestAccVPCSecurityGroup_ingressMode === PAUSE TestAccVPCSecurityGroup_ingressMode === RUN TestAccVPCSecurityGroup_ruleGathering === PAUSE TestAccVPCSecurityGroup_ruleGathering === RUN TestAccVPCSecurityGroup_forceRevokeRulesTrue === PAUSE TestAccVPCSecurityGroup_forceRevokeRulesTrue === RUN TestAccVPCSecurityGroup_forceRevokeRulesFalse === PAUSE TestAccVPCSecurityGroup_forceRevokeRulesFalse === RUN TestAccVPCSecurityGroup_change === PAUSE TestAccVPCSecurityGroup_change === RUN TestAccVPCSecurityGroup_ipv6 === PAUSE TestAccVPCSecurityGroup_ipv6 === RUN TestAccVPCSecurityGroup_self === PAUSE TestAccVPCSecurityGroup_self === RUN TestAccVPCSecurityGroup_vpc === PAUSE TestAccVPCSecurityGroup_vpc === RUN TestAccVPCSecurityGroup_vpcNegOneIngress === PAUSE TestAccVPCSecurityGroup_vpcNegOneIngress === RUN TestAccVPCSecurityGroup_vpcProtoNumIngress === PAUSE TestAccVPCSecurityGroup_vpcProtoNumIngress === RUN TestAccVPCSecurityGroup_multiIngress === PAUSE TestAccVPCSecurityGroup_multiIngress === RUN TestAccVPCSecurityGroup_ruleDescription === PAUSE TestAccVPCSecurityGroup_ruleDescription === RUN TestAccVPCSecurityGroup_defaultEgressVPC === PAUSE TestAccVPCSecurityGroup_defaultEgressVPC === RUN TestAccVPCSecurityGroup_drift === PAUSE TestAccVPCSecurityGroup_drift === RUN TestAccVPCSecurityGroup_driftComplex === PAUSE TestAccVPCSecurityGroup_driftComplex === RUN TestAccVPCSecurityGroup_invalidCIDRBlock === PAUSE TestAccVPCSecurityGroup_invalidCIDRBlock === RUN TestAccVPCSecurityGroup_cidrAndGroups === PAUSE TestAccVPCSecurityGroup_cidrAndGroups === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === RUN TestAccVPCSecurityGroup_egressWithPrefixList === PAUSE TestAccVPCSecurityGroup_egressWithPrefixList === RUN TestAccVPCSecurityGroup_ingressWithPrefixList === PAUSE TestAccVPCSecurityGroup_ingressWithPrefixList === RUN TestAccVPCSecurityGroup_ipv4AndIPv6Egress === PAUSE TestAccVPCSecurityGroup_ipv4AndIPv6Egress === RUN TestAccVPCSecurityGroup_failWithDiffMismatch === PAUSE TestAccVPCSecurityGroup_failWithDiffMismatch === RUN TestAccVPCSecurityGroup_ruleLimitExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitExceededPrepend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededPrepend === RUN TestAccVPCSecurityGroup_ruleLimitExceededAllNew === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAllNew === RUN TestAccVPCSecurityGroup_rulesDropOnError === PAUSE TestAccVPCSecurityGroup_rulesDropOnError === CONT TestAccVPCSecurityGroup_basic === CONT TestAccVPCSecurityGroup_vpcNegOneIngress === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic (23.70s) === CONT TestAccVPCSecurityGroup_rulesDropOnError --- PASS: TestAccVPCSecurityGroup_vpcNegOneIngress (29.28s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededAllNew --- PASS: TestAccVPCSecurityGroup_basic (29.66s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededPrepend --- PASS: TestAccVPCSecurityGroup_rulesDropOnError (48.53s) === CONT TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededAllNew (66.85s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededAppend --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededPrepend (69.97s) === CONT TestAccVPCSecurityGroup_failWithDiffMismatch --- PASS: TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend (47.83s) === CONT TestAccVPCSecurityGroup_ipv4AndIPv6Egress --- PASS: TestAccVPCSecurityGroup_failWithDiffMismatch (29.36s) === CONT TestAccVPCSecurityGroup_drift --- PASS: TestAccVPCSecurityGroup_drift (22.95s) === CONT TestAccVPCSecurityGroup_ingressWithPrefixList --- PASS: TestAccVPCSecurityGroup_ipv4AndIPv6Egress (38.44s) === CONT TestAccVPCSecurityGroup_egressWithPrefixList --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededAppend (63.62s) === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC (32.06s) === CONT TestAccVPCSecurityGroup_driftComplex --- PASS: TestAccVPCSecurityGroup_ingressWithPrefixList (42.99s) === CONT TestAccVPCSecurityGroup_ruleDescription --- PASS: TestAccVPCSecurityGroup_egressWithPrefixList (41.05s) === CONT TestAccVPCSecurityGroup_defaultEgressVPC --- PASS: TestAccVPCSecurityGroup_driftComplex (30.62s) === CONT TestAccVPCSecurityGroup_cidrAndGroups --- PASS: TestAccVPCSecurityGroup_defaultEgressVPC (27.23s) === CONT TestAccVPCSecurityGroup_multiIngress --- PASS: TestAccVPCSecurityGroup_cidrAndGroups (33.42s) === CONT TestAccVPCSecurityGroup_vpcProtoNumIngress --- PASS: TestAccVPCSecurityGroup_multiIngress (34.19s) === CONT TestAccVPCSecurityGroup_ipRangesWithSameRules --- PASS: TestAccVPCSecurityGroup_ruleDescription (68.35s) === CONT TestAccVPCSecurityGroup_vpc --- PASS: TestAccVPCSecurityGroup_vpcProtoNumIngress (29.04s) === CONT TestAccVPCSecurityGroup_self --- PASS: TestAccVPCSecurityGroup_ipRangesWithSameRules (30.11s) === CONT TestAccVPCSecurityGroup_ipv6 --- PASS: TestAccVPCSecurityGroup_vpc (29.23s) === CONT TestAccVPCSecurityGroup_change --- PASS: TestAccVPCSecurityGroup_self (29.61s) === CONT TestAccVPCSecurityGroup_forceRevokeRulesFalse --- PASS: TestAccVPCSecurityGroup_ipv6 (29.37s) === CONT TestAccVPCSecurityGroup_forceRevokeRulesTrue --- PASS: TestAccVPCSecurityGroup_change (47.74s) === CONT TestAccVPCSecurityGroup_ruleGathering --- PASS: TestAccVPCSecurityGroup_ruleGathering (42.07s) === CONT TestAccVPCSecurityGroup_ingressMode --- PASS: TestAccVPCSecurityGroup_ingressMode (57.67s) === CONT TestAccVPCSecurityGroup_egressMode --- PASS: TestAccVPCSecurityGroup_egressMode (56.54s) === CONT TestAccVPCSecurityGroup_namePrefixTerraform --- PASS: TestAccVPCSecurityGroup_namePrefixTerraform (25.16s) === CONT TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules --- PASS: TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules (31.41s) === CONT TestAccVPCSecurityGroup_sourceSecurityGroup --- PASS: TestAccVPCSecurityGroup_sourceSecurityGroup (28.62s) === CONT TestAccVPCSecurityGroup_allowAll --- PASS: TestAccVPCSecurityGroup_allowAll (29.43s) === CONT TestAccVPCSecurityGroup_tags --- PASS: TestAccVPCSecurityGroup_tags (58.22s) === CONT TestAccVPCSecurityGroup_nameGenerated --- PASS: TestAccVPCSecurityGroup_nameGenerated (28.04s) === CONT TestAccVPCSecurityGroup_namePrefix --- PASS: TestAccVPCSecurityGroup_namePrefix (28.19s) === CONT TestAccVPCSecurityGroup_nameTerraformPrefix --- PASS: TestAccVPCSecurityGroup_nameTerraformPrefix (31.00s) === CONT TestAccVPCSecurityGroup_disappears --- PASS: TestAccVPCSecurityGroup_disappears (29.22s) === CONT TestAccVPCSecurityGroup_basicEC2Classic --- PASS: TestAccVPCSecurityGroup_basicEC2Classic (34.04s) === CONT TestAccVPCSecurityGroup_invalidCIDRBlock --- PASS: TestAccVPCSecurityGroup_invalidCIDRBlock (5.99s) --- PASS: TestAccVPCSecurityGroup_forceRevokeRulesFalse (968.32s) --- PASS: TestAccVPCSecurityGroup_forceRevokeRulesTrue (999.43s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 1327.722s From d4c8e4b00a38603bb48262854fb8884cc1aaf15b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 09:08:47 -0400 Subject: [PATCH 054/120] d/aws_security_group: Tidy up. --- .../ec2/vpc_security_group_data_source.go | 71 +++++++++---------- 1 file changed, 32 insertions(+), 39 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_data_source.go b/internal/service/ec2/vpc_security_group_data_source.go index d61b68e9778c..7fe5d86c1edc 100644 --- a/internal/service/ec2/vpc_security_group_data_source.go +++ b/internal/service/ec2/vpc_security_group_data_source.go @@ -1,7 +1,6 @@ package ec2 import ( - "errors" "fmt" "github.com/aws/aws-sdk-go/aws" @@ -18,33 +17,29 @@ func DataSourceSecurityGroup() *schema.Resource { Read: dataSourceSecurityGroupRead, Schema: map[string]*schema.Schema{ - "vpc_id": { + "arn": { Type: schema.TypeString, - Optional: true, Computed: true, }, - "name": { + "description": { Type: schema.TypeString, - Optional: true, Computed: true, }, "filter": CustomFiltersSchema(), - "id": { Type: schema.TypeString, Optional: true, Computed: true, }, - - "arn": { + "name": { Type: schema.TypeString, + Optional: true, Computed: true, }, - "tags": tftags.TagsSchemaComputed(), - - "description": { + "vpc_id": { Type: schema.TypeString, + Optional: true, Computed: true, }, }, @@ -55,48 +50,39 @@ func dataSourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error conn := meta.(*conns.AWSClient).EC2Conn ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - req := &ec2.DescribeSecurityGroupsInput{} + input := &ec2.DescribeSecurityGroupsInput{ + Filters: BuildAttributeFilterList( + map[string]string{ + "group-name": d.Get("name").(string), + "vpc-id": d.Get("vpc_id").(string), + }, + ), + } - if id, ok := d.GetOk("id"); ok { - req.GroupIds = []*string{aws.String(id.(string))} + if v, ok := d.GetOk("id"); ok { + input.GroupIds = aws.StringSlice([]string{v.(string)}) } - req.Filters = BuildAttributeFilterList( - map[string]string{ - "group-name": d.Get("name").(string), - "vpc-id": d.Get("vpc_id").(string), - }, - ) - req.Filters = append(req.Filters, BuildTagFilterList( + input.Filters = append(input.Filters, BuildTagFilterList( Tags(tftags.New(d.Get("tags").(map[string]interface{}))), )...) - req.Filters = append(req.Filters, BuildCustomFilterList( + + input.Filters = append(input.Filters, BuildCustomFilterList( d.Get("filter").(*schema.Set), )...) - if len(req.Filters) == 0 { + + if len(input.Filters) == 0 { // Don't send an empty filters list; the EC2 API won't accept it. - req.Filters = nil + input.Filters = nil } - sg, err := FindSecurityGroup(conn, req) - if errors.Is(err, tfresource.ErrEmptyResult) { - return fmt.Errorf("no matching SecurityGroup found") - } - if errors.Is(err, tfresource.ErrTooManyResults) { - return fmt.Errorf("multiple Security Groups matched; use additional constraints to reduce matches to a single Security Group") - } + sg, err := FindSecurityGroup(conn, input) + if err != nil { - return err + return tfresource.SingularDataSourceFindError("EC2 Security Group", err) } d.SetId(aws.StringValue(sg.GroupId)) - d.Set("name", sg.GroupName) - d.Set("description", sg.Description) - d.Set("vpc_id", sg.VpcId) - - if err := d.Set("tags", KeyValueTags(sg.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) - } arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, @@ -106,6 +92,13 @@ func dataSourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error Resource: fmt.Sprintf("security-group/%s", *sg.GroupId), }.String() d.Set("arn", arn) + d.Set("description", sg.Description) + d.Set("name", sg.GroupName) + d.Set("vpc_id", sg.VpcId) + + if err := d.Set("tags", KeyValueTags(sg.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("setting tags: %w", err) + } return nil } From 943a797e71b03f7dbeab48e6f65ce9249f49b716 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 09:18:10 -0400 Subject: [PATCH 055/120] d/aws_security_group: Tidy up 'TestAccVPCSecurityGroupDataSource_basic*'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupDataSource_basic' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupDataSource_basic -timeout 180m === RUN TestAccVPCSecurityGroupDataSource_basic === PAUSE TestAccVPCSecurityGroupDataSource_basic === CONT TestAccVPCSecurityGroupDataSource_basic --- PASS: TestAccVPCSecurityGroupDataSource_basic (25.50s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 32.511s --- .../vpc_security_group_data_source_test.go | 107 ++++-------------- 1 file changed, 19 insertions(+), 88 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_data_source_test.go b/internal/service/ec2/vpc_security_group_data_source_test.go index 7b239a54a1a2..06563a28acf6 100644 --- a/internal/service/ec2/vpc_security_group_data_source_test.go +++ b/internal/service/ec2/vpc_security_group_data_source_test.go @@ -2,128 +2,64 @@ package ec2_test import ( "fmt" - "strings" "testing" "github.com/aws/aws-sdk-go/service/ec2" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" ) func TestAccVPCSecurityGroupDataSource_basic(t *testing.T) { - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupDataSourceConfig_basic(rInt), - Check: resource.ComposeTestCheckFunc( + Config: testAccVPCSecurityGroupDataSourceConfig_basic(rName), + Check: resource.ComposeAggregateTestCheckFunc( testAccSecurityGroupCheckDataSource("data.aws_security_group.by_id"), - resource.TestCheckResourceAttr("data.aws_security_group.by_id", "description", "sg description"), testAccSecurityGroupCheckDataSource("data.aws_security_group.by_tag"), testAccSecurityGroupCheckDataSource("data.aws_security_group.by_filter"), testAccSecurityGroupCheckDataSource("data.aws_security_group.by_name"), - testAccSecurityGroupCheckDefaultDataSource("data.aws_security_group.default_by_name"), ), }, }, }) } -func testAccSecurityGroupCheckDataSource(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("root module has no resource called %s", name) - } - - SGRs, ok := s.RootModule().Resources["aws_security_group.test"] - if !ok { - return fmt.Errorf("can't find aws_security_group.test in state") - } - vpcRs, ok := s.RootModule().Resources["aws_vpc.test"] - if !ok { - return fmt.Errorf("can't find aws_vpc.test in state") - } - attr := rs.Primary.Attributes - - if attr["id"] != SGRs.Primary.Attributes["id"] { - return fmt.Errorf( - "id is %s; want %s", - attr["id"], - SGRs.Primary.Attributes["id"], - ) - } - - if attr["vpc_id"] != vpcRs.Primary.Attributes["id"] { - return fmt.Errorf( - "vpc_id is %s; want %s", - attr["vpc_id"], - vpcRs.Primary.Attributes["id"], - ) - } +func testAccSecurityGroupCheckDataSource(dataSourceName string) resource.TestCheckFunc { + resourceName := "aws_security_group.test" - if attr["tags.Name"] != "tf-acctest" { - return fmt.Errorf("bad Name tag %s", attr["tags.Name"]) - } - - if !strings.Contains(attr["arn"], attr["id"]) { - return fmt.Errorf("bad ARN %s", attr["arn"]) - } - - return nil - } + return resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "description", resourceName, "description"), + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(dataSourceName, "vpc_id", resourceName, "vpc_id"), + ) } -func testAccSecurityGroupCheckDefaultDataSource(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("root module has no resource called %s", name) - } - - vpcRs, ok := s.RootModule().Resources["aws_vpc.test"] - if !ok { - return fmt.Errorf("can't find aws_vpc.test in state") - } - attr := rs.Primary.Attributes - - if attr["id"] != vpcRs.Primary.Attributes["default_security_group_id"] { - return fmt.Errorf( - "id is %s; want %s", - attr["id"], - vpcRs.Primary.Attributes["default_security_group_id"], - ) - } - - return nil - } -} - -func testAccVPCSecurityGroupDataSourceConfig_basic(rInt int) string { +func testAccVPCSecurityGroupDataSourceConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" tags = { - Name = "terraform-testacc-security-group-data-source" + Name = %[1]q } } resource "aws_security_group" "test" { vpc_id = aws_vpc.test.id - name = "test-%d" + name = %[1]q tags = { - Name = "tf-acctest" - Seed = "%d" + Name = %[1]q } - - description = "sg description" } data "aws_security_group" "by_id" { @@ -134,14 +70,9 @@ data "aws_security_group" "by_name" { name = aws_security_group.test.name } -data "aws_security_group" "default_by_name" { - vpc_id = aws_vpc.test.id - name = "default" -} - data "aws_security_group" "by_tag" { tags = { - Seed = aws_security_group.test.tags["Seed"] + Name = aws_security_group.test.tags["Name"] } } @@ -151,5 +82,5 @@ data "aws_security_group" "by_filter" { values = [aws_security_group.test.name] } } -`, rInt, rInt) +`, rName) } From 824ff81845110f768daa391d3c4699d52bd3d286 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 09:27:04 -0400 Subject: [PATCH 056/120] 'testAccCheckSecurityGroupRuleExists' -> 'testAccCheckSecurityGroupExists' and 'testAccCheckSecurityGroupRuleDestroy' -> 'testAccCheckSecurityGroupDestroy'. --- .../ec2/vpc_security_group_rule_test.go | 159 ++++++------------ .../service/ec2/vpc_security_group_test.go | 4 +- 2 files changed, 58 insertions(+), 105 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 939286c4faa6..cea9f6bd9352 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func TestIPPermissionIDHash(t *testing.T) { @@ -136,12 +135,12 @@ func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingress(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), resource.TestCheckResourceAttr( "aws_security_group_rule.ingress_1", "from_port", "80"), @@ -169,12 +168,12 @@ func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), resource.TestCheckResourceAttrPair( ruleName, "security_group_id", "aws_security_group.web", "id"), resource.TestMatchResourceAttr( @@ -215,12 +214,12 @@ func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressProtocol, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), resource.TestCheckResourceAttr( "aws_security_group_rule.ingress_1", "from_port", "80"), @@ -246,12 +245,12 @@ func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressIcmpv6, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists(sgResourceName, &group), + testAccCheckSecurityGroupExists(sgResourceName, &group), resource.TestCheckResourceAttr(resourceName, "from_port", "-1"), resource.TestCheckResourceAttr(resourceName, "to_port", "-1"), resource.TestCheckResourceAttr(resourceName, "protocol", "icmpv6"), @@ -298,12 +297,12 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressIPv6, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testRuleCount, ), }, @@ -340,12 +339,12 @@ func TestAccVPCSecurityGroupRule_Ingress_classic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressClassic(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), resource.TestCheckResourceAttr( "aws_security_group_rule.ingress_1", "from_port", "80"), @@ -390,12 +389,12 @@ func TestAccVPCSecurityGroupRule_multiIngress(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_multiIngress, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testMultiRuleCount, ), }, @@ -417,12 +416,12 @@ func TestAccVPCSecurityGroupRule_egress(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_egress(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), ), }, @@ -443,12 +442,12 @@ func TestAccVPCSecurityGroupRule_selfReference(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_selfReference, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), ), }, { @@ -467,7 +466,7 @@ func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_expectInvalidType(rInt), @@ -483,7 +482,7 @@ func TestAccVPCSecurityGroupRule_expectInvalidCIDR(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rInt), @@ -526,12 +525,12 @@ func TestAccVPCSecurityGroupRule_PartialMatching_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_partialMatching(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress", &group, &p, "ingress"), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.other", &group, &o, "ingress"), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.nat_ingress", &group, &o, "ingress"), @@ -589,13 +588,13 @@ func TestAccVPCSecurityGroupRule_PartialMatching_source(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleExists("aws_security_group.nat", &nat), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.nat", &nat), setupSG, testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.source_ingress", &group, &p, "ingress"), ), @@ -617,12 +616,12 @@ func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_issue5310, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.issue_5310", &group), + testAccCheckSecurityGroupExists("aws_security_group.issue_5310", &group), ), }, { @@ -642,12 +641,12 @@ func TestAccVPCSecurityGroupRule_race(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_race, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.race", &group), + testAccCheckSecurityGroupExists("aws_security_group.race", &group), ), }, }, @@ -662,12 +661,12 @@ func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_selfInSource(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), ), }, { @@ -720,12 +719,12 @@ func TestAccVPCSecurityGroupRule_prefixListEgress(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_prefixListEgress, Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.egress", &group), + testAccCheckSecurityGroupExists("aws_security_group.egress", &group), // lookup info on the VPC Endpoint created, to populate the expected // IP Perm testAccCheckVPCEndpointExists("aws_vpc_endpoint.s3_endpoint", &endpoint), @@ -751,12 +750,12 @@ func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), resource.TestCheckResourceAttr("aws_security_group_rule.ingress_1", "description", "TF acceptance test ingress rule"), ), @@ -779,12 +778,12 @@ func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), resource.TestCheckResourceAttr("aws_security_group_rule.egress_1", "description", "TF acceptance test egress rule"), ), @@ -807,12 +806,12 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), resource.TestCheckResourceAttr("aws_security_group_rule.ingress_1", "description", "TF acceptance test ingress rule"), ), @@ -821,7 +820,7 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { { Config: testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), resource.TestCheckResourceAttr("aws_security_group_rule.ingress_1", "description", "TF acceptance test ingress rule updated"), ), @@ -844,12 +843,12 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), resource.TestCheckResourceAttr("aws_security_group_rule.egress_1", "description", "TF acceptance test egress rule"), ), @@ -858,7 +857,7 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { { Config: testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.web", &group), + testAccCheckSecurityGroupExists("aws_security_group.web", &group), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), resource.TestCheckResourceAttr("aws_security_group_rule.egress_1", "description", "TF acceptance test egress rule updated"), ), @@ -897,12 +896,12 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, "description1"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), + testAccCheckSecurityGroupExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule1, "ingress"), resource.TestCheckResourceAttr(resourceName, "description", "description1"), resource.TestCheckResourceAttr(resourceName, "from_port", "0"), @@ -919,7 +918,7 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, "description2"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), + testAccCheckSecurityGroupExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule2, "ingress"), resource.TestCheckResourceAttr(resourceName, "description", "description2"), resource.TestCheckResourceAttr(resourceName, "from_port", "0"), @@ -955,12 +954,12 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, "description1"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), + testAccCheckSecurityGroupExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule1, "ingress"), resource.TestCheckResourceAttr(resourceName, "description", "description1"), resource.TestCheckResourceAttr(resourceName, "from_port", "-1"), @@ -977,7 +976,7 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, "description2"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), + testAccCheckSecurityGroupExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule2, "ingress"), resource.TestCheckResourceAttr(resourceName, "description", "description2"), resource.TestCheckResourceAttr(resourceName, "from_port", "0"), @@ -1017,12 +1016,12 @@ func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testi PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_multipleSearchingAllProtocolCrash(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists(securityGroupResourceName, &group), + testAccCheckSecurityGroupExists(securityGroupResourceName, &group), testAccCheckSecurityGroupRuleAttributes(resourceName1, &group, &rule1, "ingress"), testAccCheckSecurityGroupRuleAttributes(resourceName2, &group, &rule2, "ingress"), resource.TestCheckResourceAttr(resourceName1, "from_port", "0"), @@ -1122,13 +1121,13 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupRuleDestroy, + CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_multidescription(rInt, "ingress"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.worker", &group), - testAccCheckSecurityGroupRuleExists("aws_security_group.nat", &nat), + testAccCheckSecurityGroupExists("aws_security_group.worker", &group), + testAccCheckSecurityGroupExists("aws_security_group.nat", &nat), testAccCheckVPCEndpointExists("aws_vpc_endpoint.s3_endpoint", &endpoint), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_1", &group, &rule1, "ingress"), @@ -1163,8 +1162,8 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { { Config: testAccVPCSecurityGroupRuleConfig_multidescription(rInt, "egress"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupRuleExists("aws_security_group.worker", &group), - testAccCheckSecurityGroupRuleExists("aws_security_group.nat", &nat), + testAccCheckSecurityGroupExists("aws_security_group.worker", &group), + testAccCheckSecurityGroupExists("aws_security_group.nat", &nat), testAccCheckVPCEndpointExists("aws_vpc_endpoint.s3_endpoint", &endpoint), testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_1", &group, &rule1, "egress"), @@ -1210,52 +1209,6 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { }) } -func testAccCheckSecurityGroupRuleDestroy(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_security_group" { - continue - } - - _, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - if tfresource.NotFound(err) { - continue - } - if err != nil { - return err - } - - return fmt.Errorf("Security Group (%s) still exists.", rs.Primary.ID) - } - - return nil -} - -func testAccCheckSecurityGroupRuleExists(n string, group *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group is set") - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - sg, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - if err != nil { - return err - } - - *group = *sg - - return nil - } -} - func testAccCheckSecurityGroupRuleAttributes(n string, group *ec2.SecurityGroup, p *ec2.IpPermission, ruleType string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 36c1257cc706..78e0f6025a1e 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -2405,7 +2405,7 @@ func testAccCheckSecurityGroupDestroy(s *terraform.State) error { return err } - return fmt.Errorf("Security Group (%s) still exists.", rs.Primary.ID) + return fmt.Errorf("VPC Security Group (%s) still exists.", rs.Primary.ID) } return nil @@ -2443,7 +2443,7 @@ func testAccCheckSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.Te } if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group ID is set") + return fmt.Errorf("No VPC Security Group ID is set") } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn From 33af63f3e91c2cf447a993f54127746281dfcda7 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 10:55:42 -0400 Subject: [PATCH 057/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_Ingress_vpc*'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_vpc' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_Ingress_vpc -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_vpc === PAUSE TestAccVPCSecurityGroupRule_Ingress_vpc === CONT TestAccVPCSecurityGroupRule_Ingress_vpc --- PASS: TestAccVPCSecurityGroupRule_Ingress_vpc (26.71s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 34.218s --- .../ec2/vpc_security_group_rule_test.go | 60 +++++++++---------- 1 file changed, 27 insertions(+), 33 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index cea9f6bd9352..a2501023e6cb 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -114,22 +114,9 @@ func TestIPPermissionIDHash(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() - - testRuleCount := func(*terraform.State) error { - if len(group.IpPermissions) != 1 { - return fmt.Errorf("Wrong Security Group rule count, expected %d, got %d", - 1, len(group.IpPermissions)) - } - - rule := group.IpPermissions[0] - if aws.Int64Value(rule.FromPort) != int64(80) { - return fmt.Errorf("Wrong Security Group port setting, expected %d, got %d", - 80, aws.Int64Value(rule.FromPort)) - } - - return nil - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -138,19 +125,27 @@ func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingress(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), - resource.TestCheckResourceAttr( - "aws_security_group_rule.ingress_1", "from_port", "80"), - testRuleCount, + Config: testAccVPCSecurityGroupRuleConfig_ingress(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.ingress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1394,27 +1389,26 @@ func testAccSecurityGroupRuleImportGetAttrs(attrs map[string]string, key string) return &values, nil } -func testAccVPCSecurityGroupRuleConfig_ingress(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingress(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress_1" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "tcp" from_port = 80 to_port = 8000 cidr_blocks = ["10.0.0.0/8"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } const testAccVPCSecurityGroupRuleConfig_ingressIcmpv6 = ` From 169924c00d5cd08ea13d3f06374850aae47022f4 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 11:03:24 -0400 Subject: [PATCH 058/120] r/aws_security_group_rule: Alphabetize attributes. --- .../service/ec2/vpc_security_group_rule.go | 105 ++++++++---------- 1 file changed, 48 insertions(+), 57 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 1d114b450423..f8b54392342b 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -28,6 +28,7 @@ func ResourceSecurityGroupRule() *schema.Resource { Read: resourceSecurityGroupRuleRead, Update: resourceSecurityGroupRuleUpdate, Delete: resourceSecurityGroupRuleDelete, + Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { importParts, err := validateSecurityGroupRuleImportString(d.Id()) @@ -45,32 +46,22 @@ func ResourceSecurityGroupRule() *schema.Resource { MigrateState: SecurityGroupRuleMigrateState, Schema: map[string]*schema.Schema{ - "type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - Description: "Type of rule, ingress (inbound) or egress (outbound).", - ValidateFunc: validation.StringInSlice([]string{ - "ingress", - "egress", - }, false), - }, - - "from_port": { - Type: schema.TypeInt, - Required: true, + "cidr_blocks": { + Type: schema.TypeList, + Optional: true, ForceNew: true, - // Support existing configurations that have non-zero from_port and to_port defined with all protocols - DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { - protocol := ProtocolForValue(d.Get("protocol").(string)) - if protocol == "-1" && old == "0" { - return true - } - return false + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidCIDRNetworkAddress, }, + ConflictsWith: []string{"source_security_group_id", "self"}, }, - - "to_port": { + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validSecurityGroupRuleDescription, + }, + "from_port": { Type: schema.TypeInt, Required: true, ForceNew: true, @@ -83,25 +74,6 @@ func ResourceSecurityGroupRule() *schema.Resource { return false }, }, - - "protocol": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: ProtocolStateFunc, - }, - - "cidr_blocks": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - ConflictsWith: []string{"source_security_group_id", "self"}, - }, - "ipv6_cidr_blocks": { Type: schema.TypeList, Optional: true, @@ -112,20 +84,30 @@ func ResourceSecurityGroupRule() *schema.Resource { }, ConflictsWith: []string{"source_security_group_id", "self"}, }, - "prefix_list_ids": { Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - + "protocol": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: ProtocolStateFunc, + }, "security_group_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, - + "self": { + Type: schema.TypeBool, + Optional: true, + Default: false, + ForceNew: true, + ConflictsWith: []string{"cidr_blocks", "ipv6_cidr_blocks", "source_security_group_id"}, + }, "source_security_group_id": { Type: schema.TypeString, Optional: true, @@ -133,19 +115,28 @@ func ResourceSecurityGroupRule() *schema.Resource { Computed: true, ConflictsWith: []string{"cidr_blocks", "ipv6_cidr_blocks", "self"}, }, - - "self": { - Type: schema.TypeBool, - Optional: true, - Default: false, - ForceNew: true, - ConflictsWith: []string{"cidr_blocks", "ipv6_cidr_blocks", "source_security_group_id"}, + "to_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + // Support existing configurations that have non-zero from_port and to_port defined with all protocols + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + protocol := ProtocolForValue(d.Get("protocol").(string)) + if protocol == "-1" && old == "0" { + return true + } + return false + }, }, - - "description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validSecurityGroupRuleDescription, + "type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Type of rule, ingress (inbound) or egress (outbound).", + ValidateFunc: validation.StringInSlice([]string{ + "ingress", + "egress", + }, false), }, }, } From 445dc844dd24a9a225ac8989f2bfc605b363c723 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 11:09:23 -0400 Subject: [PATCH 059/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id -timeout 180m === RUN TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === PAUSE TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === CONT TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id --- PASS: TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id (23.83s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.138s --- .../ec2/vpc_security_group_rule_test.go | 61 ++++++++++--------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index a2501023e6cb..2b47b62ac932 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -154,10 +154,9 @@ func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { var group ec2.SecurityGroup - - rInt := sdkacctest.RandInt() - - ruleName := "aws_security_group_rule.allow_self" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -166,21 +165,20 @@ func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - resource.TestCheckResourceAttrPair( - ruleName, "security_group_id", "aws_security_group.web", "id"), - resource.TestMatchResourceAttr( - ruleName, "source_security_group_id", regexp.MustCompile("^[0-9]{12}/sg-[0-9a-z]{17}$")), - resource.TestCheckResourceAttr( - ruleName, "description", "some description"), - resource.TestCheckResourceAttr( - ruleName, "from_port", "0"), - resource.TestCheckResourceAttr( - ruleName, "to_port", "0"), - resource.TestCheckResourceAttr( - ruleName, "protocol", "-1"), + Config: testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "description", "some description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestMatchResourceAttr(resourceName, "source_security_group_id", regexp.MustCompile("^[0-9]{12}/sg-[0-9a-z]{17}$")), + resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, }, @@ -2092,34 +2090,37 @@ resource "aws_security_group_rule" "allow_self" { `, rInt) } -func testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rName string) string { return fmt.Sprintf(` data "aws_caller_identity" "current" {} -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-self-ingress" + Name = %[1]q } } -resource "aws_security_group" "web" { - name = "allow_all-%d" - description = "Allow all inbound traffic" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "allow_self" { +resource "aws_security_group_rule" "test" { type = "ingress" from_port = 0 to_port = 0 protocol = "-1" description = "some description" - security_group_id = aws_security_group.web.id - source_security_group_id = "${data.aws_caller_identity.current.account_id}/${aws_security_group.web.id}" + security_group_id = aws_security_group.test.id + source_security_group_id = "${data.aws_caller_identity.current.account_id}/${aws_security_group.test.id}" } -`, rInt) +`, rName) } func testAccVPCSecurityGroupRuleConfig_expectInvalidType(rInt int) string { From b5d25d2038dbc15e94dd3f6cb51fc0e6998c2c92 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 15:42:04 -0400 Subject: [PATCH 060/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_Ingress_protocol'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_protocol' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_Ingress_protocol -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_protocol === PAUSE TestAccVPCSecurityGroupRule_Ingress_protocol === CONT TestAccVPCSecurityGroupRule_Ingress_protocol --- PASS: TestAccVPCSecurityGroupRule_Ingress_protocol (23.90s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.072s --- .../ec2/vpc_security_group_rule_test.go | 63 +++++++++---------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 2b47b62ac932..32f768ed1e64 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -187,21 +187,9 @@ func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { var group ec2.SecurityGroup - - testRuleCount := func(*terraform.State) error { - if len(group.IpPermissions) != 1 { - return fmt.Errorf("Wrong Security Group rule count, expected %d, got %d", - 1, len(group.IpPermissions)) - } - - rule := group.IpPermissions[0] - if *rule.FromPort != int64(80) { - return fmt.Errorf("Wrong Security Group port setting, expected %d, got %d", - 80, aws.Int64Value(rule.FromPort)) - } - - return nil - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -210,19 +198,27 @@ func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressProtocol, + Config: testAccVPCSecurityGroupRuleConfig_ingressProtocol(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), - resource.TestCheckResourceAttr( - "aws_security_group_rule.ingress_1", "from_port", "80"), - testRuleCount, + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.ingress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1456,33 +1452,36 @@ resource "aws_security_group_rule" "ingress_1" { } ` -const testAccVPCSecurityGroupRuleConfig_ingressProtocol = ` -resource "aws_vpc" "tftest" { +func testAccVPCSecurityGroupRuleConfig_ingressProtocol(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-ingress-protocol" + Name = %[1]q } } -resource "aws_security_group" "web" { - vpc_id = aws_vpc.tftest.id +resource "aws_security_group" "test" { + vpc_id = aws_vpc.test.id + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress_1" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "6" from_port = 80 to_port = 8000 cidr_blocks = ["10.0.0.0/8"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id +} +`, rName) } -` const testAccVPCSecurityGroupRuleConfig_issue5310 = ` resource "aws_security_group" "issue_5310" { From a009a99230264730c7dd368a8c0718ad2c52c6c6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 15:47:45 -0400 Subject: [PATCH 061/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_Ingress_icmpv6'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_icmpv6' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_Ingress_icmpv6 -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_icmpv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_icmpv6 === CONT TestAccVPCSecurityGroupRule_Ingress_icmpv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_icmpv6 (22.95s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 26.977s --- .../ec2/vpc_security_group_rule_test.go | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 32f768ed1e64..2dc391d41d81 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -199,7 +199,7 @@ func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_ingressProtocol(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(sgResourceName, &group), resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), @@ -227,6 +227,7 @@ func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -237,15 +238,21 @@ func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressIcmpv6, - Check: resource.ComposeTestCheckFunc( + Config: testAccVPCSecurityGroupRuleConfig_ingressIcmpv6(rName), + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), resource.TestCheckResourceAttr(resourceName, "from_port", "-1"), - resource.TestCheckResourceAttr(resourceName, "to_port", "-1"), - resource.TestCheckResourceAttr(resourceName, "protocol", "icmpv6"), - resource.TestCheckResourceAttr(resourceName, "type", "ingress"), resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "1"), resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.0", "::/0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "icmpv6"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "-1"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { @@ -1405,13 +1412,23 @@ resource "aws_security_group_rule" "test" { `, rName) } -const testAccVPCSecurityGroupRuleConfig_ingressIcmpv6 = ` +func testAccVPCSecurityGroupRuleConfig_ingressIcmpv6(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } } resource "aws_security_group" "test" { vpc_id = aws_vpc.test.id + name = %[1]q + + tags = { + Name = %[1]q + } } resource "aws_security_group_rule" "test" { @@ -1422,7 +1439,8 @@ resource "aws_security_group_rule" "test" { protocol = "icmpv6" ipv6_cidr_blocks = ["::/0"] } -` +`, rName) +} const testAccVPCSecurityGroupRuleConfig_ingressIPv6 = ` resource "aws_vpc" "tftest" { From 84e7255b095cf43d116a650edb322dbf8b5af4e2 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 15:59:29 -0400 Subject: [PATCH 062/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_Ingress_ipv6'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_ipv6' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_Ingress_ipv6 -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_ipv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv6 === CONT TestAccVPCSecurityGroupRule_Ingress_ipv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv6 (22.16s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 26.140s --- .../ec2/vpc_security_group_rule_test.go | 64 +++++++++---------- 1 file changed, 30 insertions(+), 34 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 2dc391d41d81..c85f597f32d4 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -267,27 +267,9 @@ func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { var group ec2.SecurityGroup - - testRuleCount := func(*terraform.State) error { - if len(group.IpPermissions) != 1 { - return fmt.Errorf("Wrong Security Group rule count, expected %d, got %d", - 1, len(group.IpPermissions)) - } - - rule := group.IpPermissions[0] - if *rule.FromPort != int64(80) { - return fmt.Errorf("Wrong Security Group port setting, expected %d, got %d", - 80, aws.Int64Value(rule.FromPort)) - } - - ipv6Address := rule.Ipv6Ranges[0] - if *ipv6Address.CidrIpv6 != "::/0" { - return fmt.Errorf("Wrong Security Group IPv6 address, expected %s, got %s", - "::/0", *ipv6Address.CidrIpv6) - } - - return nil - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -296,16 +278,27 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressIPv6, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testRuleCount, + Config: testAccVPCSecurityGroupRuleConfig_ingressIPv6(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.0", "::/0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.ingress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1442,33 +1435,36 @@ resource "aws_security_group_rule" "test" { `, rName) } -const testAccVPCSecurityGroupRuleConfig_ingressIPv6 = ` +func testAccVPCSecurityGroupRuleConfig_ingressIPv6(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "tftest" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-ingress-ipv6" + Name = %[1]q } } -resource "aws_security_group" "web" { +resource "aws_security_group" "test" { vpc_id = aws_vpc.tftest.id + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress_1" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "6" from_port = 80 to_port = 8000 ipv6_cidr_blocks = ["::/0"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id +} +`, rName) } -` func testAccVPCSecurityGroupRuleConfig_ingressProtocol(rName string) string { return fmt.Sprintf(` From 76a2395650644f8f4c4020372fd60b0e98d18e3f Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:09:04 -0400 Subject: [PATCH 063/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_Ingress_classic'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_classic' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_Ingress_classic -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_classic === PAUSE TestAccVPCSecurityGroupRule_Ingress_classic === CONT TestAccVPCSecurityGroupRule_Ingress_classic --- PASS: TestAccVPCSecurityGroupRule_Ingress_classic (13.16s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 17.176s --- .../ec2/vpc_security_group_rule_test.go | 64 +++++++++---------- 1 file changed, 29 insertions(+), 35 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index c85f597f32d4..9d8d6ffe2238 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -307,43 +307,38 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_classic(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() - - testRuleCount := func(*terraform.State) error { - if len(group.IpPermissions) != 1 { - return fmt.Errorf("Wrong Security Group rule count, expected %d, got %d", - 1, len(group.IpPermissions)) - } - - rule := group.IpPermissions[0] - if *rule.FromPort != int64(80) { - return fmt.Errorf("Wrong Security Group port setting, expected %d, got %d", - 80, aws.Int64Value(rule.FromPort)) - } - - return nil - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressClassic(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), - resource.TestCheckResourceAttr( - "aws_security_group_rule.ingress_1", "from_port", "80"), - testRuleCount, + Config: testAccVPCSecurityGroupRuleConfig_ingressClassic(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupEC2ClassicExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.ingress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1513,27 +1508,26 @@ resource "aws_security_group_rule" "issue_5310" { } ` -func testAccVPCSecurityGroupRuleConfig_ingressClassic(rInt int) string { - return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +func testAccVPCSecurityGroupRuleConfig_ingressClassic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress_1" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "tcp" from_port = 80 to_port = 8000 cidr_blocks = ["10.0.0.0/8"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName)) } func testAccVPCSecurityGroupRuleConfig_egress(rInt int) string { From 652f1c2a2ebcf025b85d19f62f16d4bf2fb246b0 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:24:17 -0400 Subject: [PATCH 064/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_egress'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_egress\|TestAccVPCSecurityGroupRule_EgressDescription_updates' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_egress\|TestAccVPCSecurityGroupRule_EgressDescription_updates -timeout 180m === RUN TestAccVPCSecurityGroupRule_egress === PAUSE TestAccVPCSecurityGroupRule_egress === RUN TestAccVPCSecurityGroupRule_egressDescription === PAUSE TestAccVPCSecurityGroupRule_egressDescription === RUN TestAccVPCSecurityGroupRule_EgressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_EgressDescription_updates === CONT TestAccVPCSecurityGroupRule_egress === CONT TestAccVPCSecurityGroupRule_EgressDescription_updates === CONT TestAccVPCSecurityGroupRule_egressDescription --- PASS: TestAccVPCSecurityGroupRule_egress (25.14s) --- PASS: TestAccVPCSecurityGroupRule_egressDescription (25.47s) --- PASS: TestAccVPCSecurityGroupRule_EgressDescription_updates (39.31s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 45.654s --- .../ec2/vpc_security_group_rule_test.go | 228 ++++++++---------- 1 file changed, 96 insertions(+), 132 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 9d8d6ffe2238..fe35ef1690cb 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -345,56 +345,11 @@ func TestAccVPCSecurityGroupRule_Ingress_classic(t *testing.T) { }) } -func TestAccVPCSecurityGroupRule_multiIngress(t *testing.T) { - var group ec2.SecurityGroup - - testMultiRuleCount := func(*terraform.State) error { - if len(group.IpPermissions) != 2 { - return fmt.Errorf("Wrong Security Group rule count, expected %d, got %d", - 2, len(group.IpPermissions)) - } - - var rule *ec2.IpPermission - for _, r := range group.IpPermissions { - if *r.FromPort == int64(80) { - rule = r - } - } - - if *rule.ToPort != int64(8000) { - return fmt.Errorf("Wrong Security Group port 2 setting, expected %d, got %d", - 8000, aws.Int64Value(rule.ToPort)) - } - - return nil - } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(t) }, - ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), - ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckSecurityGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccVPCSecurityGroupRuleConfig_multiIngress, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testMultiRuleCount, - ), - }, - { - ResourceName: "aws_security_group_rule.ingress_2", - ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_2"), - ImportStateVerify: true, - }, - }, - }) -} - func TestAccVPCSecurityGroupRule_egress(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -403,16 +358,27 @@ func TestAccVPCSecurityGroupRule_egress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_egress(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), + Config: testAccVPCSecurityGroupRuleConfig_egress(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "egress"), ), }, { - ResourceName: "aws_security_group_rule.egress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.egress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -756,7 +722,9 @@ func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -765,17 +733,27 @@ func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.egress_1", "description", "TF acceptance test egress rule"), + Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckResourceAttr(resourceName, "description", "TF acceptance test egress rule"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "egress"), ), }, { - ResourceName: "aws_security_group_rule.egress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.egress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -821,7 +799,9 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -830,26 +810,45 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.egress_1", "description", "TF acceptance test egress rule"), + Config: testAccVPCSecurityGroupRuleConfig_egressDescription(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckResourceAttr(resourceName, "description", "TF acceptance test egress rule"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "egress"), ), }, - { - Config: testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, nil, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.egress_1", "description", "TF acceptance test egress rule updated"), + Config: testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckResourceAttr(resourceName, "description", "TF acceptance test egress rule updated"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "egress"), ), }, { - ResourceName: "aws_security_group_rule.egress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.egress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1530,60 +1529,27 @@ resource "aws_security_group_rule" "test" { `, rName)) } -func testAccVPCSecurityGroupRuleConfig_egress(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_egress(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "egress_1" { +resource "aws_security_group_rule" "test" { type = "egress" protocol = "tcp" from_port = 80 to_port = 8000 cidr_blocks = ["10.0.0.0/8"] - security_group_id = aws_security_group.web.id -} -`, rInt) -} - -const testAccVPCSecurityGroupRuleConfig_multiIngress = ` -resource "aws_security_group" "web" { - name = "terraform_acceptance_test_example_2" - description = "Used in the terraform acceptance tests" -} - -resource "aws_security_group" "worker" { - name = "terraform_acceptance_test_example_worker" - description = "Used in the terraform acceptance tests" -} - -resource "aws_security_group_rule" "ingress_1" { - type = "ingress" - protocol = "tcp" - from_port = 22 - to_port = 22 - cidr_blocks = ["10.0.0.0/8"] - - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } - -resource "aws_security_group_rule" "ingress_2" { - type = "ingress" - protocol = "tcp" - from_port = 80 - to_port = 8000 - self = true - - security_group_id = aws_security_group.web.id +`, rName) } -` func testAccVPCSecurityGroupRuleConfig_multidescription(rInt int, rType string) string { var b bytes.Buffer @@ -1907,18 +1873,17 @@ resource "aws_security_group_rule" "ingress_1" { `, rInt) } -func testAccVPCSecurityGroupRuleConfig_egressDescription(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_egressDescription(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "egress_1" { +resource "aws_security_group_rule" "test" { type = "egress" protocol = "tcp" from_port = 80 @@ -1926,23 +1891,22 @@ resource "aws_security_group_rule" "egress_1" { cidr_blocks = ["10.0.0.0/8"] description = "TF acceptance test egress rule" - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } -func testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_egressUpdateDescription(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "egress_1" { +resource "aws_security_group_rule" "test" { type = "egress" protocol = "tcp" from_port = 80 @@ -1950,9 +1914,9 @@ resource "aws_security_group_rule" "egress_1" { cidr_blocks = ["10.0.0.0/8"] description = "TF acceptance test egress rule updated" - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } func testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, description string) string { From 863087243ab9bafbfcb0e888eab860a7e4e1cc55 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:30:56 -0400 Subject: [PATCH 065/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_selfReference'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_selfReference' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_selfReference -timeout 180m === RUN TestAccVPCSecurityGroupRule_selfReference === PAUSE TestAccVPCSecurityGroupRule_selfReference === CONT TestAccVPCSecurityGroupRule_selfReference --- PASS: TestAccVPCSecurityGroupRule_selfReference (24.18s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 28.370s --- .../ec2/vpc_security_group_rule_test.go | 46 +++++++++++++------ 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index fe35ef1690cb..ebfd92242157 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -387,6 +387,9 @@ func TestAccVPCSecurityGroupRule_egress(t *testing.T) { func TestAccVPCSecurityGroupRule_selfReference(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -395,15 +398,26 @@ func TestAccVPCSecurityGroupRule_selfReference(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_selfReference, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), + Config: testAccVPCSecurityGroupRuleConfig_selfReference(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "true"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.self", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.self"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1634,33 +1648,35 @@ resource "aws_security_group_rule" "rule_4" { } // check for GH-1985 regression -const testAccVPCSecurityGroupRuleConfig_selfReference = ` -resource "aws_vpc" "main" { +func testAccVPCSecurityGroupRuleConfig_selfReference(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-self-ref" + Name = %[1]q } } -resource "aws_security_group" "web" { - name = "main" - vpc_id = aws_vpc.main.id +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id tags = { - Name = "sg-self-test" + Name = %[1]q } } -resource "aws_security_group_rule" "self" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "-1" from_port = 0 to_port = 0 self = true - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id +} +`, rName) } -` func testAccVPCSecurityGroupRuleConfig_partialMatching(rInt int) string { return fmt.Sprintf(` From f1ed817d2571d94cb5f6bca2741996235970d1c4 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:34:57 -0400 Subject: [PATCH 066/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_expectInvalidTypeError'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_expectInvalidTypeError' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_expectInvalidTypeError -timeout 180m === RUN TestAccVPCSecurityGroupRule_expectInvalidTypeError === PAUSE TestAccVPCSecurityGroupRule_expectInvalidTypeError === CONT TestAccVPCSecurityGroupRule_expectInvalidTypeError --- PASS: TestAccVPCSecurityGroupRule_expectInvalidTypeError (2.11s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 8.575s --- .../ec2/vpc_security_group_rule_test.go | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index ebfd92242157..5cb6c1791fff 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -425,7 +425,8 @@ func TestAccVPCSecurityGroupRule_selfReference(t *testing.T) { } func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -433,7 +434,7 @@ func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_expectInvalidType(rInt), + Config: testAccVPCSecurityGroupRuleConfig_expectInvalidType(rName), ExpectError: regexp.MustCompile(`expected type to be one of \[ingress egress\]`), }, }, @@ -2110,31 +2111,34 @@ resource "aws_security_group_rule" "test" { `, rName) } -func testAccVPCSecurityGroupRuleConfig_expectInvalidType(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_expectInvalidType(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-invalid-type" + Name = %[1]q } } -resource "aws_security_group" "web" { - name = "allow_all-%d" - description = "Allow all inbound traffic" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "allow_self" { - type = "foobar" +resource "aws_security_group_rule" "test" { + type = "invalid" from_port = 0 to_port = 0 protocol = "-1" - security_group_id = aws_security_group.web.id - source_security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id + source_security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } func testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rInt int) string { From 78cb5fe9ca4a56734e433cf6c9f3ecb42698c6c2 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:38:54 -0400 Subject: [PATCH 067/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_expectInvalidCIDR'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_expectInvalidCIDR' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_expectInvalidCIDR -timeout 180m === RUN TestAccVPCSecurityGroupRule_expectInvalidCIDR === PAUSE TestAccVPCSecurityGroupRule_expectInvalidCIDR === CONT TestAccVPCSecurityGroupRule_expectInvalidCIDR --- PASS: TestAccVPCSecurityGroupRule_expectInvalidCIDR (3.31s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 10.469s --- .../ec2/vpc_security_group_rule_test.go | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 5cb6c1791fff..98a348748431 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -442,7 +442,8 @@ func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { } func TestAccVPCSecurityGroupRule_expectInvalidCIDR(t *testing.T) { - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), @@ -450,11 +451,11 @@ func TestAccVPCSecurityGroupRule_expectInvalidCIDR(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rInt), + Config: testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rName), ExpectError: regexp.MustCompile("invalid CIDR address: 1.2.3.4/33"), }, { - Config: testAccVPCSecurityGroupRuleConfig_invalidIPv6CIDR(rInt), + Config: testAccVPCSecurityGroupRuleConfig_invalidIPv6CIDR(rName), ExpectError: regexp.MustCompile("invalid CIDR address: ::/244"), }, }, @@ -2141,36 +2142,44 @@ resource "aws_security_group_rule" "test" { `, rName) } -func testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_invalidIPv4CIDR(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "foo" { - name = "testing-failure-%d" +resource "aws_security_group" "test" { + name = %[1]q + + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "ing" { +resource "aws_security_group_rule" "test" { type = "ingress" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["1.2.3.4/33"] - security_group_id = aws_security_group.foo.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } -func testAccVPCSecurityGroupRuleConfig_invalidIPv6CIDR(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_invalidIPv6CIDR(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "foo" { - name = "testing-failure-%d" +resource "aws_security_group" "test" { + name = %[1]q + + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "ing" { +resource "aws_security_group_rule" "test" { type = "egress" from_port = 0 to_port = 0 protocol = "-1" ipv6_cidr_blocks = ["::/244"] - security_group_id = aws_security_group.foo.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } From c3adb70124db0ea2dc5a5610f4e5a62c37481587 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:49:00 -0400 Subject: [PATCH 068/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_PartialMatching_basic'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_PartialMatching_basic' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_PartialMatching_basic -timeout 180m === RUN TestAccVPCSecurityGroupRule_PartialMatching_basic === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_basic === CONT TestAccVPCSecurityGroupRule_PartialMatching_basic --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_basic (32.20s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 36.352s --- .../ec2/vpc_security_group_rule_test.go | 93 ++++++++----------- 1 file changed, 37 insertions(+), 56 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 98a348748431..b66fe7d9c856 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -464,28 +464,10 @@ func TestAccVPCSecurityGroupRule_expectInvalidCIDR(t *testing.T) { // testing partial match implementation func TestAccVPCSecurityGroupRule_PartialMatching_basic(t *testing.T) { - var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() - - p := ec2.IpPermission{ - FromPort: aws.Int64(80), - ToPort: aws.Int64(80), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("10.0.2.0/24")}, - {CidrIp: aws.String("10.0.3.0/24")}, - {CidrIp: aws.String("10.0.4.0/24")}, - }, - } - - o := ec2.IpPermission{ - FromPort: aws.Int64(80), - ToPort: aws.Int64(80), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("10.0.5.0/24")}, - }, - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource1Name := "aws_security_group_rule.test1" + resource2Name := "aws_security_group_rule.test2" + resource3Name := "aws_security_group_rule.test3" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -494,30 +476,36 @@ func TestAccVPCSecurityGroupRule_PartialMatching_basic(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_partialMatching(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress", &group, &p, "ingress"), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.other", &group, &o, "ingress"), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.nat_ingress", &group, &o, "ingress"), + Config: testAccVPCSecurityGroupRuleConfig_partialMatching(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "3"), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.0", "10.0.2.0/24"), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.1", "10.0.3.0/24"), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.2", "10.0.4.0/24"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.0", "10.0.5.0/24"), + resource.TestCheckResourceAttr(resource3Name, "cidr_blocks.#", "3"), + resource.TestCheckResourceAttr(resource3Name, "cidr_blocks.0", "10.0.2.0/24"), + resource.TestCheckResourceAttr(resource3Name, "cidr_blocks.1", "10.0.3.0/24"), + resource.TestCheckResourceAttr(resource3Name, "cidr_blocks.2", "10.0.4.0/24"), ), }, { - ResourceName: "aws_security_group_rule.ingress", + ResourceName: resource1Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource1Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.other", + ResourceName: resource2Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.other"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource2Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.nat_ingress", + ResourceName: resource3Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.nat_ingress"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource3Name), ImportStateVerify: true, }, }, @@ -1680,65 +1668,58 @@ resource "aws_security_group_rule" "test" { `, rName) } -func testAccVPCSecurityGroupRuleConfig_partialMatching(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_partialMatching(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "default" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-partial-match" + Name = %[1]q } } -resource "aws_security_group" "web" { - name = "tf-other-%d" - vpc_id = aws_vpc.default.id - - tags = { - Name = "tf-other-sg" - } -} +resource "aws_security_group" "test" { + count = 2 -resource "aws_security_group" "nat" { - name = "tf-nat-%d" - vpc_id = aws_vpc.default.id + name = "%[1]s-${count.index}" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-nat-sg" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress" { +resource "aws_security_group_rule" "test1" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["10.0.2.0/24", "10.0.3.0/24", "10.0.4.0/24"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test[0].id } -resource "aws_security_group_rule" "other" { +resource "aws_security_group_rule" "test2" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["10.0.5.0/24"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test[0].id } # same a above, but different group, to guard against bad hashing -resource "aws_security_group_rule" "nat_ingress" { +resource "aws_security_group_rule" "test3" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["10.0.2.0/24", "10.0.3.0/24", "10.0.4.0/24"] - security_group_id = aws_security_group.nat.id + security_group_id = aws_security_group.test[1].id } -`, rInt, rInt) +`, rName) } func testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rInt int) string { From 6955e1348c1952b780fad395fc45ec35eeb05e9d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:55:34 -0400 Subject: [PATCH 069/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_PartialMatching_source'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_PartialMatching_source' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_PartialMatching_source -timeout 180m === RUN TestAccVPCSecurityGroupRule_PartialMatching_source === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_source === CONT TestAccVPCSecurityGroupRule_PartialMatching_source --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_source (28.83s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 32.892s --- .../ec2/vpc_security_group_rule_test.go | 87 ++++++++----------- 1 file changed, 34 insertions(+), 53 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index b66fe7d9c856..446267bdc57c 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -513,30 +513,9 @@ func TestAccVPCSecurityGroupRule_PartialMatching_basic(t *testing.T) { } func TestAccVPCSecurityGroupRule_PartialMatching_source(t *testing.T) { - var group ec2.SecurityGroup - var nat ec2.SecurityGroup - var p ec2.IpPermission - rInt := sdkacctest.RandInt() - - // This function creates the expected IPPermission with the group id from an - // external security group, needed because Security Group IDs are generated on - // AWS side and can't be known ahead of time. - setupSG := func(*terraform.State) error { - if nat.GroupId == nil { - return fmt.Errorf("Error: nat group has nil GroupID") - } - - p = ec2.IpPermission{ - FromPort: aws.Int64(80), - ToPort: aws.Int64(80), - IpProtocol: aws.String("tcp"), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: nat.GroupId}, - }, - } - - return nil - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource1Name := "aws_security_group_rule.test1" + resource2Name := "aws_security_group_rule.test2" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -545,18 +524,27 @@ func TestAccVPCSecurityGroupRule_PartialMatching_source(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupExists("aws_security_group.nat", &nat), - setupSG, - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.source_ingress", &group, &p, "ingress"), + Config: testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttrSet(resource1Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.#", "3"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.0", "10.0.2.0/24"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.1", "10.0.3.0/24"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.2", "10.0.4.0/24"), + resource.TestCheckNoResourceAttr(resource2Name, "source_security_group_id"), ), }, { - ResourceName: "aws_security_group_rule.source_ingress", + ResourceName: resource1Name, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource1Name), + ImportStateVerify: true, + }, + { + ResourceName: resource2Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.source_ingress"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource2Name), ImportStateVerify: true, }, }, @@ -1722,54 +1710,47 @@ resource "aws_security_group_rule" "test3" { `, rName) } -func testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_partialMatchingSource(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "default" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-partial-match" + Name = %[1]q } } -resource "aws_security_group" "web" { - name = "tf-other-%d" - vpc_id = aws_vpc.default.id - - tags = { - Name = "tf-other-sg" - } -} +resource "aws_security_group" "test" { + count = 2 -resource "aws_security_group" "nat" { - name = "tf-nat-%d" - vpc_id = aws_vpc.default.id + name = "%[1]s-${count.index}" + vpc_id = aws_vpc.test.id tags = { - Name = "tf-nat-sg" + Name = %[1]q } } -resource "aws_security_group_rule" "source_ingress" { +resource "aws_security_group_rule" "test1" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" - source_security_group_id = aws_security_group.nat.id - security_group_id = aws_security_group.web.id + source_security_group_id = aws_security_group.test[0].id + security_group_id = aws_security_group.test[1].id } -resource "aws_security_group_rule" "other_ingress" { +resource "aws_security_group_rule" "test2" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["10.0.2.0/24", "10.0.3.0/24", "10.0.4.0/24"] - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test[0].id } -`, rInt, rInt) +`, rName) } const testAccVPCSecurityGroupRuleConfig_prefixListEgress = ` From bd2783161479fe3ddedc0b084ef3b1984cd96c1a Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 16:59:13 -0400 Subject: [PATCH 070/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_issue5310'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_issue5310' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_issue5310 -timeout 180m === RUN TestAccVPCSecurityGroupRule_issue5310 === PAUSE TestAccVPCSecurityGroupRule_issue5310 === CONT TestAccVPCSecurityGroupRule_issue5310 --- PASS: TestAccVPCSecurityGroupRule_issue5310 (21.96s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 26.010s --- .../ec2/vpc_security_group_rule_test.go | 43 +++++++++++++------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 446267bdc57c..264387a48364 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -553,6 +553,9 @@ func TestAccVPCSecurityGroupRule_PartialMatching_source(t *testing.T) { func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -561,15 +564,26 @@ func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_issue5310, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.issue_5310", &group), + Config: testAccVPCSecurityGroupRuleConfig_issue5310(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "true"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "65535"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.issue_5310", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.issue_5310"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1483,21 +1497,26 @@ resource "aws_security_group_rule" "test" { `, rName) } -const testAccVPCSecurityGroupRuleConfig_issue5310 = ` -resource "aws_security_group" "issue_5310" { - name = "terraform-test-issue_5310" - description = "SG for test of issue 5310" +func testAccVPCSecurityGroupRuleConfig_issue5310(rName string) string { + return fmt.Sprintf(` +resource "aws_security_group" "test" { + name = %[1]q + + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "issue_5310" { +resource "aws_security_group_rule" "test" { type = "ingress" from_port = 0 to_port = 65535 protocol = "tcp" - security_group_id = aws_security_group.issue_5310.id + security_group_id = aws_security_group.test.id self = true } -` +`, rName) +} func testAccVPCSecurityGroupRuleConfig_ingressClassic(rName string) string { return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` From 540b1ec23c5bc50da1eea223cd5a305d6bc287e3 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 29 Jun 2022 17:27:54 -0400 Subject: [PATCH 071/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_race'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_race' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_race -timeout 180m === RUN TestAccVPCSecurityGroupRule_race === PAUSE TestAccVPCSecurityGroupRule_race === CONT TestAccVPCSecurityGroupRule_race --- PASS: TestAccVPCSecurityGroupRule_race (152.43s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 156.361s --- .../ec2/vpc_security_group_rule_test.go | 62 ++++++++++--------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 264387a48364..bffacf47ca27 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -592,6 +592,9 @@ func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { func TestAccVPCSecurityGroupRule_race(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + sgResourceName := "aws_security_group.test" + n := 50 resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -600,9 +603,10 @@ func TestAccVPCSecurityGroupRule_race(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_race, + Config: testAccVPCSecurityGroupRuleConfig_race(rName, n), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.race", &group), + testAccCheckSecurityGroupExists(sgResourceName, &group), + testAccCheckSecurityGroupRuleCount(&group, n, n), ), }, }, @@ -1992,46 +1996,48 @@ resource "aws_security_group_rule" "test2" { `, rName) } -var testAccVPCSecurityGroupRuleConfig_race = func() string { - var b bytes.Buffer - iterations := 50 - b.WriteString(fmt.Sprintf(` -resource "aws_vpc" "default" { +func testAccVPCSecurityGroupRuleConfig_race(rName string, n int) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-race" + Name = %[1]q } } -resource "aws_security_group" "race" { - name = "tf-sg-rule-race-group-%d" - vpc_id = aws_vpc.default.id +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } -`, sdkacctest.RandInt())) - for i := 1; i < iterations; i++ { - b.WriteString(fmt.Sprintf(` -resource "aws_security_group_rule" "ingress%d" { - security_group_id = aws_security_group.race.id + +resource "aws_security_group_rule" "test_ingress" { + count = %[2]d + + security_group_id = aws_security_group.test.id type = "ingress" - from_port = %d - to_port = %d + from_port = count.index + to_port = count.index protocol = "tcp" - cidr_blocks = ["10.0.0.%d/32"] + cidr_blocks = ["10.0.0.${count.index}/32"] } -resource "aws_security_group_rule" "egress%d" { - security_group_id = aws_security_group.race.id +resource "aws_security_group_rule" "test_egress" { + count = %[2]d + + security_group_id = aws_security_group.test.id type = "egress" - from_port = %d - to_port = %d + from_port = count.index + to_port = count.index protocol = "tcp" - cidr_blocks = ["10.0.0.%d/32"] + cidr_blocks = ["10.0.0.${count.index}/32"] +} +`, rName, n) } -`, i, i, i, i, i, i, i, i)) - } - return b.String() -}() func testAccVPCSecurityGroupRuleConfig_selfInSource(rInt int) string { return fmt.Sprintf(` From 726f5d89a674e73e336bbaa91d3e9872b79b1d2f Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 09:11:51 -0400 Subject: [PATCH 072/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_selfSource'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_selfSource' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_selfSource -timeout 180m === RUN TestAccVPCSecurityGroupRule_selfSource === PAUSE TestAccVPCSecurityGroupRule_selfSource === CONT TestAccVPCSecurityGroupRule_selfSource --- PASS: TestAccVPCSecurityGroupRule_selfSource (25.26s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 29.711s --- .../ec2/vpc_security_group_rule_test.go | 50 ++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index bffacf47ca27..d3cf1fb9ac30 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -615,7 +615,9 @@ func TestAccVPCSecurityGroupRule_race(t *testing.T) { func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -624,15 +626,26 @@ func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_selfInSource(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), + Config: testAccVPCSecurityGroupRuleConfig_selfInSource(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckResourceAttrPair(resourceName, "source_security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.allow_self", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.allow_self"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -2039,31 +2052,34 @@ resource "aws_security_group_rule" "test_egress" { `, rName, n) } -func testAccVPCSecurityGroupRuleConfig_selfInSource(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_selfInSource(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-self-ingress" + Name = %[1]q } } -resource "aws_security_group" "web" { - name = "allow_all-%d" - description = "Allow all inbound traffic" - vpc_id = aws_vpc.foo.id +resource "aws_security_group" "test" { + name = %[1]q + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "allow_self" { +resource "aws_security_group_rule" "test" { type = "ingress" from_port = 0 to_port = 0 protocol = "-1" - security_group_id = aws_security_group.web.id - source_security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id + source_security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } func testAccVPCSecurityGroupRuleConfig_ingressSourceAccountID(rName string) string { From 4bc4acd5a6bb9f111ac40c7f97c480744640e9f6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 09:22:14 -0400 Subject: [PATCH 073/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_prefixListEgress'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_prefixListEgress' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_prefixListEgress -timeout 180m === RUN TestAccVPCSecurityGroupRule_prefixListEgress === PAUSE TestAccVPCSecurityGroupRule_prefixListEgress === CONT TestAccVPCSecurityGroupRule_prefixListEgress --- PASS: TestAccVPCSecurityGroupRule_prefixListEgress (38.32s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 42.487s --- .../ec2/vpc_security_group_rule_test.go | 109 ++++++++---------- 1 file changed, 50 insertions(+), 59 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index d3cf1fb9ac30..abc8024259b4 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -654,39 +654,10 @@ func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { func TestAccVPCSecurityGroupRule_prefixListEgress(t *testing.T) { var group ec2.SecurityGroup - var endpoint ec2.VpcEndpoint - var p ec2.IpPermission - - // This function creates the expected IPPermission with the prefix list ID from - // the VPC Endpoint created in the test - setupSG := func(*terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - prefixListInput := &ec2.DescribePrefixListsInput{ - Filters: []*ec2.Filter{ - {Name: aws.String("prefix-list-name"), Values: []*string{endpoint.ServiceName}}, - }, - } - - log.Printf("[DEBUG] Reading VPC Endpoint prefix list: %s", prefixListInput) - prefixListsOutput, err := conn.DescribePrefixLists(prefixListInput) - - if err != nil { - return fmt.Errorf("error reading VPC Endpoint prefix list: %w", err) - } - - if len(prefixListsOutput.PrefixLists) != 1 { - return fmt.Errorf("unexpected multiple prefix lists associated with the service: %s", prefixListsOutput) - } - - p = ec2.IpPermission{ - IpProtocol: aws.String("-1"), - PrefixListIds: []*ec2.PrefixListId{ - {PrefixListId: prefixListsOutput.PrefixLists[0].PrefixListId}, - }, - } - - return nil - } + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" + vpceResourceName := "aws_vpc_endpoint.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -695,20 +666,27 @@ func TestAccVPCSecurityGroupRule_prefixListEgress(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_prefixListEgress, - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.egress", &group), - // lookup info on the VPC Endpoint created, to populate the expected - // IP Perm - testAccCheckVPCEndpointExists("aws_vpc_endpoint.s3_endpoint", &endpoint), - setupSG, - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.egress_1", &group, &p, "egress"), + Config: testAccVPCSecurityGroupRuleConfig_prefixListEgress(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "prefix_list_ids.0", vpceResourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "egress"), ), }, { - ResourceName: "aws_security_group_rule.egress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.egress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1789,25 +1767,34 @@ resource "aws_security_group_rule" "test2" { `, rName) } -const testAccVPCSecurityGroupRuleConfig_prefixListEgress = ` -resource "aws_vpc" "tf_sg_prefix_list_egress_test" { +func testAccVPCSecurityGroupRuleConfig_prefixListEgress(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-prefix-list-egress" + Name = %[1]q } } -resource "aws_route_table" "default" { - vpc_id = aws_vpc.tf_sg_prefix_list_egress_test.id +resource "aws_route_table" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } } data "aws_region" "current" {} -resource "aws_vpc_endpoint" "s3_endpoint" { - vpc_id = aws_vpc.tf_sg_prefix_list_egress_test.id +resource "aws_vpc_endpoint" "test" { + vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" - route_table_ids = [aws_route_table.default.id] + route_table_ids = [aws_route_table.test.id] + + tags = { + Name = %[1]q + } policy = < Date: Thu, 30 Jun 2022 09:30:24 -0400 Subject: [PATCH 074/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_ingressDescription'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_ingressDescription\|TestAccVPCSecurityGroupRule_IngressDescription_updates' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_ingressDescription\|TestAccVPCSecurityGroupRule_IngressDescription_updates -timeout 180m === RUN TestAccVPCSecurityGroupRule_ingressDescription === PAUSE TestAccVPCSecurityGroupRule_ingressDescription === RUN TestAccVPCSecurityGroupRule_IngressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_IngressDescription_updates === CONT TestAccVPCSecurityGroupRule_ingressDescription === CONT TestAccVPCSecurityGroupRule_IngressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_ingressDescription (20.10s) --- PASS: TestAccVPCSecurityGroupRule_IngressDescription_updates (32.33s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 36.433s --- .../ec2/vpc_security_group_rule_test.go | 107 +++++++++++------- 1 file changed, 69 insertions(+), 38 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index abc8024259b4..5ddc5d9a8ede 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -695,7 +695,9 @@ func TestAccVPCSecurityGroupRule_prefixListEgress(t *testing.T) { func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -704,17 +706,27 @@ func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), - resource.TestCheckResourceAttr("aws_security_group_rule.ingress_1", "description", "TF acceptance test ingress rule"), + Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckResourceAttr(resourceName, "description", "TF acceptance test ingress rule"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.ingress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -763,7 +775,9 @@ func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { var group ec2.SecurityGroup - rInt := sdkacctest.RandInt() + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -772,26 +786,45 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), - resource.TestCheckResourceAttr("aws_security_group_rule.ingress_1", "description", "TF acceptance test ingress rule"), + Config: testAccVPCSecurityGroupRuleConfig_ingressDescription(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckResourceAttr(resourceName, "description", "TF acceptance test ingress rule"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, - { - Config: testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.web", &group), - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.ingress_1", &group, nil, "ingress"), - resource.TestCheckResourceAttr("aws_security_group_rule.ingress_1", "description", "TF acceptance test ingress rule updated"), + Config: testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckResourceAttr(resourceName, "description", "TF acceptance test ingress rule updated"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.ingress_1", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.ingress_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -1832,18 +1865,17 @@ resource "aws_security_group_rule" "test" { `, rName) } -func testAccVPCSecurityGroupRuleConfig_ingressDescription(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressDescription(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress_1" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "tcp" from_port = 80 @@ -1851,23 +1883,22 @@ resource "aws_security_group_rule" "ingress_1" { cidr_blocks = ["10.0.0.0/8"] description = "TF acceptance test ingress rule" - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } -func testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rInt int) string { +func testAccVPCSecurityGroupRuleConfig_ingressUpdateDescription(rName string) string { return fmt.Sprintf(` -resource "aws_security_group" "web" { - name = "terraform_test_%d" - description = "Used in the terraform acceptance tests" +resource "aws_security_group" "test" { + name = %[1]q tags = { - Name = "tf-acc-test" + Name = %[1]q } } -resource "aws_security_group_rule" "ingress_1" { +resource "aws_security_group_rule" "test" { type = "ingress" protocol = "tcp" from_port = 80 @@ -1875,9 +1906,9 @@ resource "aws_security_group_rule" "ingress_1" { cidr_blocks = ["10.0.0.0/8"] description = "TF acceptance test ingress rule updated" - security_group_id = aws_security_group.web.id + security_group_id = aws_security_group.test.id } -`, rInt) +`, rName) } func testAccVPCSecurityGroupRuleConfig_egressDescription(rName string) string { From 45eaf5a0ad03f2594e3799e7116f5b22bc5e37c6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 09:46:27 -0400 Subject: [PATCH 075/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_Description_allPorts'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Description_allPorts' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_Description_allPorts -timeout 180m === RUN TestAccVPCSecurityGroupRule_Description_allPorts === PAUSE TestAccVPCSecurityGroupRule_Description_allPorts === CONT TestAccVPCSecurityGroupRule_Description_allPorts --- PASS: TestAccVPCSecurityGroupRule_Description_allPorts (30.85s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 37.289s --- internal/service/ec2/vpc_security_group.go | 8 ++++ .../ec2/vpc_security_group_rule_test.go | 48 +++++++++---------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index 95a80babe136..b71c1def4aaa 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -384,6 +384,14 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("error deleting Security Group (%s): %w", d.Id(), err) } + _, err = tfresource.RetryUntilNotFound(propagationTimeout, func() (interface{}, error) { + return FindSecurityGroupByID(conn, d.Id()) + }) + + if err != nil { + return fmt.Errorf("error waiting for Security Group (%s) delete: %w", d.Id(), err) + } + return nil } diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 5ddc5d9a8ede..eb3fb1cfe47b 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -892,22 +892,8 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - securityGroupResourceName := "aws_security_group.test" resourceName := "aws_security_group_rule.test" - - rule1 := ec2.IpPermission{ - IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("0.0.0.0/0"), Description: aws.String("description1")}, - }, - } - - rule2 := ec2.IpPermission{ - IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("0.0.0.0/0"), Description: aws.String("description2")}, - }, - } + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -917,13 +903,20 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, "description1"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(securityGroupResourceName, &group), - testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule1, "ingress"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "0.0.0.0/0"), resource.TestCheckResourceAttr(resourceName, "description", "description1"), resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { @@ -934,13 +927,20 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { }, { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, "description2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(securityGroupResourceName, &group), - testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule2, "ingress"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "0.0.0.0/0"), resource.TestCheckResourceAttr(resourceName, "description", "description2"), resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, }, @@ -1960,16 +1960,16 @@ resource "aws_security_group_rule" "test" { func testAccVPCSecurityGroupRuleConfig_descriptionAllPorts(rName, description string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { - name = %q + name = %[1]q tags = { - Name = "tf-acc-test-ec2-security-group-rule" + Name = %[1]q } } resource "aws_security_group_rule" "test" { cidr_blocks = ["0.0.0.0/0"] - description = %q + description = %[2]q from_port = 0 protocol = -1 security_group_id = aws_security_group.test.id From e0b3aa6d89556671512291d43f9b5a7fd6d2ac01 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 10:01:29 -0400 Subject: [PATCH 076/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts -timeout 180m === RUN TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === PAUSE TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === CONT TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts --- PASS: TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts (33.62s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 38.345s --- .../ec2/vpc_security_group_rule_test.go | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index eb3fb1cfe47b..1a3a9c48e352 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -950,22 +950,8 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - securityGroupResourceName := "aws_security_group.test" resourceName := "aws_security_group_rule.test" - - rule1 := ec2.IpPermission{ - IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("0.0.0.0/0"), Description: aws.String("description1")}, - }, - } - - rule2 := ec2.IpPermission{ - IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("0.0.0.0/0"), Description: aws.String("description2")}, - }, - } + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -975,13 +961,20 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, "description1"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(securityGroupResourceName, &group), - testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule1, "ingress"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "0.0.0.0/0"), resource.TestCheckResourceAttr(resourceName, "description", "description1"), resource.TestCheckResourceAttr(resourceName, "from_port", "-1"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), resource.TestCheckResourceAttr(resourceName, "to_port", "-1"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, { @@ -992,13 +985,20 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) }, { Config: testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, "description2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(securityGroupResourceName, &group), - testAccCheckSecurityGroupRuleAttributes(resourceName, &group, &rule2, "ingress"), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "0.0.0.0/0"), resource.TestCheckResourceAttr(resourceName, "description", "description2"), resource.TestCheckResourceAttr(resourceName, "from_port", "0"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), resource.TestCheckResourceAttr(resourceName, "protocol", "-1"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), resource.TestCheckResourceAttr(resourceName, "to_port", "0"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), ), }, }, @@ -1982,16 +1982,16 @@ resource "aws_security_group_rule" "test" { func testAccVPCSecurityGroupRuleConfig_descriptionAllPortsNonZeroPorts(rName, description string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { - name = %q + name = %[1]q tags = { - Name = "tf-acc-test-ec2-security-group-rule" + Name = %[1]q } } resource "aws_security_group_rule" "test" { cidr_blocks = ["0.0.0.0/0"] - description = %q + description = %[2]q from_port = -1 protocol = -1 security_group_id = aws_security_group.test.id From 2cb37cda524131c614f142dfb78ef6d355fbf9dd Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 11:11:33 -0400 Subject: [PATCH 077/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash -timeout 180m === RUN TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === PAUSE TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === CONT TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash --- PASS: TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash (30.73s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 38.330s --- .../ec2/vpc_security_group_rule_test.go | 72 +++++++++++-------- 1 file changed, 42 insertions(+), 30 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 1a3a9c48e352..32745d97bec9 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1009,25 +1009,9 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - securityGroupResourceName := "aws_security_group.test" - resourceName1 := "aws_security_group_rule.test1" - resourceName2 := "aws_security_group_rule.test2" - - rule1 := ec2.IpPermission{ - IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("10.0.0.0/8")}, - }, - } - - rule2 := ec2.IpPermission{ - FromPort: aws.Int64(443), - ToPort: aws.Int64(443), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("172.168.0.0/16")}, - }, - } + resource1Name := "aws_security_group_rule.test1" + resource2Name := "aws_security_group_rule.test2" + sgResourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1038,17 +1022,45 @@ func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testi { Config: testAccVPCSecurityGroupRuleConfig_multipleSearchingAllProtocolCrash(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists(securityGroupResourceName, &group), - testAccCheckSecurityGroupRuleAttributes(resourceName1, &group, &rule1, "ingress"), - testAccCheckSecurityGroupRuleAttributes(resourceName2, &group, &rule2, "ingress"), - resource.TestCheckResourceAttr(resourceName1, "from_port", "0"), - resource.TestCheckResourceAttr(resourceName1, "protocol", "-1"), - resource.TestCheckResourceAttr(resourceName1, "to_port", "65535"), - resource.TestCheckResourceAttr(resourceName2, "from_port", "443"), - resource.TestCheckResourceAttr(resourceName2, "protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName2, "to_port", "443"), + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.0", "10.0.0.0/8"), + resource.TestCheckNoResourceAttr(resource1Name, "description"), + resource.TestCheckResourceAttr(resource1Name, "from_port", "0"), + resource.TestCheckResourceAttr(resource1Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource1Name, "protocol", "-1"), + resource.TestCheckResourceAttr(resource1Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource1Name, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resource1Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource1Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource1Name, "to_port", "65535"), + resource.TestCheckResourceAttr(resource1Name, "type", "ingress"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.0", "172.168.0.0/16"), + resource.TestCheckNoResourceAttr(resource2Name, "description"), + resource.TestCheckResourceAttr(resource2Name, "from_port", "443"), + resource.TestCheckResourceAttr(resource2Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource2Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource2Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource2Name, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resource2Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource2Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource2Name, "to_port", "443"), + resource.TestCheckResourceAttr(resource2Name, "type", "ingress"), ), }, + { + ResourceName: resource1Name, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource1Name), + ImportStateVerify: true, + }, + { + ResourceName: resource2Name, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource2Name), + ImportStateVerify: true, + }, }, }) } @@ -2004,10 +2016,10 @@ resource "aws_security_group_rule" "test" { func testAccVPCSecurityGroupRuleConfig_multipleSearchingAllProtocolCrash(rName string) string { return fmt.Sprintf(` resource "aws_security_group" "test" { - name = %q + name = %[1]q tags = { - Name = "tf-acc-test-ec2-security-group-rule" + Name = %[1]q } } From 710684be9dc2db2f816f1c63dff54892cdc83504 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 11:55:53 -0400 Subject: [PATCH 078/120] r/aws_security_group_rule: Tidy up 'TestAccVPCSecurityGroupRule_multiDescription'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_multiDescription' PKG=ec2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 20 -run=TestAccVPCSecurityGroupRule_multiDescription -timeout 180m === RUN TestAccVPCSecurityGroupRule_multiDescription === PAUSE TestAccVPCSecurityGroupRule_multiDescription === CONT TestAccVPCSecurityGroupRule_multiDescription --- PASS: TestAccVPCSecurityGroupRule_multiDescription (68.12s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 72.571s --- .../ec2/vpc_security_group_rule_test.go | 446 ++++++------------ 1 file changed, 153 insertions(+), 293 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 32745d97bec9..4d9dadb38fa1 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1,9 +1,7 @@ package ec2_test import ( - "bytes" "fmt" - "log" "regexp" "strconv" "strings" @@ -15,7 +13,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" - "github.com/hashicorp/terraform-provider-aws/internal/conns" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) @@ -1066,85 +1063,15 @@ func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testi } func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { - var group ec2.SecurityGroup - var nat ec2.SecurityGroup - rInt := sdkacctest.RandInt() - - rule1 := ec2.IpPermission{ - FromPort: aws.Int64(22), - ToPort: aws.Int64(22), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("0.0.0.0/0"), Description: aws.String("CIDR Description")}, - }, - } - - rule2 := ec2.IpPermission{ - FromPort: aws.Int64(22), - ToPort: aws.Int64(22), - IpProtocol: aws.String("tcp"), - Ipv6Ranges: []*ec2.Ipv6Range{ - {CidrIpv6: aws.String("::/0"), Description: aws.String("IPv6 CIDR Description")}, - }, - } - - var rule3 ec2.IpPermission - - // This function creates the expected IPPermission with the group id from an - // external security group, needed because Security Group IDs are generated on - // AWS side and can't be known ahead of time. - setupSG := func(*terraform.State) error { - if nat.GroupId == nil { - return fmt.Errorf("Error: nat group has nil GroupID") - } - - rule3 = ec2.IpPermission{ - FromPort: aws.Int64(22), - ToPort: aws.Int64(22), - IpProtocol: aws.String("tcp"), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: nat.GroupId, Description: aws.String("NAT SG Description")}, - }, - } - - return nil - } - - var endpoint ec2.VpcEndpoint - var rule4 ec2.IpPermission - - // This function creates the expected IPPermission with the prefix list ID from - // the VPC Endpoint created in the test - setupPL := func(*terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - prefixListInput := &ec2.DescribePrefixListsInput{ - Filters: []*ec2.Filter{ - {Name: aws.String("prefix-list-name"), Values: []*string{endpoint.ServiceName}}, - }, - } - - log.Printf("[DEBUG] Reading VPC Endpoint prefix list: %s", prefixListInput) - prefixListsOutput, err := conn.DescribePrefixLists(prefixListInput) - - if err != nil { - return fmt.Errorf("error reading VPC Endpoint prefix list: %w", err) - } - - if len(prefixListsOutput.PrefixLists) != 1 { - return fmt.Errorf("unexpected multiple prefix lists associated with the service: %s", prefixListsOutput) - } - - rule4 = ec2.IpPermission{ - FromPort: aws.Int64(22), - ToPort: aws.Int64(22), - IpProtocol: aws.String("tcp"), - PrefixListIds: []*ec2.PrefixListId{ - {PrefixListId: prefixListsOutput.PrefixLists[0].PrefixListId, Description: aws.String("Prefix List Description")}, - }, - } - - return nil - } + var group1, group2 ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resource1Name := "aws_security_group_rule.test1" + resource2Name := "aws_security_group_rule.test2" + resource3Name := "aws_security_group_rule.test3" + resource4Name := "aws_security_group_rule.test4" + sg1ResourceName := "aws_security_group.test.0" + sg2ResourceName := "aws_security_group.test.1" + vpceResourceName := "aws_vpc_endpoint.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t) }, @@ -1153,212 +1080,147 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { CheckDestroy: testAccCheckSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccVPCSecurityGroupRuleConfig_multidescription(rInt, "ingress"), + Config: testAccVPCSecurityGroupRuleConfig_multiDescription(rName, "ingress"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.worker", &group), - testAccCheckSecurityGroupExists("aws_security_group.nat", &nat), - testAccCheckVPCEndpointExists("aws_vpc_endpoint.s3_endpoint", &endpoint), - - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_1", &group, &rule1, "ingress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_1", "description", "CIDR Description"), - - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_2", &group, &rule2, "ingress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_2", "description", "IPv6 CIDR Description"), - - setupSG, - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_3", &group, &rule3, "ingress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_3", "description", "NAT SG Description"), + testAccCheckSecurityGroupExists(sg1ResourceName, &group1), + testAccCheckSecurityGroupExists(sg2ResourceName, &group2), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.0", "0.0.0.0/0"), + resource.TestCheckResourceAttr(resource1Name, "description", "CIDR Description"), + resource.TestCheckResourceAttr(resource1Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource1Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource1Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource1Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource1Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource1Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource1Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource1Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource1Name, "type", "ingress"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource2Name, "description", "IPv6 CIDR Description"), + resource.TestCheckResourceAttr(resource2Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource2Name, "ipv6_cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource2Name, "ipv6_cidr_blocks.0", "::/0"), + resource.TestCheckResourceAttr(resource2Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource2Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource2Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource2Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource2Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource2Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource2Name, "type", "ingress"), + resource.TestCheckResourceAttr(resource3Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource3Name, "description", "Third Description"), + resource.TestCheckResourceAttr(resource3Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource3Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource3Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource3Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource3Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource3Name, "self", "false"), + resource.TestCheckResourceAttrPair(resource3Name, "source_security_group_id", sg2ResourceName, "id"), + resource.TestCheckResourceAttr(resource3Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource3Name, "type", "ingress"), ), }, { - ResourceName: "aws_security_group_rule.rule_1", + ResourceName: resource1Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource1Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.rule_2", + ResourceName: resource2Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_2"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource2Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.rule_3", + ResourceName: resource3Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_3"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource3Name), ImportStateVerify: true, }, { - Config: testAccVPCSecurityGroupRuleConfig_multidescription(rInt, "egress"), + Config: testAccVPCSecurityGroupRuleConfig_multiDescription(rName, "egress"), Check: resource.ComposeTestCheckFunc( - testAccCheckSecurityGroupExists("aws_security_group.worker", &group), - testAccCheckSecurityGroupExists("aws_security_group.nat", &nat), - testAccCheckVPCEndpointExists("aws_vpc_endpoint.s3_endpoint", &endpoint), - - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_1", &group, &rule1, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_1", "description", "CIDR Description"), - - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_2", &group, &rule2, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_2", "description", "IPv6 CIDR Description"), - - setupSG, - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_3", &group, &rule3, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_3", "description", "NAT SG Description"), - - setupPL, - testAccCheckSecurityGroupRuleAttributes("aws_security_group_rule.rule_4", &group, &rule4, "egress"), - resource.TestCheckResourceAttr("aws_security_group_rule.rule_4", "description", "Prefix List Description"), + testAccCheckSecurityGroupExists(sg1ResourceName, &group1), + testAccCheckSecurityGroupExists(sg2ResourceName, &group2), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.0", "0.0.0.0/0"), + resource.TestCheckResourceAttr(resource1Name, "description", "CIDR Description"), + resource.TestCheckResourceAttr(resource1Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource1Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource1Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource1Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource1Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource1Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource1Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource1Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource1Name, "type", "egress"), + resource.TestCheckResourceAttr(resource2Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource2Name, "description", "IPv6 CIDR Description"), + resource.TestCheckResourceAttr(resource2Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource2Name, "ipv6_cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resource2Name, "ipv6_cidr_blocks.0", "::/0"), + resource.TestCheckResourceAttr(resource2Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource2Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource2Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource2Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource2Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource2Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource2Name, "type", "egress"), + resource.TestCheckResourceAttr(resource3Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource3Name, "description", "Third Description"), + resource.TestCheckResourceAttr(resource3Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource3Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource3Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource3Name, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resource3Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource3Name, "self", "false"), + resource.TestCheckResourceAttrPair(resource3Name, "source_security_group_id", sg2ResourceName, "id"), + resource.TestCheckResourceAttr(resource3Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource3Name, "type", "egress"), + resource.TestCheckResourceAttr(resource4Name, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource4Name, "description", "Prefix List Description"), + resource.TestCheckResourceAttr(resource4Name, "from_port", "22"), + resource.TestCheckResourceAttr(resource4Name, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resource4Name, "protocol", "tcp"), + resource.TestCheckResourceAttr(resource4Name, "prefix_list_ids.#", "1"), + resource.TestCheckResourceAttrPair(resource4Name, "prefix_list_ids.0", vpceResourceName, "prefix_list_id"), + resource.TestCheckResourceAttrPair(resource4Name, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resource4Name, "self", "false"), + resource.TestCheckNoResourceAttr(resource4Name, "source_security_group_id"), + resource.TestCheckResourceAttr(resource4Name, "to_port", "22"), + resource.TestCheckResourceAttr(resource4Name, "type", "egress"), ), }, { - ResourceName: "aws_security_group_rule.rule_1", + ResourceName: resource1Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_1"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource1Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.rule_2", + ResourceName: resource2Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_2"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource2Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.rule_3", + ResourceName: resource3Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_3"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource3Name), ImportStateVerify: true, }, { - ResourceName: "aws_security_group_rule.rule_4", + ResourceName: resource4Name, ImportState: true, - ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc("aws_security_group_rule.rule_4"), + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resource4Name), ImportStateVerify: true, }, }, }) } -func testAccCheckSecurityGroupRuleAttributes(n string, group *ec2.SecurityGroup, p *ec2.IpPermission, ruleType string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Security Group Rule Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No Security Group Rule is set") - } - - if p == nil { - p = &ec2.IpPermission{ - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - } - } - - var matchingRule *ec2.IpPermission - var rules []*ec2.IpPermission - if ruleType == "ingress" { - rules = group.IpPermissions - } else { - rules = group.IpPermissionsEgress - } - - if len(rules) == 0 { - return fmt.Errorf("No IPPerms") - } - - for _, r := range rules { - if p.ToPort != nil && r.ToPort != nil && *p.ToPort != *r.ToPort { - continue - } - - if p.FromPort != nil && r.FromPort != nil && *p.FromPort != *r.FromPort { - continue - } - - if p.IpProtocol != nil && r.IpProtocol != nil && *p.IpProtocol != *r.IpProtocol { - continue - } - - remaining := len(p.IpRanges) - for _, ip := range p.IpRanges { - for _, rip := range r.IpRanges { - if ip.CidrIp == nil || rip.CidrIp == nil { - continue - } - if *ip.CidrIp == *rip.CidrIp { - remaining-- - } - } - } - - if remaining > 0 { - continue - } - - remaining = len(p.Ipv6Ranges) - for _, ip := range p.Ipv6Ranges { - for _, rip := range r.Ipv6Ranges { - if ip.CidrIpv6 == nil || rip.CidrIpv6 == nil { - continue - } - if *ip.CidrIpv6 == *rip.CidrIpv6 { - remaining-- - } - } - } - - if remaining > 0 { - continue - } - - remaining = len(p.UserIdGroupPairs) - for _, ip := range p.UserIdGroupPairs { - for _, rip := range r.UserIdGroupPairs { - if ip.GroupId == nil || rip.GroupId == nil { - continue - } - if *ip.GroupId == *rip.GroupId { - remaining-- - } - } - } - - if remaining > 0 { - continue - } - - remaining = len(p.PrefixListIds) - for _, pip := range p.PrefixListIds { - for _, rpip := range r.PrefixListIds { - if pip.PrefixListId == nil || rpip.PrefixListId == nil { - continue - } - if *pip.PrefixListId == *rpip.PrefixListId { - remaining-- - } - } - } - - if remaining > 0 { - continue - } - - matchingRule = r - } - - if matchingRule != nil { - log.Printf("[DEBUG] Matching rule found : %s", matchingRule) - return nil - } - - return fmt.Errorf("Error here\n\tlooking for %s, wasn't found in %s", p, rules) - } -} - func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -1602,86 +1464,84 @@ resource "aws_security_group_rule" "test" { `, rName) } -func testAccVPCSecurityGroupRuleConfig_multidescription(rInt int, rType string) string { - var b bytes.Buffer - b.WriteString(fmt.Sprintf(` -resource "aws_vpc" "tf_sgrule_description_test" { +func testAccVPCSecurityGroupRuleConfig_multiDescription(rName, ruleType string) string { + config := fmt.Sprintf(` +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-security-group-rule-multi-desc" + Name = %[1]q } } -data "aws_region" "current" {} - -resource "aws_vpc_endpoint" "s3_endpoint" { - vpc_id = aws_vpc.tf_sgrule_description_test.id - service_name = "com.amazonaws.${data.aws_region.current.name}.s3" -} - -resource "aws_security_group" "worker" { - name = "terraform_test_%[1]d" - vpc_id = aws_vpc.tf_sgrule_description_test.id - description = "Used in the terraform acceptance tests" - - tags = { Name = "tf-sg-rule-description" } -} +resource "aws_security_group" "test" { + count = 2 -resource "aws_security_group" "nat" { - name = "terraform_test_%[1]d_nat" - vpc_id = aws_vpc.tf_sgrule_description_test.id - description = "Used in the terraform acceptance tests" + name = "%[1]s-${count.index}" + vpc_id = aws_vpc.test.id - tags = { Name = "tf-sg-rule-description" } + tags = { + Name = %[1]q + } } -resource "aws_security_group_rule" "rule_1" { - security_group_id = aws_security_group.worker.id +resource "aws_security_group_rule" "test1" { + security_group_id = aws_security_group.test[0].id description = "CIDR Description" - type = "%[2]s" + type = %[2]q protocol = "tcp" from_port = 22 to_port = 22 cidr_blocks = ["0.0.0.0/0"] } -resource "aws_security_group_rule" "rule_2" { - security_group_id = aws_security_group.worker.id +resource "aws_security_group_rule" "test2" { + security_group_id = aws_security_group.test[0].id description = "IPv6 CIDR Description" - type = "%[2]s" + type = %[2]q protocol = "tcp" from_port = 22 to_port = 22 ipv6_cidr_blocks = ["::/0"] } -resource "aws_security_group_rule" "rule_3" { - security_group_id = aws_security_group.worker.id - description = "NAT SG Description" - type = "%[2]s" +resource "aws_security_group_rule" "test3" { + security_group_id = aws_security_group.test[0].id + description = "Third Description" + type = %[2]q protocol = "tcp" from_port = 22 to_port = 22 - source_security_group_id = aws_security_group.nat.id + source_security_group_id = aws_security_group.test[1].id +} +`, rName, ruleType) + + if ruleType == "egress" { + config = acctest.ConfigCompose(config, fmt.Sprintf(` +data "aws_region" "current" {} + +resource "aws_vpc_endpoint" "test" { + vpc_id = aws_vpc.test.id + service_name = "com.amazonaws.${data.aws_region.current.name}.s3" + + tags = { + Name = %[1]q + } } -`, rInt, rType)) - if rType == "egress" { - b.WriteString(` -resource "aws_security_group_rule" "rule_4" { - security_group_id = aws_security_group.worker.id +resource "aws_security_group_rule" "test4" { + security_group_id = aws_security_group.test[0].id description = "Prefix List Description" - type = "egress" + type = %[2]q protocol = "tcp" from_port = 22 to_port = 22 - prefix_list_ids = [aws_vpc_endpoint.s3_endpoint.prefix_list_id] + prefix_list_ids = [aws_vpc_endpoint.test.prefix_list_id] } -`) +`, rName, ruleType)) } - return b.String() + return config } // check for GH-1985 regression From a1985b784af92a2f44924b550f27e802aa59141d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 12:07:52 -0400 Subject: [PATCH 079/120] 'sgProtocolIntegers()' -> 'securityGroupProtocolIntegers'. --- internal/service/ec2/vpc_security_group.go | 18 ++++++++---------- .../service/ec2/vpc_security_group_rule.go | 2 +- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index b71c1def4aaa..660ef32c2ab7 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -1213,7 +1213,7 @@ func ProtocolForValue(v string) string { return "-1" } // if it's a name like tcp, return that - if _, ok := sgProtocolIntegers()[protocol]; ok { + if _, ok := securityGroupProtocolIntegers[protocol]; ok { return protocol } // convert to int, look for that value @@ -1225,7 +1225,7 @@ func ProtocolForValue(v string) string { return protocol } - for k, v := range sgProtocolIntegers() { + for k, v := range securityGroupProtocolIntegers { if p == v { // guard against protocolIntegers sometime in the future not having lower // case ids in the map @@ -1244,14 +1244,12 @@ func ProtocolForValue(v string) string { // http://docs.aws.amazon.com/fr_fr/AWSEC2/latest/APIReference/API_IpPermission.html // Similar to protocolIntegers() used by Network ACLs, but explicitly only // supports "tcp", "udp", "icmp", "icmpv6", and "all" -func sgProtocolIntegers() map[string]int { - return map[string]int{ - "icmpv6": 58, - "udp": 17, - "tcp": 6, - "icmp": 1, - "all": -1, - } +var securityGroupProtocolIntegers = map[string]int{ + "icmpv6": 58, + "udp": 17, + "tcp": 6, + "icmp": 1, + "all": -1, } // The AWS Lambda service creates ENIs behind the scenes and keeps these around for a while diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index f8b54392342b..4a43ce6d829a 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -920,7 +920,7 @@ func validateSecurityGroupRuleImportString(importStr string) ([]string, error) { return nil, fmt.Errorf(errStr, importStr, "expecting 'ingress' or 'egress'") } - if _, ok := sgProtocolIntegers()[protocol]; !ok { + if _, ok := securityGroupProtocolIntegers[protocol]; !ok { if _, err := strconv.Atoi(protocol); err != nil { return nil, fmt.Errorf(errStr, importStr, "protocol must be tcp/udp/icmp/icmpv6/all or a number") } From ffb801b6c5f87b4fecc34fd2f3693092fa154da7 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 12:20:10 -0400 Subject: [PATCH 080/120] r/aws_route_table: Use 'tfresource.RetryWhenNotFound' and 'tfresource.RetryUntilNotFound'. --- internal/service/ec2/status.go | 20 -------------- internal/service/ec2/vpc_route_table.go | 18 ++++++++----- internal/service/ec2/wait.go | 35 ------------------------- 3 files changed, 12 insertions(+), 61 deletions(-) diff --git a/internal/service/ec2/status.go b/internal/service/ec2/status.go index 63517bf5e1a2..d560ddfe9b35 100644 --- a/internal/service/ec2/status.go +++ b/internal/service/ec2/status.go @@ -386,26 +386,6 @@ func StatusRoute(conn *ec2.EC2, routeFinder RouteFinder, routeTableID, destinati } } -const ( - RouteTableStatusReady = "ready" -) - -func StatusRouteTable(conn *ec2.EC2, id string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := FindRouteTableByID(conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, RouteTableStatusReady, nil - } -} - func StatusRouteTableAssociationState(conn *ec2.EC2, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { output, err := FindRouteTableAssociationByID(conn, id) diff --git a/internal/service/ec2/vpc_route_table.go b/internal/service/ec2/vpc_route_table.go index 5a7b5d36ac6b..b468c9716abc 100644 --- a/internal/service/ec2/vpc_route_table.go +++ b/internal/service/ec2/vpc_route_table.go @@ -185,8 +185,12 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(aws.StringValue(output.RouteTable.RouteTableId)) - if _, err := WaitRouteTableReady(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("error waiting for Route Table (%s) to become available: %w", d.Id(), err) + _, err = tfresource.RetryWhenNotFound(d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { + return FindRouteTableByID(conn, d.Id()) + }) + + if err != nil { + return fmt.Errorf("error waiting for Route Table (%s) create: %w", d.Id(), err) } if v, ok := d.GetOk("propagating_vgws"); ok && v.(*schema.Set).Len() > 0 { @@ -398,10 +402,12 @@ func resourceRouteTableDelete(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error deleting Route Table (%s): %w", d.Id(), err) } - // Wait for the route table to really destroy - log.Printf("[DEBUG] Waiting for route table (%s) deletion", d.Id()) - if _, err := WaitRouteTableDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for Route Table (%s) deletion: %w", d.Id(), err) + _, err = tfresource.RetryUntilNotFound(d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { + return FindRouteTableByID(conn, d.Id()) + }) + + if err != nil { + return fmt.Errorf("error waiting for Route Table (%s) delete: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/wait.go b/internal/service/ec2/wait.go index 7e9c9c54535a..841f05a93c59 100644 --- a/internal/service/ec2/wait.go +++ b/internal/service/ec2/wait.go @@ -696,41 +696,6 @@ const ( RouteTableAssociationDeletedTimeout = 5 * time.Minute ) -func WaitRouteTableReady(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.RouteTable, error) { - stateConf := &resource.StateChangeConf{ - Pending: []string{}, - Target: []string{RouteTableStatusReady}, - Refresh: StatusRouteTable(conn, id), - Timeout: timeout, - NotFoundChecks: RouteTableNotFoundChecks, - } - - outputRaw, err := stateConf.WaitForState() - - if output, ok := outputRaw.(*ec2.RouteTable); ok { - return output, err - } - - return nil, err -} - -func WaitRouteTableDeleted(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.RouteTable, error) { - stateConf := &resource.StateChangeConf{ - Pending: []string{RouteTableStatusReady}, - Target: []string{}, - Refresh: StatusRouteTable(conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForState() - - if output, ok := outputRaw.(*ec2.RouteTable); ok { - return output, err - } - - return nil, err -} - func WaitRouteTableAssociationCreated(conn *ec2.EC2, id string) (*ec2.RouteTableAssociationState, error) { stateConf := &resource.StateChangeConf{ Pending: []string{ec2.RouteTableAssociationStateCodeAssociating}, From 6c50d7b1dae214c82da3b78827ba6be892365afc Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 30 Jun 2022 12:21:44 -0400 Subject: [PATCH 081/120] Revert "r/aws_route_table: Use 'tfresource.RetryWhenNotFound' and 'tfresource.RetryUntilNotFound'." This reverts commit ffb801b6c5f87b4fecc34fd2f3693092fa154da7. --- internal/service/ec2/status.go | 20 ++++++++++++++ internal/service/ec2/vpc_route_table.go | 18 +++++-------- internal/service/ec2/wait.go | 35 +++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/internal/service/ec2/status.go b/internal/service/ec2/status.go index d560ddfe9b35..63517bf5e1a2 100644 --- a/internal/service/ec2/status.go +++ b/internal/service/ec2/status.go @@ -386,6 +386,26 @@ func StatusRoute(conn *ec2.EC2, routeFinder RouteFinder, routeTableID, destinati } } +const ( + RouteTableStatusReady = "ready" +) + +func StatusRouteTable(conn *ec2.EC2, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := FindRouteTableByID(conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, RouteTableStatusReady, nil + } +} + func StatusRouteTableAssociationState(conn *ec2.EC2, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { output, err := FindRouteTableAssociationByID(conn, id) diff --git a/internal/service/ec2/vpc_route_table.go b/internal/service/ec2/vpc_route_table.go index b468c9716abc..5a7b5d36ac6b 100644 --- a/internal/service/ec2/vpc_route_table.go +++ b/internal/service/ec2/vpc_route_table.go @@ -185,12 +185,8 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(aws.StringValue(output.RouteTable.RouteTableId)) - _, err = tfresource.RetryWhenNotFound(d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { - return FindRouteTableByID(conn, d.Id()) - }) - - if err != nil { - return fmt.Errorf("error waiting for Route Table (%s) create: %w", d.Id(), err) + if _, err := WaitRouteTableReady(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + return fmt.Errorf("error waiting for Route Table (%s) to become available: %w", d.Id(), err) } if v, ok := d.GetOk("propagating_vgws"); ok && v.(*schema.Set).Len() > 0 { @@ -402,12 +398,10 @@ func resourceRouteTableDelete(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error deleting Route Table (%s): %w", d.Id(), err) } - _, err = tfresource.RetryUntilNotFound(d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { - return FindRouteTableByID(conn, d.Id()) - }) - - if err != nil { - return fmt.Errorf("error waiting for Route Table (%s) delete: %w", d.Id(), err) + // Wait for the route table to really destroy + log.Printf("[DEBUG] Waiting for route table (%s) deletion", d.Id()) + if _, err := WaitRouteTableDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return fmt.Errorf("error waiting for Route Table (%s) deletion: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/wait.go b/internal/service/ec2/wait.go index 841f05a93c59..7e9c9c54535a 100644 --- a/internal/service/ec2/wait.go +++ b/internal/service/ec2/wait.go @@ -696,6 +696,41 @@ const ( RouteTableAssociationDeletedTimeout = 5 * time.Minute ) +func WaitRouteTableReady(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.RouteTable, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{}, + Target: []string{RouteTableStatusReady}, + Refresh: StatusRouteTable(conn, id), + Timeout: timeout, + NotFoundChecks: RouteTableNotFoundChecks, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.RouteTable); ok { + return output, err + } + + return nil, err +} + +func WaitRouteTableDeleted(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.RouteTable, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{RouteTableStatusReady}, + Target: []string{}, + Refresh: StatusRouteTable(conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.RouteTable); ok { + return output, err + } + + return nil, err +} + func WaitRouteTableAssociationCreated(conn *ec2.EC2, id string) (*ec2.RouteTableAssociationState, error) { stateConf := &resource.StateChangeConf{ Pending: []string{ec2.RouteTableAssociationStateCodeAssociating}, From 54b0c3c89450a2e7b579bf9244cc7df02fdafafe Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 1 Jul 2022 14:35:06 -0400 Subject: [PATCH 082/120] Add 'securityGroupRuleTypeIngress' and 'securityGroupRuleTypeEgress'. --- internal/service/ec2/consts.go | 12 ++++ .../service/ec2/vpc_security_group_rule.go | 64 +++++++++---------- 2 files changed, 43 insertions(+), 33 deletions(-) diff --git a/internal/service/ec2/consts.go b/internal/service/ec2/consts.go index 7e24d9bf34b4..89e273860632 100644 --- a/internal/service/ec2/consts.go +++ b/internal/service/ec2/consts.go @@ -249,3 +249,15 @@ func outsideIPAddressType_Values() []string { OutsideIPAddressTypePublicIPv4, } } + +const ( + securityGroupRuleTypeEgress = "egress" + securityGroupRuleTypeIngress = "ingress" +) + +func securityGroupRuleType_Values() []string { + return []string{ + securityGroupRuleTypeEgress, + securityGroupRuleTypeIngress, + } +} diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 4a43ce6d829a..560297b2375a 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -129,14 +129,10 @@ func ResourceSecurityGroupRule() *schema.Resource { }, }, "type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - Description: "Type of rule, ingress (inbound) or egress (outbound).", - ValidateFunc: validation.StringInSlice([]string{ - "ingress", - "egress", - }, false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(securityGroupRuleType_Values(), false), }, }, } @@ -144,17 +140,19 @@ func ResourceSecurityGroupRule() *schema.Resource { func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - sg_id := d.Get("security_group_id").(string) + securityGroupID := d.Get("security_group_id").(string) - conns.GlobalMutexKV.Lock(sg_id) - defer conns.GlobalMutexKV.Unlock(sg_id) + conns.GlobalMutexKV.Lock(securityGroupID) + defer conns.GlobalMutexKV.Unlock(securityGroupID) + + sg, err := FindSecurityGroupByID(conn, securityGroupID) - sg, err := FindSecurityGroupByID(conn, sg_id) if err != nil { - return err + return fmt.Errorf("reading Security Group (%s): %w", securityGroupID, err) } perm, err := expandIPPerm(d, sg) + if err != nil { return err } @@ -172,9 +170,9 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e var autherr error switch ruleType { - case "ingress": + case securityGroupRuleTypeIngress: log.Printf("[DEBUG] Authorizing security group %s %s rule: %s", - sg_id, "Ingress", perm) + securityGroupID, "Ingress", perm) req := &ec2.AuthorizeSecurityGroupIngressInput{ GroupId: sg.GroupId, @@ -188,9 +186,9 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e _, autherr = conn.AuthorizeSecurityGroupIngress(req) - case "egress": + case securityGroupRuleTypeEgress: log.Printf("[DEBUG] Authorizing security group %s %s rule: %#v", - sg_id, "Egress", perm) + securityGroupID, "Egress", perm) req := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: sg.GroupId, @@ -208,26 +206,26 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e a side effect of a now-fixed Terraform issue causing two security groups with identical attributes but different source_security_group_ids to overwrite each other in the state. See https://github.com/hashicorp/terraform/pull/2376 for more -information and instructions for recovery. Error: %w`, sg_id, autherr) +information and instructions for recovery. Error: %w`, securityGroupID, autherr) } if autherr != nil { return fmt.Errorf("Error authorizing security group rule type %s: %w", ruleType, autherr) } var rules []*ec2.IpPermission - id := IPPermissionIDHash(sg_id, ruleType, perm) + id := IPPermissionIDHash(securityGroupID, ruleType, perm) log.Printf("[DEBUG] Computed group rule ID %s", id) err = resource.Retry(5*time.Minute, func() *resource.RetryError { - sg, err := FindSecurityGroupByID(conn, sg_id) + sg, err := FindSecurityGroupByID(conn, securityGroupID) if err != nil { - log.Printf("[DEBUG] Error finding Security Group (%s) for Rule (%s): %s", sg_id, id, err) + log.Printf("[DEBUG] Error finding Security Group (%s) for Rule (%s): %s", securityGroupID, id, err) return resource.NonRetryableError(err) } switch ruleType { - case "ingress": + case securityGroupRuleTypeIngress: rules = sg.IpPermissions default: rules = sg.IpPermissionsEgress @@ -236,7 +234,7 @@ information and instructions for recovery. Error: %w`, sg_id, autherr) rule := findRuleMatch(perm, rules, isVPC) if rule == nil { log.Printf("[DEBUG] Unable to find matching %s Security Group Rule (%s) for Group %s", - ruleType, id, sg_id) + ruleType, id, securityGroupID) return resource.RetryableError(fmt.Errorf("No match found")) } @@ -244,13 +242,13 @@ information and instructions for recovery. Error: %w`, sg_id, autherr) return nil }) if tfresource.TimedOut(err) { - sg, err := FindSecurityGroupByID(conn, sg_id) + sg, err := FindSecurityGroupByID(conn, securityGroupID) if err != nil { return fmt.Errorf("Error finding security group: %w", err) } switch ruleType { - case "ingress": + case securityGroupRuleTypeIngress: rules = sg.IpPermissions default: rules = sg.IpPermissionsEgress @@ -262,7 +260,7 @@ information and instructions for recovery. Error: %w`, sg_id, autherr) } } if err != nil { - return fmt.Errorf("Error finding matching %s Security Group Rule (%s) for Group %s", ruleType, id, sg_id) + return fmt.Errorf("Error finding matching %s Security Group Rule (%s) for Group %s", ruleType, id, securityGroupID) } d.SetId(id) @@ -288,7 +286,7 @@ func resourceSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) err var rules []*ec2.IpPermission ruleType := d.Get("type").(string) switch ruleType { - case "ingress": + case securityGroupRuleTypeIngress: rules = sg.IpPermissions default: rules = sg.IpPermissionsEgress @@ -361,7 +359,7 @@ func resourceSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) e } ruleType := d.Get("type").(string) switch ruleType { - case "ingress": + case securityGroupRuleTypeIngress: log.Printf("[DEBUG] Revoking rule (%s) from security group %s:\n%s", "ingress", sg_id, perm) req := &ec2.RevokeSecurityGroupIngressInput{ @@ -374,7 +372,7 @@ func resourceSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) e if err != nil { return fmt.Errorf("Error revoking security group %s rules: %w", sg_id, err) } - case "egress": + case securityGroupRuleTypeEgress: log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v", sg_id, "egress", perm) req := &ec2.RevokeSecurityGroupEgressInput{ @@ -861,7 +859,7 @@ func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.Resourc } ruleType := d.Get("type").(string) switch ruleType { - case "ingress": + case securityGroupRuleTypeIngress: req := &ec2.UpdateSecurityGroupRuleDescriptionsIngressInput{ GroupId: sg.GroupId, IpPermissions: []*ec2.IpPermission{perm}, @@ -872,7 +870,7 @@ func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.Resourc if err != nil { return fmt.Errorf("Error updating security group %s rule description: %w", sg_id, err) } - case "egress": + case securityGroupRuleTypeEgress: req := &ec2.UpdateSecurityGroupRuleDescriptionsEgressInput{ GroupId: sg.GroupId, IpPermissions: []*ec2.IpPermission{perm}, @@ -916,7 +914,7 @@ func validateSecurityGroupRuleImportString(importStr string) ([]string, error) { return nil, fmt.Errorf(errStr, importStr, "invalid security group ID") } - if ruleType != "ingress" && ruleType != "egress" { + if ruleType != securityGroupRuleTypeIngress && ruleType != securityGroupRuleTypeEgress { return nil, fmt.Errorf(errStr, importStr, "expecting 'ingress' or 'egress'") } @@ -972,7 +970,7 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s d.Set("security_group_id", sgID) - if ruleType == "ingress" { + if ruleType == securityGroupRuleTypeIngress { d.Set("type", ruleType) } else { d.Set("type", "egress") From 749388309a348042426306024914197ddb8def91 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 1 Jul 2022 14:44:26 -0400 Subject: [PATCH 083/120] Remove 'validSecurityGroupRule'. --- .../service/ec2/vpc_security_group_rule.go | 39 +++++-------------- 1 file changed, 9 insertions(+), 30 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 560297b2375a..fb6107d43a3b 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -55,6 +55,7 @@ func ResourceSecurityGroupRule() *schema.Resource { ValidateFunc: verify.ValidCIDRNetworkAddress, }, ConflictsWith: []string{"source_security_group_id", "self"}, + AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, }, "description": { Type: schema.TypeString, @@ -83,12 +84,14 @@ func ResourceSecurityGroupRule() *schema.Resource { ValidateFunc: verify.ValidCIDRNetworkAddress, }, ConflictsWith: []string{"source_security_group_id", "self"}, + AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, }, "prefix_list_ids": { - Type: schema.TypeList, - Optional: true, - ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, }, "protocol": { Type: schema.TypeString, @@ -107,6 +110,7 @@ func ResourceSecurityGroupRule() *schema.Resource { Default: false, ForceNew: true, ConflictsWith: []string{"cidr_blocks", "ipv6_cidr_blocks", "source_security_group_id"}, + AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, }, "source_security_group_id": { Type: schema.TypeString, @@ -114,6 +118,7 @@ func ResourceSecurityGroupRule() *schema.Resource { ForceNew: true, Computed: true, ConflictsWith: []string{"cidr_blocks", "ipv6_cidr_blocks", "self"}, + AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, }, "to_port": { Type: schema.TypeInt, @@ -157,14 +162,6 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e return err } - // Verify that either 'cidr_blocks', 'self', or 'source_security_group_id' is set - // If they are not set the AWS API will silently fail. This causes TF to hit a timeout - // at 5-minutes waiting for the security group rule to appear, when it was never actually - // created. - if err := validSecurityGroupRule(d); err != nil { - return err - } - ruleType := d.Get("type").(string) isVPC := aws.StringValue(sg.VpcId) != "" @@ -824,24 +821,6 @@ func descriptionFromIPPerm(d *schema.ResourceData, rule *ec2.IpPermission) strin return "" } -// Validates that either 'cidr_blocks', 'ipv6_cidr_blocks', 'self', or 'source_security_group_id' is set -func validSecurityGroupRule(d *schema.ResourceData) error { - blocks, blocksOk := d.GetOk("cidr_blocks") - self, selfOk := d.GetOk("self") - if blocksOk && self.(bool) { - return fmt.Errorf("'self': conflicts with 'cidr_blocks' (%#v)", blocks) - } - - _, ipv6Ok := d.GetOk("ipv6_cidr_blocks") - _, sourceOk := d.GetOk("source_security_group_id") - _, prefixOk := d.GetOk("prefix_list_ids") - if !blocksOk && !sourceOk && !selfOk && !prefixOk && !ipv6Ok { - return fmt.Errorf( - "One of ['cidr_blocks', 'ipv6_cidr_blocks', 'self', 'source_security_group_id', 'prefix_list_ids'] must be set to create an AWS Security Group Rule") - } - return nil -} - func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.ResourceData) error { sg_id := d.Get("security_group_id").(string) From 97155fd4bbf7883fa245ee0c6451ca6e022b24fe Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 1 Jul 2022 16:33:20 -0400 Subject: [PATCH 084/120] r/aws_security_group_rule: Tidy up resource Create. --- .../service/ec2/vpc_security_group_rule.go | 226 ++++++++++++------ .../ec2/vpc_security_group_rule_test.go | 2 +- 2 files changed, 148 insertions(+), 80 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index fb6107d43a3b..34859217e71b 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -156,111 +156,80 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("reading Security Group (%s): %w", securityGroupID, err) } - perm, err := expandIPPerm(d, sg) - - if err != nil { - return err - } - + ipPermission := expandIpPermission(d, sg) ruleType := d.Get("type").(string) isVPC := aws.StringValue(sg.VpcId) != "" - var autherr error switch ruleType { case securityGroupRuleTypeIngress: - log.Printf("[DEBUG] Authorizing security group %s %s rule: %s", - securityGroupID, "Ingress", perm) - - req := &ec2.AuthorizeSecurityGroupIngressInput{ - GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{perm}, + input := &ec2.AuthorizeSecurityGroupIngressInput{ + IpPermissions: []*ec2.IpPermission{ipPermission}, } - if !isVPC { - req.GroupId = nil - req.GroupName = sg.GroupName + if isVPC { + input.GroupId = sg.GroupId + } else { + input.GroupName = sg.GroupName } - _, autherr = conn.AuthorizeSecurityGroupIngress(req) + _, err = conn.AuthorizeSecurityGroupIngress(input) case securityGroupRuleTypeEgress: - log.Printf("[DEBUG] Authorizing security group %s %s rule: %#v", - securityGroupID, "Egress", perm) - - req := &ec2.AuthorizeSecurityGroupEgressInput{ + input := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{perm}, + IpPermissions: []*ec2.IpPermission{ipPermission}, } - _, autherr = conn.AuthorizeSecurityGroupEgress(req) + _, err = conn.AuthorizeSecurityGroupEgress(input) default: - return fmt.Errorf("Security Group Rule must be type 'ingress' or type 'egress'") + return fmt.Errorf("invalid Security Group Rule type: %s", ruleType) } - if tfawserr.ErrCodeEquals(autherr, errCodeInvalidPermissionDuplicate) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidPermissionDuplicate) { return fmt.Errorf(`[WARN] A duplicate Security Group rule was found on (%s). This may be a side effect of a now-fixed Terraform issue causing two security groups with identical attributes but different source_security_group_ids to overwrite each other in the state. See https://github.com/hashicorp/terraform/pull/2376 for more -information and instructions for recovery. Error: %w`, securityGroupID, autherr) +information and instructions for recovery. Error: %w`, securityGroupID, err) } - if autherr != nil { - return fmt.Errorf("Error authorizing security group rule type %s: %w", ruleType, autherr) + + if err != nil { + return fmt.Errorf("authorizing Security Group (%s) Rule (%s): %w", securityGroupID, ruleType, err) } - var rules []*ec2.IpPermission - id := IPPermissionIDHash(securityGroupID, ruleType, perm) - log.Printf("[DEBUG] Computed group rule ID %s", id) + id := IPPermissionIDHash(securityGroupID, ruleType, ipPermission) - err = resource.Retry(5*time.Minute, func() *resource.RetryError { + _, err = tfresource.RetryWhenNotFound(5*time.Minute, func() (interface{}, error) { sg, err := FindSecurityGroupByID(conn, securityGroupID) if err != nil { - log.Printf("[DEBUG] Error finding Security Group (%s) for Rule (%s): %s", securityGroupID, id, err) - return resource.NonRetryableError(err) + return nil, err } - switch ruleType { - case securityGroupRuleTypeIngress: + var rules []*ec2.IpPermission + + if ruleType == securityGroupRuleTypeIngress { rules = sg.IpPermissions - default: + } else { rules = sg.IpPermissionsEgress } - rule := findRuleMatch(perm, rules, isVPC) + rule := findRuleMatch(ipPermission, rules, isVPC) + if rule == nil { - log.Printf("[DEBUG] Unable to find matching %s Security Group Rule (%s) for Group %s", - ruleType, id, securityGroupID) - return resource.RetryableError(fmt.Errorf("No match found")) + return nil, &resource.NotFoundError{} } - log.Printf("[DEBUG] Found rule for Security Group Rule (%s): %s", id, rule) - return nil + return rule, nil }) - if tfresource.TimedOut(err) { - sg, err := FindSecurityGroupByID(conn, securityGroupID) - if err != nil { - return fmt.Errorf("Error finding security group: %w", err) - } - - switch ruleType { - case securityGroupRuleTypeIngress: - rules = sg.IpPermissions - default: - rules = sg.IpPermissionsEgress - } - rule := findRuleMatch(perm, rules, isVPC) - if rule == nil { - return fmt.Errorf("Error finding matching security group rule: %w", err) - } - } if err != nil { - return fmt.Errorf("Error finding matching %s Security Group Rule (%s) for Group %s", ruleType, id, securityGroupID) + return fmt.Errorf("waiting for Security Group (%s) Rule (%s): %w", securityGroupID, id, err) } d.SetId(id) + return nil } @@ -407,6 +376,7 @@ func (b ByGroupPair) Less(i, j int) bool { func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) *ec2.IpPermission { var rule *ec2.IpPermission + for _, r := range rules { if p.ToPort != nil && r.ToPort != nil && aws.Int64Value(p.ToPort) != aws.Int64Value(r.ToPort) { continue @@ -421,12 +391,12 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } remaining := len(p.IpRanges) - for _, ip := range p.IpRanges { - for _, rip := range r.IpRanges { - if ip.CidrIp == nil || rip.CidrIp == nil { + for _, v1 := range p.IpRanges { + for _, v2 := range r.IpRanges { + if v1.CidrIp == nil || v2.CidrIp == nil { continue } - if aws.StringValue(ip.CidrIp) == aws.StringValue(rip.CidrIp) { + if aws.StringValue(v1.CidrIp) == aws.StringValue(v2.CidrIp) { remaining-- } } @@ -437,12 +407,12 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } remaining = len(p.Ipv6Ranges) - for _, ipv6 := range p.Ipv6Ranges { - for _, ipv6ip := range r.Ipv6Ranges { - if ipv6.CidrIpv6 == nil || ipv6ip.CidrIpv6 == nil { + for _, v1 := range p.Ipv6Ranges { + for _, v2 := range r.Ipv6Ranges { + if v1.CidrIpv6 == nil || v2.CidrIpv6 == nil { continue } - if aws.StringValue(ipv6.CidrIpv6) == aws.StringValue(ipv6ip.CidrIpv6) { + if aws.StringValue(v1.CidrIpv6) == aws.StringValue(v2.CidrIpv6) { remaining-- } } @@ -453,12 +423,12 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } remaining = len(p.PrefixListIds) - for _, pl := range p.PrefixListIds { - for _, rpl := range r.PrefixListIds { - if pl.PrefixListId == nil || rpl.PrefixListId == nil { + for _, v1 := range p.PrefixListIds { + for _, v2 := range r.PrefixListIds { + if v1.PrefixListId == nil || v2.PrefixListId == nil { continue } - if aws.StringValue(pl.PrefixListId) == aws.StringValue(rpl.PrefixListId) { + if aws.StringValue(v1.PrefixListId) == aws.StringValue(v2.PrefixListId) { remaining-- } } @@ -469,20 +439,20 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } remaining = len(p.UserIdGroupPairs) - for _, ip := range p.UserIdGroupPairs { - for _, rip := range r.UserIdGroupPairs { + for _, v1 := range p.UserIdGroupPairs { + for _, v2 := range r.UserIdGroupPairs { if isVPC { - if ip.GroupId == nil || rip.GroupId == nil { + if v1.GroupId == nil || v2.GroupId == nil { continue } - if aws.StringValue(ip.GroupId) == aws.StringValue(rip.GroupId) { + if aws.StringValue(v1.GroupId) == aws.StringValue(v2.GroupId) { remaining-- } } else { - if ip.GroupName == nil || rip.GroupName == nil { + if v1.GroupName == nil || v2.GroupName == nil { continue } - if aws.StringValue(ip.GroupName) == aws.StringValue(rip.GroupName) { + if aws.StringValue(v1.GroupName) == aws.StringValue(v2.GroupName) { remaining-- } } @@ -495,6 +465,7 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * rule = r } + return rule } @@ -982,3 +953,100 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s return nil } + +func expandIpPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPermission { // nosemgrep:caps5-in-func-name + apiObject := &ec2.IpPermission{ + IpProtocol: aws.String(ProtocolForValue(d.Get("protocol").(string))), + } + + // InvalidParameterValue: When protocol is ALL, you cannot specify from-port. + if v := aws.StringValue(apiObject.IpProtocol); v != "-1" { + apiObject.FromPort = aws.Int64(int64(d.Get("from_port").(int))) + apiObject.ToPort = aws.Int64(int64(d.Get("to_port").(int))) + } + + if v, ok := d.GetOk("cidr_blocks"); ok && len(v.([]interface{})) > 0 { + for _, v := range v.([]interface{}) { + apiObject.IpRanges = append(apiObject.IpRanges, &ec2.IpRange{ + CidrIp: aws.String(v.(string)), + }) + } + } + + if v, ok := d.GetOk("ipv6_cidr_blocks"); ok && len(v.([]interface{})) > 0 { + for _, v := range v.([]interface{}) { + apiObject.Ipv6Ranges = append(apiObject.Ipv6Ranges, &ec2.Ipv6Range{ + CidrIpv6: aws.String(v.(string)), + }) + } + } + + if v, ok := d.GetOk("prefix_list_ids"); ok && len(v.([]interface{})) > 0 { + for _, v := range v.([]interface{}) { + apiObject.PrefixListIds = append(apiObject.PrefixListIds, &ec2.PrefixListId{ + PrefixListId: aws.String(v.(string)), + }) + } + } + + var self string + vpc := aws.StringValue(sg.VpcId) != "" + + if _, ok := d.GetOk("self"); ok { + if vpc { + self = aws.StringValue(sg.GroupId) + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + GroupId: aws.String(self), + }) + } else { + self = aws.StringValue(sg.GroupName) + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + GroupName: aws.String(self), + }) + } + } + + if v, ok := d.GetOk("source_security_group_id"); ok { + if v := v.(string); v != self { + if vpc { + // [OwnerID/]SecurityGroupID. + if parts := strings.Split(v, "/"); len(parts) == 1 { + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + GroupId: aws.String(v), + }) + } else { + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + GroupId: aws.String(parts[1]), + UserId: aws.String(parts[0]), + }) + } + } else { + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + GroupName: aws.String(v), + }) + } + } + } + + if v, ok := d.GetOk("description"); ok { + description := v.(string) + + for _, v := range apiObject.IpRanges { + v.Description = aws.String(description) + } + + for _, v := range apiObject.Ipv6Ranges { + v.Description = aws.String(description) + } + + for _, v := range apiObject.PrefixListIds { + v.Description = aws.String(description) + } + + for _, v := range apiObject.UserIdGroupPairs { + v.Description = aws.String(description) + } + } + + return apiObject +} diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 4d9dadb38fa1..1362b19a5f19 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -432,7 +432,7 @@ func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_expectInvalidType(rName), - ExpectError: regexp.MustCompile(`expected type to be one of \[ingress egress\]`), + ExpectError: regexp.MustCompile(`expected type to be one of \[egress ingress\]`), }, }, }) From cf2d36c0062edf8acebd37224c111e98865fda37 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 1 Jul 2022 16:37:43 -0400 Subject: [PATCH 085/120] Use 'verify.ValidIPv4CIDRNetworkAddress' and 'verify.ValidIPv6CIDRNetworkAddress'. --- internal/service/ec2/vpc_security_group_rule.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 34859217e71b..b28709bc84fb 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -52,7 +52,7 @@ func ResourceSecurityGroupRule() *schema.Resource { ForceNew: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, + ValidateFunc: verify.ValidIPv4CIDRNetworkAddress, }, ConflictsWith: []string{"source_security_group_id", "self"}, AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, @@ -81,7 +81,7 @@ func ResourceSecurityGroupRule() *schema.Resource { ForceNew: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, + ValidateFunc: verify.ValidIPv6CIDRNetworkAddress, }, ConflictsWith: []string{"source_security_group_id", "self"}, AtLeastOneOf: []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", "self", "source_security_group_id"}, From e457f723cf53fedcdd27562a72d5ddeeb43d325d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 1 Jul 2022 16:49:57 -0400 Subject: [PATCH 086/120] r/aws_security_group_rule: Tidy up resource Delete. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroupRule_ -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_vpc === PAUSE TestAccVPCSecurityGroupRule_Ingress_vpc === RUN TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === PAUSE TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === RUN TestAccVPCSecurityGroupRule_Ingress_protocol === PAUSE TestAccVPCSecurityGroupRule_Ingress_protocol === RUN TestAccVPCSecurityGroupRule_Ingress_icmpv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_icmpv6 === RUN TestAccVPCSecurityGroupRule_Ingress_ipv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv6 === RUN TestAccVPCSecurityGroupRule_Ingress_classic === PAUSE TestAccVPCSecurityGroupRule_Ingress_classic === RUN TestAccVPCSecurityGroupRule_egress === PAUSE TestAccVPCSecurityGroupRule_egress === RUN TestAccVPCSecurityGroupRule_selfReference === PAUSE TestAccVPCSecurityGroupRule_selfReference === RUN TestAccVPCSecurityGroupRule_expectInvalidTypeError === PAUSE TestAccVPCSecurityGroupRule_expectInvalidTypeError === RUN TestAccVPCSecurityGroupRule_expectInvalidCIDR === PAUSE TestAccVPCSecurityGroupRule_expectInvalidCIDR === RUN TestAccVPCSecurityGroupRule_PartialMatching_basic === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_basic === RUN TestAccVPCSecurityGroupRule_PartialMatching_source === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_source === RUN TestAccVPCSecurityGroupRule_issue5310 === PAUSE TestAccVPCSecurityGroupRule_issue5310 === RUN TestAccVPCSecurityGroupRule_race === PAUSE TestAccVPCSecurityGroupRule_race === RUN TestAccVPCSecurityGroupRule_selfSource === PAUSE TestAccVPCSecurityGroupRule_selfSource === RUN TestAccVPCSecurityGroupRule_prefixListEgress === PAUSE TestAccVPCSecurityGroupRule_prefixListEgress === RUN TestAccVPCSecurityGroupRule_ingressDescription === PAUSE TestAccVPCSecurityGroupRule_ingressDescription === RUN TestAccVPCSecurityGroupRule_egressDescription === PAUSE TestAccVPCSecurityGroupRule_egressDescription === RUN TestAccVPCSecurityGroupRule_IngressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_IngressDescription_updates === RUN TestAccVPCSecurityGroupRule_EgressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_EgressDescription_updates === RUN TestAccVPCSecurityGroupRule_Description_allPorts === PAUSE TestAccVPCSecurityGroupRule_Description_allPorts === RUN TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === PAUSE TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === RUN TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === PAUSE TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === RUN TestAccVPCSecurityGroupRule_multiDescription === PAUSE TestAccVPCSecurityGroupRule_multiDescription === CONT TestAccVPCSecurityGroupRule_Ingress_vpc === CONT TestAccVPCSecurityGroupRule_issue5310 === CONT TestAccVPCSecurityGroupRule_IngressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_issue5310 (19.82s) === CONT TestAccVPCSecurityGroupRule_multiDescription --- PASS: TestAccVPCSecurityGroupRule_Ingress_vpc (21.54s) === CONT TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash --- PASS: TestAccVPCSecurityGroupRule_IngressDescription_updates (33.45s) === CONT TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts --- PASS: TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash (23.03s) === CONT TestAccVPCSecurityGroupRule_Description_allPorts --- PASS: TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts (31.30s) === CONT TestAccVPCSecurityGroupRule_EgressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_Description_allPorts (30.04s) === CONT TestAccVPCSecurityGroupRule_egress --- PASS: TestAccVPCSecurityGroupRule_multiDescription (65.86s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_source --- PASS: TestAccVPCSecurityGroupRule_egress (19.10s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_basic --- PASS: TestAccVPCSecurityGroupRule_EgressDescription_updates (31.75s) === CONT TestAccVPCSecurityGroupRule_expectInvalidCIDR --- PASS: TestAccVPCSecurityGroupRule_expectInvalidCIDR (1.12s) === CONT TestAccVPCSecurityGroupRule_expectInvalidTypeError --- PASS: TestAccVPCSecurityGroupRule_expectInvalidTypeError (0.78s) === CONT TestAccVPCSecurityGroupRule_selfReference --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_source (26.63s) === CONT TestAccVPCSecurityGroupRule_Ingress_icmpv6 --- PASS: TestAccVPCSecurityGroupRule_selfReference (23.42s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv6 --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_basic (29.26s) === CONT TestAccVPCSecurityGroupRule_Ingress_protocol --- PASS: TestAccVPCSecurityGroupRule_Ingress_icmpv6 (22.99s) === CONT TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv6 (22.49s) === CONT TestAccVPCSecurityGroupRule_prefixListEgress --- PASS: TestAccVPCSecurityGroupRule_Ingress_protocol (22.88s) === CONT TestAccVPCSecurityGroupRule_egressDescription --- PASS: TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id (23.31s) === CONT TestAccVPCSecurityGroupRule_ingressDescription --- PASS: TestAccVPCSecurityGroupRule_egressDescription (20.15s) === CONT TestAccVPCSecurityGroupRule_selfSource --- PASS: TestAccVPCSecurityGroupRule_prefixListEgress (33.46s) === CONT TestAccVPCSecurityGroupRule_race --- PASS: TestAccVPCSecurityGroupRule_ingressDescription (19.46s) === CONT TestAccVPCSecurityGroupRule_Ingress_classic --- PASS: TestAccVPCSecurityGroupRule_selfSource (22.98s) --- PASS: TestAccVPCSecurityGroupRule_Ingress_classic (13.40s) --- PASS: TestAccVPCSecurityGroupRule_race (149.33s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 331.559s --- .../service/ec2/vpc_security_group_rule.go | 53 +++++++++---------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index b28709bc84fb..47b3e022d868 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -181,9 +181,6 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e } _, err = conn.AuthorizeSecurityGroupEgress(input) - - default: - return fmt.Errorf("invalid Security Group Rule type: %s", ruleType) } if tfawserr.ErrCodeEquals(err, errCodeInvalidPermissionDuplicate) { @@ -309,48 +306,46 @@ func resourceSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) e func resourceSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - sg_id := d.Get("security_group_id").(string) + securityGroupID := d.Get("security_group_id").(string) - conns.GlobalMutexKV.Lock(sg_id) - defer conns.GlobalMutexKV.Unlock(sg_id) + conns.GlobalMutexKV.Lock(securityGroupID) + defer conns.GlobalMutexKV.Unlock(securityGroupID) - sg, err := FindSecurityGroupByID(conn, sg_id) - if err != nil { - return err - } + sg, err := FindSecurityGroupByID(conn, securityGroupID) - perm, err := expandIPPerm(d, sg) if err != nil { - return err + return fmt.Errorf("reading Security Group (%s): %w", securityGroupID, err) } + + ipPermission := expandIpPermission(d, sg) ruleType := d.Get("type").(string) + isVPC := aws.StringValue(sg.VpcId) != "" + switch ruleType { case securityGroupRuleTypeIngress: - log.Printf("[DEBUG] Revoking rule (%s) from security group %s:\n%s", - "ingress", sg_id, perm) - req := &ec2.RevokeSecurityGroupIngressInput{ - GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{perm}, + input := &ec2.RevokeSecurityGroupIngressInput{ + IpPermissions: []*ec2.IpPermission{ipPermission}, } - _, err = conn.RevokeSecurityGroupIngress(req) - - if err != nil { - return fmt.Errorf("Error revoking security group %s rules: %w", sg_id, err) + if isVPC { + input.GroupId = sg.GroupId + } else { + input.GroupName = sg.GroupName } - case securityGroupRuleTypeEgress: - log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v", sg_id, "egress", perm) - req := &ec2.RevokeSecurityGroupEgressInput{ + _, err = conn.RevokeSecurityGroupIngress(input) + + case securityGroupRuleTypeEgress: + input := &ec2.RevokeSecurityGroupEgressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{perm}, + IpPermissions: []*ec2.IpPermission{ipPermission}, } - _, err = conn.RevokeSecurityGroupEgress(req) + _, err = conn.RevokeSecurityGroupEgress(input) + } - if err != nil { - return fmt.Errorf("Error revoking security group %s rules: %w", sg_id, err) - } + if err != nil { + return fmt.Errorf("revoking Security Group (%s) Rule (%s): %w", securityGroupID, ruleType, err) } return nil From eb6ec42ceb918f11c6488e60eb817457cdf54e93 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 11:45:31 -0400 Subject: [PATCH 087/120] r/aws_security_group_rule: Add 'TestAccVPCSecurityGroupRule_Ingress_multipleIPv6'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_multipleIPv6' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === CONT TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 (22.28s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 26.983s --- .../ec2/vpc_security_group_rule_test.go | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 1362b19a5f19..7eb2f1601a36 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1221,6 +1221,47 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { }) } +func TestAccVPCSecurityGroupRule_Ingress_multipleIPv6(t *testing.T) { + var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCSecurityGroupRuleConfig_ingressMultipleIPv6(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "2"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.0", "2001:db8:85a3::/64"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.1", "2001:db8:85a3:2::/64"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -2080,3 +2121,34 @@ resource "aws_security_group_rule" "test" { } `, rName) } + +func testAccVPCSecurityGroupRuleConfig_ingressMultipleIPv6(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "tftest" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + vpc_id = aws_vpc.tftest.id + name = %[1]q + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group_rule" "test" { + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + ipv6_cidr_blocks = ["2001:db8:85a3::/64", "2001:db8:85a3:2::/64"] + + security_group_id = aws_security_group.test.id +} +`, rName) +} From 57e7d6f25d9bb502694732d7fecb7a37a2015a55 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 11:55:01 -0400 Subject: [PATCH 088/120] r/aws_security_group_rule: Add 'TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === PAUSE TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === CONT TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists --- PASS: TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists (29.89s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 33.908s --- .../ec2/vpc_security_group_rule_test.go | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 7eb2f1601a36..4a8b5b1e49e4 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1262,6 +1262,45 @@ func TestAccVPCSecurityGroupRule_Ingress_multipleIPv6(t *testing.T) { }) } +func TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists(t *testing.T) { + var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckManagedPrefixList(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCSecurityGroupRuleConfig_ingressMultiplePrefixLists(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "2"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -2152,3 +2191,42 @@ resource "aws_security_group_rule" "test" { } `, rName) } + +func testAccVPCSecurityGroupRuleConfig_ingressMultiplePrefixLists(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "tftest" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + vpc_id = aws_vpc.tftest.id + name = %[1]q + + tags = { + Name = %[1]q + } +} + +resource "aws_ec2_managed_prefix_list" "test" { + count = 2 + + address_family = "IPv4" + max_entries = 1 + name = "%[1]s-${count.index}" +} + +resource "aws_security_group_rule" "test" { + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + prefix_list_ids = aws_ec2_managed_prefix_list.test[*].id + + security_group_id = aws_security_group.test.id +} +`, rName) +} From f162ce08cf78033d6cf251ad877d6b5a4660a5a4 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 12:49:16 -0400 Subject: [PATCH 089/120] Fix 'revoking Security Group (sg-0b05b5b814100f939) Rule (ingress): InvalidPermission.NotFound: The specified rule does not exist in this security group'. --- internal/service/ec2/vpc_security_group_rule.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 47b3e022d868..67837bf31077 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -344,6 +344,10 @@ func resourceSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) e _, err = conn.RevokeSecurityGroupEgress(input) } + if tfawserr.ErrCodeEquals(err, errCodeInvalidPermissionNotFound) { + return nil + } + if err != nil { return fmt.Errorf("revoking Security Group (%s) Rule (%s): %w", securityGroupID, ruleType, err) } From 401c088b146c3cd28aa4d326f8c63e80d6078184 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 13:50:59 -0400 Subject: [PATCH 090/120] r/aws_security_group_rule: Add 'TestAccVPCSecurityGroupRule_Ingress_peeredVPC'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_peeredVPC' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_Ingress_peeredVPC -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_peeredVPC === PAUSE TestAccVPCSecurityGroupRule_Ingress_peeredVPC === CONT TestAccVPCSecurityGroupRule_Ingress_peeredVPC --- PASS: TestAccVPCSecurityGroupRule_Ingress_peeredVPC (27.25s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 31.569s --- .../ec2/vpc_security_group_rule_test.go | 135 +++++++++++++++++- 1 file changed, 129 insertions(+), 6 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 4a8b5b1e49e4..7eb79c2562b2 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" @@ -1301,6 +1302,46 @@ func TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists(t *testing.T) { }) } +func TestAccVPCSecurityGroupRule_Ingress_peeredVPC(t *testing.T) { + var group ec2.SecurityGroup + var providers []*schema.Provider + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckAlternateAccount(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.FactoriesAlternate(&providers), + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCSecurityGroupRuleConfig_ingressPeeredVPC(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckResourceAttrSet(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -1419,7 +1460,7 @@ resource "aws_security_group_rule" "test" { func testAccVPCSecurityGroupRuleConfig_ingressIPv6(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "tftest" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { @@ -1428,7 +1469,7 @@ resource "aws_vpc" "tftest" { } resource "aws_security_group" "test" { - vpc_id = aws_vpc.tftest.id + vpc_id = aws_vpc.test.id name = %[1]q tags = { @@ -2163,7 +2204,7 @@ resource "aws_security_group_rule" "test" { func testAccVPCSecurityGroupRuleConfig_ingressMultipleIPv6(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "tftest" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { @@ -2172,7 +2213,7 @@ resource "aws_vpc" "tftest" { } resource "aws_security_group" "test" { - vpc_id = aws_vpc.tftest.id + vpc_id = aws_vpc.test.id name = %[1]q tags = { @@ -2194,7 +2235,7 @@ resource "aws_security_group_rule" "test" { func testAccVPCSecurityGroupRuleConfig_ingressMultiplePrefixLists(rName string) string { return fmt.Sprintf(` -resource "aws_vpc" "tftest" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { @@ -2203,7 +2244,7 @@ resource "aws_vpc" "tftest" { } resource "aws_security_group" "test" { - vpc_id = aws_vpc.tftest.id + vpc_id = aws_vpc.test.id name = %[1]q tags = { @@ -2230,3 +2271,85 @@ resource "aws_security_group_rule" "test" { } `, rName) } + +func testAccVPCSecurityGroupRuleConfig_ingressPeeredVPC(rName string) string { + return acctest.ConfigCompose(acctest.ConfigAlternateAccountProvider(), fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + vpc_id = aws_vpc.test.id + name = %[1]q + + tags = { + Name = %[1]q + } +} + +resource "aws_vpc" "other" { + provider = "awsalternate" + + cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "other" { + provider = "awsalternate" + + vpc_id = aws_vpc.other.id + name = %[1]q + + tags = { + Name = %[1]q + } +} + +data "aws_caller_identity" "other" { + provider = "awsalternate" +} + +resource "aws_vpc_peering_connection" "test" { + vpc_id = aws_vpc.test.id + peer_vpc_id = aws_vpc.other.id + peer_owner_id = data.aws_caller_identity.other.account_id + peer_region = %[2]q + auto_accept = false + + tags = { + Name = %[1]q + } +} + +resource "aws_vpc_peering_connection_accepter" "other" { + provider = "awsalternate" + + vpc_peering_connection_id = aws_vpc_peering_connection.test.id + auto_accept = true + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group_rule" "test" { + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + + source_security_group_id = "${data.aws_caller_identity.other.account_id}/${aws_security_group.other.id}" + + security_group_id = aws_security_group.test.id + + depends_on = [aws_vpc_peering_connection_accepter.other] +} +`, rName, acctest.Region())) +} From 5f4163faa4cb95a5e2c9f70168dfb18a7bd4eb4d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 14:01:56 -0400 Subject: [PATCH 091/120] r/aws_security_group_rule: Add 'TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_Ingress_peeredVPC -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_peeredVPC === PAUSE TestAccVPCSecurityGroupRule_Ingress_peeredVPC === CONT TestAccVPCSecurityGroupRule_Ingress_peeredVPC --- PASS: TestAccVPCSecurityGroupRule_Ingress_peeredVPC (27.25s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 31.569s --- .../ec2/vpc_security_group_rule_test.go | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 7eb79c2562b2..1aef02aa8ac2 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1342,6 +1342,47 @@ func TestAccVPCSecurityGroupRule_Ingress_peeredVPC(t *testing.T) { }) } +func TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6(t *testing.T) { + var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCSecurityGroupRuleConfig_ingressIPv4AndIPv6(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.0", "10.2.0.0/16"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "1"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.0", "2001:db8:85a3::/64"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "0"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -2353,3 +2394,35 @@ resource "aws_security_group_rule" "test" { } `, rName, acctest.Region())) } + +func testAccVPCSecurityGroupRuleConfig_ingressIPv4AndIPv6(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + vpc_id = aws_vpc.test.id + name = %[1]q + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group_rule" "test" { + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + cidr_blocks = ["10.2.0.0/16"] + ipv6_cidr_blocks = ["2001:db8:85a3::/64"] + + security_group_id = aws_security_group.test.id +} +`, rName) +} From 6a0957c0a1214347096eebb643d682cf47606795 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 14:13:00 -0400 Subject: [PATCH 092/120] r/aws_security_group_rule: Add 'TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_Ingress_peeredVPC -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_peeredVPC === PAUSE TestAccVPCSecurityGroupRule_Ingress_peeredVPC === CONT TestAccVPCSecurityGroupRule_Ingress_peeredVPC --- PASS: TestAccVPCSecurityGroupRule_Ingress_peeredVPC (27.25s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 31.569s --- .../ec2/vpc_security_group_rule_test.go | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 1aef02aa8ac2..17cd43ba6419 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1383,6 +1383,45 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6(t *testing.T) { }) } +func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf(t *testing.T) { + var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sgResourceName := "aws_security_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckManagedPrefixList(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCSecurityGroupRuleConfig_prefixListAndSelf(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sgResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sgResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "true"), + resource.TestCheckNoResourceAttr(resourceName, "source_security_group_id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -2426,3 +2465,41 @@ resource "aws_security_group_rule" "test" { } `, rName) } + +func testAccVPCSecurityGroupRuleConfig_prefixListAndSelf(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + vpc_id = aws_vpc.test.id + name = %[1]q + + tags = { + Name = %[1]q + } +} + +resource "aws_ec2_managed_prefix_list" "test" { + address_family = "IPv6" + max_entries = 2 + name = %[1]q +} + +resource "aws_security_group_rule" "test" { + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] + self = true + + security_group_id = aws_security_group.test.id +} +`, rName) +} From e71afa3cb96e7865437addefb535542b69549140 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 5 Jul 2022 14:19:45 -0400 Subject: [PATCH 093/120] r/aws_security_group_rule: Add 'TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource (29.88s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 33.849s --- .../ec2/vpc_security_group_rule_test.go | 83 ++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 17cd43ba6419..031ee28036e8 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1422,6 +1422,46 @@ func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf(t *testing.T) { }) } +func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource(t *testing.T) { + var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_security_group_rule.test" + sg1ResourceName := "aws_security_group.test.0" + sg2ResourceName := "aws_security_group.test.1" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t); testAccPreCheckManagedPrefixList(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: testAccCheckSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVPCSecurityGroupRuleConfig_prefixListAndSource(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckSecurityGroupExists(sg1ResourceName, &group), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "description"), + resource.TestCheckResourceAttr(resourceName, "from_port", "80"), + resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "prefix_list_ids.#", "1"), + resource.TestCheckResourceAttrPair(resourceName, "security_group_id", sg1ResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "self", "false"), + resource.TestCheckResourceAttrPair(resourceName, "source_security_group_id", sg2ResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "to_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "type", "ingress"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccSecurityGroupRuleImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccSecurityGroupRuleImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -2497,9 +2537,50 @@ resource "aws_security_group_rule" "test" { from_port = 80 to_port = 8000 prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] - self = true + security_group_id = aws_security_group.test.id } `, rName) } + +func testAccVPCSecurityGroupRuleConfig_prefixListAndSource(rName string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_security_group" "test" { + count = 2 + + vpc_id = aws_vpc.test.id + name = "%[1]s-${count.index}" + + tags = { + Name = %[1]q + } +} + +resource "aws_ec2_managed_prefix_list" "test" { + address_family = "IPv4" + max_entries = 1 + name = %[1]q +} + +resource "aws_security_group_rule" "test" { + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] + + source_security_group_id = aws_security_group.test[1].id + + security_group_id = aws_security_group.test[0].id +} +`, rName) +} From 9321569fd8c9b853d1d8767f85455a920a49c952 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 6 Jul 2022 09:41:19 -0400 Subject: [PATCH 094/120] r/aws_security_group_rule: Tidy up resource Read. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_ -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_vpc === PAUSE TestAccVPCSecurityGroupRule_Ingress_vpc === RUN TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === PAUSE TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === RUN TestAccVPCSecurityGroupRule_Ingress_protocol === PAUSE TestAccVPCSecurityGroupRule_Ingress_protocol === RUN TestAccVPCSecurityGroupRule_Ingress_icmpv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_icmpv6 === RUN TestAccVPCSecurityGroupRule_Ingress_ipv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv6 === RUN TestAccVPCSecurityGroupRule_Ingress_classic === PAUSE TestAccVPCSecurityGroupRule_Ingress_classic === RUN TestAccVPCSecurityGroupRule_egress === PAUSE TestAccVPCSecurityGroupRule_egress === RUN TestAccVPCSecurityGroupRule_selfReference === PAUSE TestAccVPCSecurityGroupRule_selfReference === RUN TestAccVPCSecurityGroupRule_expectInvalidTypeError === PAUSE TestAccVPCSecurityGroupRule_expectInvalidTypeError === RUN TestAccVPCSecurityGroupRule_expectInvalidCIDR === PAUSE TestAccVPCSecurityGroupRule_expectInvalidCIDR === RUN TestAccVPCSecurityGroupRule_PartialMatching_basic === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_basic === RUN TestAccVPCSecurityGroupRule_PartialMatching_source === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_source === RUN TestAccVPCSecurityGroupRule_issue5310 === PAUSE TestAccVPCSecurityGroupRule_issue5310 === RUN TestAccVPCSecurityGroupRule_race === PAUSE TestAccVPCSecurityGroupRule_race === RUN TestAccVPCSecurityGroupRule_selfSource === PAUSE TestAccVPCSecurityGroupRule_selfSource === RUN TestAccVPCSecurityGroupRule_prefixListEgress === PAUSE TestAccVPCSecurityGroupRule_prefixListEgress === RUN TestAccVPCSecurityGroupRule_ingressDescription === PAUSE TestAccVPCSecurityGroupRule_ingressDescription === RUN TestAccVPCSecurityGroupRule_egressDescription === PAUSE TestAccVPCSecurityGroupRule_egressDescription === RUN TestAccVPCSecurityGroupRule_IngressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_IngressDescription_updates === RUN TestAccVPCSecurityGroupRule_EgressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_EgressDescription_updates === RUN TestAccVPCSecurityGroupRule_Description_allPorts === PAUSE TestAccVPCSecurityGroupRule_Description_allPorts === RUN TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === PAUSE TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === RUN TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === PAUSE TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === RUN TestAccVPCSecurityGroupRule_multiDescription === PAUSE TestAccVPCSecurityGroupRule_multiDescription === RUN TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === RUN TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === PAUSE TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === RUN TestAccVPCSecurityGroupRule_Ingress_peeredVPC === PAUSE TestAccVPCSecurityGroupRule_Ingress_peeredVPC === RUN TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === CONT TestAccVPCSecurityGroupRule_Ingress_vpc === CONT TestAccVPCSecurityGroupRule_prefixListEgress --- PASS: TestAccVPCSecurityGroupRule_Ingress_vpc (19.05s) === CONT TestAccVPCSecurityGroupRule_expectInvalidTypeError --- PASS: TestAccVPCSecurityGroupRule_expectInvalidTypeError (0.72s) === CONT TestAccVPCSecurityGroupRule_selfSource --- PASS: TestAccVPCSecurityGroupRule_prefixListEgress (33.28s) === CONT TestAccVPCSecurityGroupRule_race --- PASS: TestAccVPCSecurityGroupRule_selfSource (23.42s) === CONT TestAccVPCSecurityGroupRule_issue5310 --- PASS: TestAccVPCSecurityGroupRule_issue5310 (20.02s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_source --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_source (25.70s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_basic --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_basic (29.81s) === CONT TestAccVPCSecurityGroupRule_expectInvalidCIDR --- PASS: TestAccVPCSecurityGroupRule_expectInvalidCIDR (1.19s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv6 (23.28s) === CONT TestAccVPCSecurityGroupRule_selfReference --- PASS: TestAccVPCSecurityGroupRule_selfReference (23.09s) === CONT TestAccVPCSecurityGroupRule_egress --- PASS: TestAccVPCSecurityGroupRule_race (147.31s) === CONT TestAccVPCSecurityGroupRule_Ingress_classic --- PASS: TestAccVPCSecurityGroupRule_egress (20.58s) === CONT TestAccVPCSecurityGroupRule_multiDescription --- PASS: TestAccVPCSecurityGroupRule_Ingress_classic (12.99s) === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource (29.27s) === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf --- PASS: TestAccVPCSecurityGroupRule_multiDescription (65.55s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf (30.33s) === CONT TestAccVPCSecurityGroupRule_Ingress_peeredVPC acctest.go:605: skipping test because at least one environment variable of [AWS_ALTERNATE_PROFILE AWS_ALTERNATE_ACCESS_KEY_ID] must be set. Usage: credentials for running acceptance testing in alternate AWS account. --- SKIP: TestAccVPCSecurityGroupRule_Ingress_peeredVPC (0.06s) === CONT TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 (22.32s) === CONT TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists (29.96s) === CONT TestAccVPCSecurityGroupRule_Ingress_protocol --- PASS: TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 (22.91s) === CONT TestAccVPCSecurityGroupRule_Ingress_icmpv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_protocol (24.38s) === CONT TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts --- PASS: TestAccVPCSecurityGroupRule_Ingress_icmpv6 (24.10s) === CONT TestAccVPCSecurityGroupRule_EgressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts (29.30s) === CONT TestAccVPCSecurityGroupRule_Description_allPorts --- PASS: TestAccVPCSecurityGroupRule_EgressDescription_updates (29.31s) === CONT TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash --- PASS: TestAccVPCSecurityGroupRule_Description_allPorts (30.66s) === CONT TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id --- PASS: TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash (22.77s) === CONT TestAccVPCSecurityGroupRule_egressDescription --- PASS: TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id (20.92s) === CONT TestAccVPCSecurityGroupRule_ingressDescription --- PASS: TestAccVPCSecurityGroupRule_egressDescription (18.44s) === CONT TestAccVPCSecurityGroupRule_IngressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_ingressDescription (18.62s) --- PASS: TestAccVPCSecurityGroupRule_IngressDescription_updates (30.74s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 427.025s --- .../service/ec2/vpc_security_group_rule.go | 293 +++++++----------- .../ec2/vpc_security_group_rule_test.go | 8 +- 2 files changed, 114 insertions(+), 187 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 67837bf31077..f81a929cceff 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -159,6 +159,7 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e ipPermission := expandIpPermission(d, sg) ruleType := d.Get("type").(string) isVPC := aws.StringValue(sg.VpcId) != "" + id := IPPermissionIDHash(securityGroupID, ruleType, ipPermission) switch ruleType { case securityGroupRuleTypeIngress: @@ -192,11 +193,9 @@ information and instructions for recovery. Error: %w`, securityGroupID, err) } if err != nil { - return fmt.Errorf("authorizing Security Group (%s) Rule (%s): %w", securityGroupID, ruleType, err) + return fmt.Errorf("authorizing Security Group (%s) Rule (%s): %w", securityGroupID, id, err) } - id := IPPermissionIDHash(securityGroupID, ruleType, ipPermission) - _, err = tfresource.RetryWhenNotFound(5*time.Minute, func() (interface{}, error) { sg, err := FindSecurityGroupByID(conn, securityGroupID) @@ -212,7 +211,7 @@ information and instructions for recovery. Error: %w`, securityGroupID, err) rules = sg.IpPermissionsEgress } - rule := findRuleMatch(ipPermission, rules, isVPC) + rule, _ := findRuleMatch(ipPermission, rules, isVPC) if rule == nil { return nil, &resource.NotFoundError{} @@ -222,7 +221,7 @@ information and instructions for recovery. Error: %w`, securityGroupID, err) }) if err != nil { - return fmt.Errorf("waiting for Security Group (%s) Rule (%s): %w", securityGroupID, id, err) + return fmt.Errorf("waiting for Security Group (%s) Rule (%s) create: %w", securityGroupID, id, err) } d.SetId(id) @@ -232,60 +231,52 @@ information and instructions for recovery. Error: %w`, securityGroupID, err) func resourceSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn - sg_id := d.Get("security_group_id").(string) - sg, err := FindSecurityGroupByID(conn, sg_id) + securityGroupID := d.Get("security_group_id").(string) + ruleType := d.Get("type").(string) + + sg, err := FindSecurityGroupByID(conn, securityGroupID) + if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Security Group (%s) not found, removing Rule (%s) from state", sg_id, d.Id()) + log.Printf("[WARN] Security Group (%s) not found, removing from state", securityGroupID) d.SetId("") return nil } + if err != nil { - return fmt.Errorf("error finding Security Group (%s) for Rule (%s): %w", sg_id, d.Id(), err) + return fmt.Errorf("reading Security Group (%s): %w", securityGroupID, err) } + ipPermission := expandIpPermission(d, sg) isVPC := aws.StringValue(sg.VpcId) != "" - var rule *ec2.IpPermission var rules []*ec2.IpPermission - ruleType := d.Get("type").(string) - switch ruleType { - case securityGroupRuleTypeIngress: + + if ruleType == securityGroupRuleTypeIngress { rules = sg.IpPermissions - default: + } else { rules = sg.IpPermissionsEgress } - log.Printf("[DEBUG] Rules %v", rules) - p, err := expandIPPerm(d, sg) - if err != nil { - return err - } - - if !d.IsNewResource() && len(rules) == 0 { - log.Printf("[WARN] No %s rules were found for Security Group (%s) looking for Security Group Rule (%s)", ruleType, aws.StringValue(sg.GroupName), d.Id()) - d.SetId("") - return nil - } + rule, description := findRuleMatch(ipPermission, rules, isVPC) - rule = findRuleMatch(p, rules, isVPC) + if rule == nil { + if !d.IsNewResource() { + log.Printf("[WARN] Security Group (%s) Rule (%s) not found, removing from state", securityGroupID, d.Id()) + d.SetId("") + return nil + } - if !d.IsNewResource() && rule == nil { - log.Printf("[DEBUG] Unable to find matching %s Security Group Rule (%s) for Group %s", ruleType, d.Id(), sg_id) - d.SetId("") - return nil + // Shouldn't reach here as we aren't called from resourceSecurityGroupRuleCreate. + return fmt.Errorf("reading Security Group (%s) Rule (%s): %w", securityGroupID, d.Id(), &resource.NotFoundError{}) } - log.Printf("[DEBUG] Found rule for Security Group Rule (%s): %s", d.Id(), rule) - + flattenIpPermission(d, ipPermission, isVPC) + d.Set("description", description) d.Set("type", ruleType) - setFromIPPerm(d, sg, p) - - d.Set("description", descriptionFromIPPerm(d, rule)) - if strings.Contains(d.Id(), "_") { // import so fix the id - id := IPPermissionIDHash(sg_id, ruleType, p) + id := IPPermissionIDHash(securityGroupID, ruleType, ipPermission) d.SetId(id) } @@ -373,8 +364,9 @@ func (b ByGroupPair) Less(i, j int) bool { panic("mismatched security group rules, may be a terraform bug") } -func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) *ec2.IpPermission { +func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) (*ec2.IpPermission, string) { var rule *ec2.IpPermission + var description string for _, r := range rules { if p.ToPort != nil && r.ToPort != nil && aws.Int64Value(p.ToPort) != aws.Int64Value(r.ToPort) { @@ -397,6 +389,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } if aws.StringValue(v1.CidrIp) == aws.StringValue(v2.CidrIp) { remaining-- + + if v := aws.StringValue(v2.Description); v != "" && description == "" { + description = v + } } } } @@ -413,6 +409,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } if aws.StringValue(v1.CidrIpv6) == aws.StringValue(v2.CidrIpv6) { remaining-- + + if v := aws.StringValue(v2.Description); v != "" && description == "" { + description = v + } } } } @@ -429,6 +429,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } if aws.StringValue(v1.PrefixListId) == aws.StringValue(v2.PrefixListId) { remaining-- + + if v := aws.StringValue(v2.Description); v != "" && description == "" { + description = v + } } } } @@ -446,6 +450,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } if aws.StringValue(v1.GroupId) == aws.StringValue(v2.GroupId) { remaining-- + + if v := aws.StringValue(v2.Description); v != "" && description == "" { + description = v + } } } else { if v1.GroupName == nil || v2.GroupName == nil { @@ -453,19 +461,25 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * } if aws.StringValue(v1.GroupName) == aws.StringValue(v2.GroupName) { remaining-- + + if v := aws.StringValue(v2.Description); v != "" && description == "" { + description = v + } } } } } if remaining > 0 { + description = "" + continue } rule = r } - return rule + return rule, description } func IPPermissionIDHash(sg_id, ruleType string, ip *ec2.IpPermission) string { @@ -647,150 +661,6 @@ func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermiss return &perm, nil } -func setFromIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup, rule *ec2.IpPermission) { - isVPC := aws.StringValue(sg.VpcId) != "" - - d.Set("from_port", rule.FromPort) - d.Set("to_port", rule.ToPort) - d.Set("protocol", rule.IpProtocol) - - var cb []string - for _, c := range rule.IpRanges { - cb = append(cb, *c.CidrIp) - } - d.Set("cidr_blocks", cb) - - var ipv6 []string - for _, ip := range rule.Ipv6Ranges { - ipv6 = append(ipv6, *ip.CidrIpv6) - } - d.Set("ipv6_cidr_blocks", ipv6) - - var pl []string - for _, p := range rule.PrefixListIds { - pl = append(pl, *p.PrefixListId) - } - d.Set("prefix_list_ids", pl) - - if len(rule.UserIdGroupPairs) > 0 { - s := rule.UserIdGroupPairs[0] - - if isVPC { - if existingSourceSgId, ok := d.GetOk("source_security_group_id"); ok { - sgIdComponents := strings.Split(existingSourceSgId.(string), "/") - hasAccountIdPrefix := len(sgIdComponents) == 2 - - if hasAccountIdPrefix && s.UserId != nil { - // then ensure on refresh that we preserve the account id prefix - d.Set("source_security_group_id", fmt.Sprintf("%s/%s", aws.StringValue(s.UserId), aws.StringValue(s.GroupId))) - } else { - d.Set("source_security_group_id", s.GroupId) - } - } else { - d.Set("source_security_group_id", s.GroupId) - } - } else { - d.Set("source_security_group_id", s.GroupName) - } - } -} - -func descriptionFromIPPerm(d *schema.ResourceData, rule *ec2.IpPermission) string { - // probe IpRanges - cidrIps := make(map[string]bool) - if raw, ok := d.GetOk("cidr_blocks"); ok { - for _, v := range raw.([]interface{}) { - cidrIps[v.(string)] = true - } - } - - if len(cidrIps) > 0 { - for _, c := range rule.IpRanges { - if _, ok := cidrIps[*c.CidrIp]; !ok { - continue - } - - if desc := aws.StringValue(c.Description); desc != "" { - return desc - } - } - } - - // probe Ipv6Ranges - cidrIpv6s := make(map[string]bool) - if raw, ok := d.GetOk("ipv6_cidr_blocks"); ok { - for _, v := range raw.([]interface{}) { - cidrIpv6s[v.(string)] = true - } - } - - if len(cidrIpv6s) > 0 { - for _, ip := range rule.Ipv6Ranges { - if _, ok := cidrIpv6s[*ip.CidrIpv6]; !ok { - continue - } - - if desc := aws.StringValue(ip.Description); desc != "" { - return desc - } - } - } - - // probe PrefixListIds - listIds := make(map[string]bool) - if raw, ok := d.GetOk("prefix_list_ids"); ok { - for _, v := range raw.([]interface{}) { - listIds[v.(string)] = true - } - } - - if len(listIds) > 0 { - for _, p := range rule.PrefixListIds { - if _, ok := listIds[*p.PrefixListId]; !ok { - continue - } - - if desc := aws.StringValue(p.Description); desc != "" { - return desc - } - } - } - - // probe UserIdGroupPairs - if raw, ok := d.GetOk("source_security_group_id"); ok { - components := strings.Split(raw.(string), "/") - - switch len(components) { - case 2: - userId := components[0] - groupId := components[1] - - for _, gp := range rule.UserIdGroupPairs { - if aws.StringValue(gp.GroupId) != groupId || aws.StringValue(gp.UserId) != userId { - continue - } - - if desc := aws.StringValue(gp.Description); desc != "" { - return desc - } - } - case 1: - groupId := components[0] - for _, gp := range rule.UserIdGroupPairs { - if aws.StringValue(gp.GroupId) != groupId { - continue - } - - if desc := aws.StringValue(gp.Description); desc != "" { - return desc - } - } - } - } - - return "" -} - func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.ResourceData) error { sg_id := d.Get("security_group_id").(string) @@ -1049,3 +919,60 @@ func expandIpPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPe return apiObject } + +func flattenIpPermission(d *schema.ResourceData, apiObject *ec2.IpPermission, isVPC bool) { // nosemgrep:caps5-in-func-name + if apiObject == nil { + return + } + + d.Set("from_port", apiObject.FromPort) + d.Set("protocol", apiObject.IpProtocol) + d.Set("to_port", apiObject.ToPort) + + if v := apiObject.IpRanges; len(v) > 0 { + var ipRanges []string + + for _, v := range v { + ipRanges = append(ipRanges, aws.StringValue(v.CidrIp)) + } + + d.Set("cidr_blocks", ipRanges) + } + + if v := apiObject.Ipv6Ranges; len(v) > 0 { + var ipv6Ranges []string + + for _, v := range v { + ipv6Ranges = append(ipv6Ranges, aws.StringValue(v.CidrIpv6)) + } + + d.Set("ipv6_cidr_blocks", ipv6Ranges) + } + + if v := apiObject.PrefixListIds; len(v) > 0 { + var prefixListIDs []string + + for _, v := range v { + prefixListIDs = append(prefixListIDs, aws.StringValue(v.PrefixListId)) + } + + d.Set("prefix_list_ids", prefixListIDs) + } + + if v := apiObject.UserIdGroupPairs; len(v) > 0 { + v := v[0] + + if isVPC { + if old, ok := d.GetOk("source_security_group_id"); ok { + // [OwnerID/]SecurityGroupID. + if parts := strings.Split(old.(string), "/"); len(parts) == 1 || aws.StringValue(v.UserId) == "" { + d.Set("source_security_group_id", v.GroupId) + } else { + d.Set("source_security_group_id", strings.Join([]string{aws.StringValue(v.UserId), aws.StringValue(v.GroupId)}, "/")) + } + } + } else { + d.Set("source_security_group_id", v.GroupName) + } + } +} diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 031ee28036e8..fe750129f1a7 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -1019,7 +1019,7 @@ func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testi Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_multipleSearchingAllProtocolCrash(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(sgResourceName, &group), resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "1"), resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.0", "10.0.0.0/8"), @@ -1082,7 +1082,7 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_multiDescription(rName, "ingress"), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(sg1ResourceName, &group1), testAccCheckSecurityGroupExists(sg2ResourceName, &group2), resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "1"), @@ -1142,7 +1142,7 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { }, { Config: testAccVPCSecurityGroupRuleConfig_multiDescription(rName, "egress"), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckSecurityGroupExists(sg1ResourceName, &group1), testAccCheckSecurityGroupExists(sg2ResourceName, &group2), resource.TestCheckResourceAttr(resource1Name, "cidr_blocks.#", "1"), @@ -2537,7 +2537,7 @@ resource "aws_security_group_rule" "test" { from_port = 80 to_port = 8000 prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] - + self = true security_group_id = aws_security_group.test.id } From b069cd0f8394347d8e1df6b46048ad4d89215df1 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 6 Jul 2022 11:17:51 -0400 Subject: [PATCH 095/120] r/aws_security_group_rule: Tidy up resource Update. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_ -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_vpc === PAUSE TestAccVPCSecurityGroupRule_Ingress_vpc === RUN TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === PAUSE TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === RUN TestAccVPCSecurityGroupRule_Ingress_protocol === PAUSE TestAccVPCSecurityGroupRule_Ingress_protocol === RUN TestAccVPCSecurityGroupRule_Ingress_icmpv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_icmpv6 === RUN TestAccVPCSecurityGroupRule_Ingress_ipv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv6 === RUN TestAccVPCSecurityGroupRule_Ingress_classic === PAUSE TestAccVPCSecurityGroupRule_Ingress_classic === RUN TestAccVPCSecurityGroupRule_egress === PAUSE TestAccVPCSecurityGroupRule_egress === RUN TestAccVPCSecurityGroupRule_selfReference === PAUSE TestAccVPCSecurityGroupRule_selfReference === RUN TestAccVPCSecurityGroupRule_expectInvalidTypeError === PAUSE TestAccVPCSecurityGroupRule_expectInvalidTypeError === RUN TestAccVPCSecurityGroupRule_expectInvalidCIDR === PAUSE TestAccVPCSecurityGroupRule_expectInvalidCIDR === RUN TestAccVPCSecurityGroupRule_PartialMatching_basic === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_basic === RUN TestAccVPCSecurityGroupRule_PartialMatching_source === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_source === RUN TestAccVPCSecurityGroupRule_issue5310 === PAUSE TestAccVPCSecurityGroupRule_issue5310 === RUN TestAccVPCSecurityGroupRule_race === PAUSE TestAccVPCSecurityGroupRule_race === RUN TestAccVPCSecurityGroupRule_selfSource === PAUSE TestAccVPCSecurityGroupRule_selfSource === RUN TestAccVPCSecurityGroupRule_prefixListEgress === PAUSE TestAccVPCSecurityGroupRule_prefixListEgress === RUN TestAccVPCSecurityGroupRule_ingressDescription === PAUSE TestAccVPCSecurityGroupRule_ingressDescription === RUN TestAccVPCSecurityGroupRule_egressDescription === PAUSE TestAccVPCSecurityGroupRule_egressDescription === RUN TestAccVPCSecurityGroupRule_IngressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_IngressDescription_updates === RUN TestAccVPCSecurityGroupRule_EgressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_EgressDescription_updates === RUN TestAccVPCSecurityGroupRule_Description_allPorts === PAUSE TestAccVPCSecurityGroupRule_Description_allPorts === RUN TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === PAUSE TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === RUN TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === PAUSE TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === RUN TestAccVPCSecurityGroupRule_multiDescription === PAUSE TestAccVPCSecurityGroupRule_multiDescription === RUN TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === RUN TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === PAUSE TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === RUN TestAccVPCSecurityGroupRule_Ingress_peeredVPC === PAUSE TestAccVPCSecurityGroupRule_Ingress_peeredVPC === RUN TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === CONT TestAccVPCSecurityGroupRule_Ingress_vpc === CONT TestAccVPCSecurityGroupRule_prefixListEgress --- PASS: TestAccVPCSecurityGroupRule_Ingress_vpc (20.74s) === CONT TestAccVPCSecurityGroupRule_expectInvalidTypeError --- PASS: TestAccVPCSecurityGroupRule_expectInvalidTypeError (0.84s) === CONT TestAccVPCSecurityGroupRule_selfSource --- PASS: TestAccVPCSecurityGroupRule_prefixListEgress (34.87s) === CONT TestAccVPCSecurityGroupRule_race --- PASS: TestAccVPCSecurityGroupRule_selfSource (24.28s) === CONT TestAccVPCSecurityGroupRule_issue5310 --- PASS: TestAccVPCSecurityGroupRule_issue5310 (21.23s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_source --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_source (25.98s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_basic --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_basic (33.61s) === CONT TestAccVPCSecurityGroupRule_expectInvalidCIDR --- PASS: TestAccVPCSecurityGroupRule_expectInvalidCIDR (1.54s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv6 (24.16s) === CONT TestAccVPCSecurityGroupRule_selfReference --- PASS: TestAccVPCSecurityGroupRule_selfReference (23.97s) === CONT TestAccVPCSecurityGroupRule_egress --- PASS: TestAccVPCSecurityGroupRule_race (147.62s) === CONT TestAccVPCSecurityGroupRule_Ingress_classic --- PASS: TestAccVPCSecurityGroupRule_egress (18.52s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_classic (13.44s) === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 (22.56s) === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource (29.66s) === CONT TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf (30.92s) === CONT TestAccVPCSecurityGroupRule_Ingress_peeredVPC acctest.go:605: skipping test because at least one environment variable of [AWS_ALTERNATE_PROFILE AWS_ALTERNATE_ACCESS_KEY_ID] must be set. Usage: credentials for running acceptance testing in alternate AWS account. --- SKIP: TestAccVPCSecurityGroupRule_Ingress_peeredVPC (0.07s) === CONT TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists (31.81s) === CONT TestAccVPCSecurityGroupRule_multiDescription --- PASS: TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 (23.66s) === CONT TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts --- PASS: TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts (30.67s) === CONT TestAccVPCSecurityGroupRule_EgressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_multiDescription (62.67s) === CONT TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash --- PASS: TestAccVPCSecurityGroupRule_EgressDescription_updates (29.47s) === CONT TestAccVPCSecurityGroupRule_Description_allPorts --- PASS: TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash (21.89s) === CONT TestAccVPCSecurityGroupRule_egressDescription --- PASS: TestAccVPCSecurityGroupRule_egressDescription (19.58s) === CONT TestAccVPCSecurityGroupRule_IngressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_Description_allPorts (31.62s) === CONT TestAccVPCSecurityGroupRule_ingressDescription --- PASS: TestAccVPCSecurityGroupRule_ingressDescription (17.94s) === CONT TestAccVPCSecurityGroupRule_Ingress_protocol --- PASS: TestAccVPCSecurityGroupRule_IngressDescription_updates (29.82s) === CONT TestAccVPCSecurityGroupRule_Ingress_icmpv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_protocol (22.60s) === CONT TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id --- PASS: TestAccVPCSecurityGroupRule_Ingress_icmpv6 (23.41s) --- PASS: TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id (22.79s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 431.413s --- .../service/ec2/vpc_security_group_rule.go | 198 ++++-------------- 1 file changed, 41 insertions(+), 157 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index f81a929cceff..e0294cf7e100 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -287,8 +287,46 @@ func resourceSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) e conn := meta.(*conns.AWSClient).EC2Conn if d.HasChange("description") { - if err := resourceSecurityGroupRuleDescriptionUpdate(conn, d); err != nil { - return err + securityGroupID := d.Get("security_group_id").(string) + + conns.GlobalMutexKV.Lock(securityGroupID) + defer conns.GlobalMutexKV.Unlock(securityGroupID) + + sg, err := FindSecurityGroupByID(conn, securityGroupID) + + if err != nil { + return fmt.Errorf("reading Security Group (%s): %w", securityGroupID, err) + } + + ipPermission := expandIpPermission(d, sg) + ruleType := d.Get("type").(string) + isVPC := aws.StringValue(sg.VpcId) != "" + + switch ruleType { + case securityGroupRuleTypeIngress: + input := &ec2.UpdateSecurityGroupRuleDescriptionsIngressInput{ + IpPermissions: []*ec2.IpPermission{ipPermission}, + } + + if isVPC { + input.GroupId = sg.GroupId + } else { + input.GroupName = sg.GroupName + } + + _, err = conn.UpdateSecurityGroupRuleDescriptionsIngress(input) + + case securityGroupRuleTypeEgress: + input := &ec2.UpdateSecurityGroupRuleDescriptionsEgressInput{ + GroupId: sg.GroupId, + IpPermissions: []*ec2.IpPermission{ipPermission}, + } + + _, err = conn.UpdateSecurityGroupRuleDescriptionsEgress(input) + } + + if err != nil { + return fmt.Errorf("updating Security Group (%s) Rule (%s) description: %w", securityGroupID, d.Id(), err) } } @@ -340,7 +378,7 @@ func resourceSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("revoking Security Group (%s) Rule (%s): %w", securityGroupID, ruleType, err) + return fmt.Errorf("revoking Security Group (%s) Rule (%s): %w", securityGroupID, d.Id(), err) } return nil @@ -551,160 +589,6 @@ func IPPermissionIDHash(sg_id, ruleType string, ip *ec2.IpPermission) string { return fmt.Sprintf("sgrule-%d", create.StringHashcode(buf.String())) } -func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) (*ec2.IpPermission, error) { - var perm ec2.IpPermission - - protocol := ProtocolForValue(d.Get("protocol").(string)) - perm.IpProtocol = aws.String(protocol) - - // InvalidParameterValue: When protocol is ALL, you cannot specify from-port. - if protocol != "-1" { - perm.FromPort = aws.Int64(int64(d.Get("from_port").(int))) - perm.ToPort = aws.Int64(int64(d.Get("to_port").(int))) - } - - // build a group map that behaves like a set - groups := make(map[string]bool) - if raw, ok := d.GetOk("source_security_group_id"); ok { - groups[raw.(string)] = true - } - - if _, ok := d.GetOk("self"); ok { - if aws.StringValue(sg.VpcId) != "" { - groups[*sg.GroupId] = true - } else { - groups[*sg.GroupName] = true - } - } - - description := d.Get("description").(string) - - if len(groups) > 0 { - perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, len(groups)) - // build string list of group name/ids - var gl []string - for k := range groups { - gl = append(gl, k) - } - - for i, name := range gl { - ownerId, id := "", name - if items := strings.Split(id, "/"); len(items) > 1 { - ownerId, id = items[0], items[1] - } - - perm.UserIdGroupPairs[i] = &ec2.UserIdGroupPair{ - GroupId: aws.String(id), - UserId: aws.String(ownerId), - } - - if aws.StringValue(sg.VpcId) == "" { - perm.UserIdGroupPairs[i].GroupId = nil - perm.UserIdGroupPairs[i].GroupName = aws.String(id) - perm.UserIdGroupPairs[i].UserId = nil - } - - if description != "" { - perm.UserIdGroupPairs[i].Description = aws.String(description) - } - } - } - - if raw, ok := d.GetOk("cidr_blocks"); ok { - list := raw.([]interface{}) - perm.IpRanges = make([]*ec2.IpRange, len(list)) - for i, v := range list { - cidrIP, ok := v.(string) - if !ok { - return nil, fmt.Errorf("empty element found in cidr_blocks - consider using the compact function") - } - perm.IpRanges[i] = &ec2.IpRange{CidrIp: aws.String(cidrIP)} - - if description != "" { - perm.IpRanges[i].Description = aws.String(description) - } - } - } - - if raw, ok := d.GetOk("ipv6_cidr_blocks"); ok { - list := raw.([]interface{}) - perm.Ipv6Ranges = make([]*ec2.Ipv6Range, len(list)) - for i, v := range list { - cidrIP, ok := v.(string) - if !ok { - return nil, fmt.Errorf("empty element found in ipv6_cidr_blocks - consider using the compact function") - } - perm.Ipv6Ranges[i] = &ec2.Ipv6Range{CidrIpv6: aws.String(cidrIP)} - - if description != "" { - perm.Ipv6Ranges[i].Description = aws.String(description) - } - } - } - - if raw, ok := d.GetOk("prefix_list_ids"); ok { - list := raw.([]interface{}) - perm.PrefixListIds = make([]*ec2.PrefixListId, len(list)) - for i, v := range list { - prefixListID, ok := v.(string) - if !ok { - return nil, fmt.Errorf("empty element found in prefix_list_ids - consider using the compact function") - } - perm.PrefixListIds[i] = &ec2.PrefixListId{PrefixListId: aws.String(prefixListID)} - - if description != "" { - perm.PrefixListIds[i].Description = aws.String(description) - } - } - } - - return &perm, nil -} - -func resourceSecurityGroupRuleDescriptionUpdate(conn *ec2.EC2, d *schema.ResourceData) error { - sg_id := d.Get("security_group_id").(string) - - conns.GlobalMutexKV.Lock(sg_id) - defer conns.GlobalMutexKV.Unlock(sg_id) - - sg, err := FindSecurityGroupByID(conn, sg_id) - if err != nil { - return err - } - - perm, err := expandIPPerm(d, sg) - if err != nil { - return err - } - ruleType := d.Get("type").(string) - switch ruleType { - case securityGroupRuleTypeIngress: - req := &ec2.UpdateSecurityGroupRuleDescriptionsIngressInput{ - GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{perm}, - } - - _, err = conn.UpdateSecurityGroupRuleDescriptionsIngress(req) - - if err != nil { - return fmt.Errorf("Error updating security group %s rule description: %w", sg_id, err) - } - case securityGroupRuleTypeEgress: - req := &ec2.UpdateSecurityGroupRuleDescriptionsEgressInput{ - GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{perm}, - } - - _, err = conn.UpdateSecurityGroupRuleDescriptionsEgress(req) - - if err != nil { - return fmt.Errorf("Error updating security group %s rule description: %w", sg_id, err) - } - } - - return nil -} - // validateSecurityGroupRuleImportString does minimal validation of import string without going to AWS func validateSecurityGroupRuleImportString(importStr string) ([]string, error) { // example: sg-09a093729ef9382a6_ingress_tcp_8000_8000_10.0.3.0/24 From f6c5497d8601a816e79e76cd10635a828dff87c8 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 6 Jul 2022 11:21:20 -0400 Subject: [PATCH 096/120] 'IPPermissionIDHash' -> 'SecurityGroupRuleCreateID'. --- internal/service/ec2/vpc_security_group_rule.go | 9 +++++---- internal/service/ec2/vpc_security_group_rule_migrate.go | 2 +- internal/service/ec2/vpc_security_group_rule_test.go | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index e0294cf7e100..604883c45e3a 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -159,7 +159,7 @@ func resourceSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) e ipPermission := expandIpPermission(d, sg) ruleType := d.Get("type").(string) isVPC := aws.StringValue(sg.VpcId) != "" - id := IPPermissionIDHash(securityGroupID, ruleType, ipPermission) + id := SecurityGroupRuleCreateID(securityGroupID, ruleType, ipPermission) switch ruleType { case securityGroupRuleTypeIngress: @@ -276,7 +276,7 @@ func resourceSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) err if strings.Contains(d.Id(), "_") { // import so fix the id - id := IPPermissionIDHash(securityGroupID, ruleType, ipPermission) + id := SecurityGroupRuleCreateID(securityGroupID, ruleType, ipPermission) d.SetId(id) } @@ -520,9 +520,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) ( return rule, description } -func IPPermissionIDHash(sg_id, ruleType string, ip *ec2.IpPermission) string { +func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermission) string { var buf bytes.Buffer - buf.WriteString(fmt.Sprintf("%s-", sg_id)) + + buf.WriteString(fmt.Sprintf("%s-", securityGroupID)) if aws.Int64Value(ip.FromPort) > 0 { buf.WriteString(fmt.Sprintf("%d-", *ip.FromPort)) } diff --git a/internal/service/ec2/vpc_security_group_rule_migrate.go b/internal/service/ec2/vpc_security_group_rule_migrate.go index 832081e340f7..5e06fb82b62d 100644 --- a/internal/service/ec2/vpc_security_group_rule_migrate.go +++ b/internal/service/ec2/vpc_security_group_rule_migrate.go @@ -41,7 +41,7 @@ func migrateSGRuleStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceS } log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) - newID := IPPermissionIDHash(is.Attributes["security_group_id"], is.Attributes["type"], perm) + newID := SecurityGroupRuleCreateID(is.Attributes["security_group_id"], is.Attributes["type"], perm) is.Attributes["id"] = newID is.ID = newID log.Printf("[DEBUG] Attributes after migration: %#v, new id: %s", is.Attributes, newID) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index fe750129f1a7..10d77f42a7d6 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -17,7 +17,7 @@ import ( tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) -func TestIPPermissionIDHash(t *testing.T) { +func TestSecurityGroupRuleCreateID(t *testing.T) { simple := &ec2.IpPermission{ IpProtocol: aws.String("tcp"), FromPort: aws.Int64(80), @@ -103,7 +103,7 @@ func TestIPPermissionIDHash(t *testing.T) { } for _, tc := range cases { - actual := tfec2.IPPermissionIDHash("sg-12345", tc.Type, tc.Input) + actual := tfec2.SecurityGroupRuleCreateID("sg-12345", tc.Type, tc.Input) if actual != tc.Output { t.Errorf("input: %s - %s\noutput: %s", tc.Type, tc.Input, actual) } From 239cba921e7a0797980b40e05dca830c72b63438 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 6 Jul 2022 17:03:08 -0400 Subject: [PATCH 097/120] r/aws_security_group_rule: Tidy up resource Import. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_' PKG=ec2 ACCTEST_PARALLELISM=2 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 2 -run=TestAccVPCSecurityGroupRule_ -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_vpc === PAUSE TestAccVPCSecurityGroupRule_Ingress_vpc === RUN TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === PAUSE TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id === RUN TestAccVPCSecurityGroupRule_Ingress_protocol === PAUSE TestAccVPCSecurityGroupRule_Ingress_protocol === RUN TestAccVPCSecurityGroupRule_Ingress_icmpv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_icmpv6 === RUN TestAccVPCSecurityGroupRule_Ingress_ipv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv6 === RUN TestAccVPCSecurityGroupRule_Ingress_classic === PAUSE TestAccVPCSecurityGroupRule_Ingress_classic === RUN TestAccVPCSecurityGroupRule_egress === PAUSE TestAccVPCSecurityGroupRule_egress === RUN TestAccVPCSecurityGroupRule_selfReference === PAUSE TestAccVPCSecurityGroupRule_selfReference === RUN TestAccVPCSecurityGroupRule_expectInvalidTypeError === PAUSE TestAccVPCSecurityGroupRule_expectInvalidTypeError === RUN TestAccVPCSecurityGroupRule_expectInvalidCIDR === PAUSE TestAccVPCSecurityGroupRule_expectInvalidCIDR === RUN TestAccVPCSecurityGroupRule_PartialMatching_basic === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_basic === RUN TestAccVPCSecurityGroupRule_PartialMatching_source === PAUSE TestAccVPCSecurityGroupRule_PartialMatching_source === RUN TestAccVPCSecurityGroupRule_issue5310 === PAUSE TestAccVPCSecurityGroupRule_issue5310 === RUN TestAccVPCSecurityGroupRule_race === PAUSE TestAccVPCSecurityGroupRule_race === RUN TestAccVPCSecurityGroupRule_selfSource === PAUSE TestAccVPCSecurityGroupRule_selfSource === RUN TestAccVPCSecurityGroupRule_prefixListEgress === PAUSE TestAccVPCSecurityGroupRule_prefixListEgress === RUN TestAccVPCSecurityGroupRule_ingressDescription === PAUSE TestAccVPCSecurityGroupRule_ingressDescription === RUN TestAccVPCSecurityGroupRule_egressDescription === PAUSE TestAccVPCSecurityGroupRule_egressDescription === RUN TestAccVPCSecurityGroupRule_IngressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_IngressDescription_updates === RUN TestAccVPCSecurityGroupRule_EgressDescription_updates === PAUSE TestAccVPCSecurityGroupRule_EgressDescription_updates === RUN TestAccVPCSecurityGroupRule_Description_allPorts === PAUSE TestAccVPCSecurityGroupRule_Description_allPorts === RUN TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === PAUSE TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts === RUN TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === PAUSE TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash === RUN TestAccVPCSecurityGroupRule_multiDescription === PAUSE TestAccVPCSecurityGroupRule_multiDescription === RUN TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 === RUN TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === PAUSE TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists === RUN TestAccVPCSecurityGroupRule_Ingress_peeredVPC === PAUSE TestAccVPCSecurityGroupRule_Ingress_peeredVPC === RUN TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 === PAUSE TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf === RUN TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === PAUSE TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource === CONT TestAccVPCSecurityGroupRule_Ingress_vpc === CONT TestAccVPCSecurityGroupRule_prefixListEgress --- PASS: TestAccVPCSecurityGroupRule_Ingress_vpc (20.68s) === CONT TestAccVPCSecurityGroupRule_multiDescription --- PASS: TestAccVPCSecurityGroupRule_prefixListEgress (39.10s) === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource (31.65s) === CONT TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf --- PASS: TestAccVPCSecurityGroupRule_multiDescription (72.60s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf (30.75s) === CONT TestAccVPCSecurityGroupRule_Ingress_peeredVPC acctest.go:605: skipping test because at least one environment variable of [AWS_ALTERNATE_PROFILE AWS_ALTERNATE_ACCESS_KEY_ID] must be set. Usage: credentials for running acceptance testing in alternate AWS account. --- SKIP: TestAccVPCSecurityGroupRule_Ingress_peeredVPC (0.07s) === CONT TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6 (23.76s) === CONT TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists (30.66s) === CONT TestAccVPCSecurityGroupRule_EgressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_Ingress_multipleIPv6 (22.97s) === CONT TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash --- PASS: TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash (22.93s) === CONT TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts --- PASS: TestAccVPCSecurityGroupRule_EgressDescription_updates (32.56s) === CONT TestAccVPCSecurityGroupRule_Description_allPorts --- PASS: TestAccVPCSecurityGroupRule_Description_allPorts (30.69s) === CONT TestAccVPCSecurityGroupRule_expectInvalidTypeError --- PASS: TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts (33.14s) === CONT TestAccVPCSecurityGroupRule_selfSource --- PASS: TestAccVPCSecurityGroupRule_expectInvalidTypeError (0.80s) === CONT TestAccVPCSecurityGroupRule_race --- PASS: TestAccVPCSecurityGroupRule_selfSource (23.82s) === CONT TestAccVPCSecurityGroupRule_issue5310 --- PASS: TestAccVPCSecurityGroupRule_issue5310 (20.14s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_source --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_source (26.28s) === CONT TestAccVPCSecurityGroupRule_PartialMatching_basic --- PASS: TestAccVPCSecurityGroupRule_PartialMatching_basic (33.03s) === CONT TestAccVPCSecurityGroupRule_expectInvalidCIDR --- PASS: TestAccVPCSecurityGroupRule_expectInvalidCIDR (1.24s) === CONT TestAccVPCSecurityGroupRule_Ingress_ipv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_ipv6 (24.72s) === CONT TestAccVPCSecurityGroupRule_selfReference --- PASS: TestAccVPCSecurityGroupRule_race (150.62s) === CONT TestAccVPCSecurityGroupRule_egress --- PASS: TestAccVPCSecurityGroupRule_selfReference (24.86s) === CONT TestAccVPCSecurityGroupRule_Ingress_classic --- PASS: TestAccVPCSecurityGroupRule_egress (19.02s) === CONT TestAccVPCSecurityGroupRule_egressDescription --- PASS: TestAccVPCSecurityGroupRule_Ingress_classic (19.95s) === CONT TestAccVPCSecurityGroupRule_IngressDescription_updates --- PASS: TestAccVPCSecurityGroupRule_egressDescription (19.25s) === CONT TestAccVPCSecurityGroupRule_ingressDescription --- PASS: TestAccVPCSecurityGroupRule_IngressDescription_updates (31.76s) === CONT TestAccVPCSecurityGroupRule_Ingress_protocol --- PASS: TestAccVPCSecurityGroupRule_ingressDescription (21.01s) === CONT TestAccVPCSecurityGroupRule_Ingress_icmpv6 --- PASS: TestAccVPCSecurityGroupRule_Ingress_protocol (24.49s) === CONT TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id --- PASS: TestAccVPCSecurityGroupRule_Ingress_icmpv6 (23.50s) --- PASS: TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id (21.63s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 452.144s --- .../service/ec2/vpc_security_group_rule.go | 257 ++++++++---------- 1 file changed, 115 insertions(+), 142 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 604883c45e3a..8c11167f167e 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -2,6 +2,7 @@ package ec2 import ( "bytes" + "context" "fmt" "log" "sort" @@ -30,16 +31,7 @@ func ResourceSecurityGroupRule() *schema.Resource { Delete: resourceSecurityGroupRuleDelete, Importer: &schema.ResourceImporter{ - State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - importParts, err := validateSecurityGroupRuleImportString(d.Id()) - if err != nil { - return nil, err - } - if err := populateSecurityGroupRuleFromImport(d, importParts); err != nil { - return nil, err - } - return []*schema.ResourceData{d}, nil - }, + StateContext: resourceSecurityGroupRuleImport, }, SchemaVersion: 2, @@ -274,7 +266,7 @@ func resourceSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) err d.Set("description", description) d.Set("type", ruleType) - if strings.Contains(d.Id(), "_") { + if strings.Contains(d.Id(), securityGroupRuleIDSeparator) { // import so fix the id id := SecurityGroupRuleCreateID(securityGroupID, ruleType, ipPermission) d.SetId(id) @@ -384,22 +376,101 @@ func resourceSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) e return nil } -// ByGroupPair implements sort.Interface for []*ec2.UserIDGroupPairs based on -// GroupID or GroupName field (only one should be set). -type ByGroupPair []*ec2.UserIdGroupPair +func resourceSecurityGroupRuleImport(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) { + invalidIDError := func(msg string) error { + return fmt.Errorf("unexpected format for ID (%q), expected SECURITYGROUPID_TYPE_PROTOCOL_FROMPORT_TOPORT_SOURCE[_SOURCE]*: %s", d.Id(), msg) + } -func (b ByGroupPair) Len() int { return len(b) } -func (b ByGroupPair) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b ByGroupPair) Less(i, j int) bool { - if b[i].GroupId != nil && b[j].GroupId != nil { - return aws.StringValue(b[i].GroupId) < aws.StringValue(b[j].GroupId) + // example: sg-09a093729ef9382a6_ingress_tcp_8000_8000_10.0.3.0/24 + // example: sg-09a093729ef9382a6_ingress_92_0_65536_10.0.3.0/24_10.0.4.0/24 + // example: sg-09a093729ef9382a6_egress_tcp_8000_8000_10.0.3.0/24 + // example: sg-09a093729ef9382a6_egress_tcp_8000_8000_pl-34800000 + // example: sg-09a093729ef9382a6_ingress_all_0_65536_sg-08123412342323 + // example: sg-09a093729ef9382a6_ingress_tcp_100_121_10.1.0.0/16_2001:db8::/48_10.2.0.0/16_2002:db8::/48 + parts := strings.Split(d.Id(), securityGroupRuleIDSeparator) + + if len(parts) < 6 { + return nil, invalidIDError("too few parts") } - if b[i].GroupName != nil && b[j].GroupName != nil { - return aws.StringValue(b[i].GroupName) < aws.StringValue(b[j].GroupName) + + securityGroupID := parts[0] + ruleType := parts[1] + protocol := parts[2] + fromPort := parts[3] + toPort := parts[4] + sources := parts[5:] + + if !strings.HasPrefix(securityGroupID, "sg-") { + return nil, invalidIDError("invalid Security Group ID") } - //lintignore:R009 - panic("mismatched security group rules, may be a terraform bug") + if ruleType != securityGroupRuleTypeIngress && ruleType != securityGroupRuleTypeEgress { + return nil, invalidIDError("expecting 'ingress' or 'egress'") + } + + if _, ok := securityGroupProtocolIntegers[protocol]; !ok { + if _, err := strconv.Atoi(protocol); err != nil { + return nil, invalidIDError("protocol must be tcp/udp/icmp/icmpv6/all or a number") + } + } + + protocolName := ProtocolForValue(protocol) + if protocolName == "icmp" || protocolName == "icmpv6" { + if v, err := strconv.Atoi(fromPort); err != nil || v < -1 || v > 255 { + return nil, invalidIDError("invalid icmp type") + } else if v, err := strconv.Atoi(toPort); err != nil || v < -1 || v > 255 { + return nil, invalidIDError("invalid icmp code") + } + } else { + if p1, err := strconv.Atoi(fromPort); err != nil { + return nil, invalidIDError("invalid from_port") + } else if p2, err := strconv.Atoi(toPort); err != nil { + return nil, invalidIDError("invalid to_port") + } else if p2 < p1 { + return nil, invalidIDError("to_port lower than from_port") + } + } + + for _, v := range sources { + // will be properly validated later + if v != "self" && !strings.Contains(v, "sg-") && !strings.Contains(v, "pl-") && !strings.Contains(v, ":") && !strings.Contains(v, ".") { + return nil, invalidIDError("source must be cidr, ipv6cidr, prefix list, 'self', or a Security Group ID") + } + } + + d.Set("security_group_id", securityGroupID) + d.Set("type", ruleType) + d.Set("protocol", protocolName) + if v, err := strconv.Atoi(fromPort); err == nil { + d.Set("from_port", v) + } + if v, err := strconv.Atoi(toPort); err == nil { + d.Set("to_port", v) + } + d.Set("self", false) + + var cidrBlocks, ipv6CIDRBlocks, prefixListIDs []string + + for _, v := range sources { + switch { + case v == "self": + d.Set("self", true) + case strings.Contains(v, "sg-"): + d.Set("source_security_group_id", v) + case strings.Contains(v, ":"): + ipv6CIDRBlocks = append(ipv6CIDRBlocks, v) + case strings.Contains(v, "pl-"): + prefixListIDs = append(prefixListIDs, v) + default: + cidrBlocks = append(cidrBlocks, v) + } + } + + d.Set("cidr_blocks", cidrBlocks) + d.Set("ipv6_cidr_blocks", ipv6CIDRBlocks) + d.Set("prefix_list_ids", prefixListIDs) + + return []*schema.ResourceData{d}, nil } func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) (*ec2.IpPermission, string) { @@ -520,6 +591,26 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) ( return rule, description } +const securityGroupRuleIDSeparator = "_" + +// byGroupPair implements sort.Interface for []*ec2.UserIDGroupPairs based on +// GroupID or GroupName field (only one should be set). +type byGroupPair []*ec2.UserIdGroupPair + +func (b byGroupPair) Len() int { return len(b) } +func (b byGroupPair) Swap(i, j int) { b[i], b[j] = b[j], b[i] } +func (b byGroupPair) Less(i, j int) bool { + if b[i].GroupId != nil && b[j].GroupId != nil { + return aws.StringValue(b[i].GroupId) < aws.StringValue(b[j].GroupId) + } + if b[i].GroupName != nil && b[j].GroupName != nil { + return aws.StringValue(b[i].GroupName) < aws.StringValue(b[j].GroupName) + } + + //lintignore:R009 + panic("mismatched security group rules, may be a terraform bug") +} + func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermission) string { var buf bytes.Buffer @@ -572,7 +663,7 @@ func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermi } if len(ip.UserIdGroupPairs) > 0 { - sort.Sort(ByGroupPair(ip.UserIdGroupPairs)) + sort.Sort(byGroupPair(ip.UserIdGroupPairs)) for _, pair := range ip.UserIdGroupPairs { if pair.GroupId != nil { buf.WriteString(fmt.Sprintf("%s-", *pair.GroupId)) @@ -590,124 +681,6 @@ func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermi return fmt.Sprintf("sgrule-%d", create.StringHashcode(buf.String())) } -// validateSecurityGroupRuleImportString does minimal validation of import string without going to AWS -func validateSecurityGroupRuleImportString(importStr string) ([]string, error) { - // example: sg-09a093729ef9382a6_ingress_tcp_8000_8000_10.0.3.0/24 - // example: sg-09a093729ef9382a6_ingress_92_0_65536_10.0.3.0/24_10.0.4.0/24 - // example: sg-09a093729ef9382a6_egress_tcp_8000_8000_10.0.3.0/24 - // example: sg-09a093729ef9382a6_egress_tcp_8000_8000_pl-34800000 - // example: sg-09a093729ef9382a6_ingress_all_0_65536_sg-08123412342323 - // example: sg-09a093729ef9382a6_ingress_tcp_100_121_10.1.0.0/16_2001:db8::/48_10.2.0.0/16_2002:db8::/48 - - log.Printf("[DEBUG] Validating import string %s", importStr) - - importParts := strings.Split(strings.ToLower(importStr), "_") - errStr := "unexpected format of import string (%q), expected SECURITYGROUPID_TYPE_PROTOCOL_FROMPORT_TOPORT_SOURCE[_SOURCE]*: %s" - if len(importParts) < 6 { - return nil, fmt.Errorf(errStr, importStr, "too few parts") - } - - sgID := importParts[0] - ruleType := importParts[1] - protocol := importParts[2] - fromPort := importParts[3] - toPort := importParts[4] - sources := importParts[5:] - - if !strings.HasPrefix(sgID, "sg-") { - return nil, fmt.Errorf(errStr, importStr, "invalid security group ID") - } - - if ruleType != securityGroupRuleTypeIngress && ruleType != securityGroupRuleTypeEgress { - return nil, fmt.Errorf(errStr, importStr, "expecting 'ingress' or 'egress'") - } - - if _, ok := securityGroupProtocolIntegers[protocol]; !ok { - if _, err := strconv.Atoi(protocol); err != nil { - return nil, fmt.Errorf(errStr, importStr, "protocol must be tcp/udp/icmp/icmpv6/all or a number") - } - } - - protocolName := ProtocolForValue(protocol) - if protocolName == "icmp" || protocolName == "icmpv6" { - if itype, err := strconv.Atoi(fromPort); err != nil || itype < -1 || itype > 255 { - return nil, fmt.Errorf(errStr, importStr, "invalid icmp type") - } else if icode, err := strconv.Atoi(toPort); err != nil || icode < -1 || icode > 255 { - return nil, fmt.Errorf(errStr, importStr, "invalid icmp code") - } - } else { - if p1, err := strconv.Atoi(fromPort); err != nil { - return nil, fmt.Errorf(errStr, importStr, "invalid from_port") - } else if p2, err := strconv.Atoi(toPort); err != nil { - return nil, fmt.Errorf(errStr, importStr, "invalid to_port") - } else if p2 < p1 { - return nil, fmt.Errorf(errStr, importStr, "to_port lower than from_port") - } - } - - for _, source := range sources { - // will be properly validated later - if source != "self" && !strings.Contains(source, "sg-") && !strings.Contains(source, "pl-") && !strings.Contains(source, ":") && !strings.Contains(source, ".") { - return nil, fmt.Errorf(errStr, importStr, "source must be cidr, ipv6cidr, prefix list, 'self', or a sg ID") - } - } - - log.Printf("[DEBUG] Validated import string %s", importStr) - return importParts, nil -} - -func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []string) error { - log.Printf("[DEBUG] Populating resource data on import: %v", importParts) - - sgID := importParts[0] - ruleType := importParts[1] - protocol := importParts[2] - fromPort, err := strconv.Atoi(importParts[3]) - if err != nil { - return err - } - toPort, err := strconv.Atoi(importParts[4]) - if err != nil { - return err - } - sources := importParts[5:] - - d.Set("security_group_id", sgID) - - if ruleType == securityGroupRuleTypeIngress { - d.Set("type", ruleType) - } else { - d.Set("type", "egress") - } - - d.Set("protocol", ProtocolForValue(protocol)) - d.Set("from_port", fromPort) - d.Set("to_port", toPort) - - d.Set("self", false) - var cidrs []string - var prefixList []string - var ipv6cidrs []string - for _, source := range sources { - if source == "self" { - d.Set("self", true) - } else if strings.Contains(source, "sg-") { - d.Set("source_security_group_id", source) - } else if strings.Contains(source, "pl-") { - prefixList = append(prefixList, source) - } else if strings.Contains(source, ":") { - ipv6cidrs = append(ipv6cidrs, source) - } else { - cidrs = append(cidrs, source) - } - } - d.Set("ipv6_cidr_blocks", ipv6cidrs) - d.Set("cidr_blocks", cidrs) - d.Set("prefix_list_ids", prefixList) - - return nil -} - func expandIpPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPermission { // nosemgrep:caps5-in-func-name apiObject := &ec2.IpPermission{ IpProtocol: aws.String(ProtocolForValue(d.Get("protocol").(string))), From 8fcc53e61125d27479961d47f9ff4cbdc4f6ab3d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 8 Jul 2022 11:07:41 -0400 Subject: [PATCH 098/120] r/aws_security_group: Tidy up resource Create. --- internal/service/ec2/vpc_security_group.go | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index 660ef32c2ab7..5fc4ce9bfff1 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -187,7 +187,7 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error output, err := conn.CreateSecurityGroup(input) if err != nil { - return fmt.Errorf("error creating Security Group (%s): %w", name, err) + return fmt.Errorf("creating Security Group (%s): %w", name, err) } d.SetId(aws.StringValue(output.GroupId)) @@ -196,11 +196,11 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error group, err := WaitSecurityGroupCreated(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return fmt.Errorf("error waiting for Security Group (%s) create: %w", d.Id(), err) + return fmt.Errorf("waiting for Security Group (%s) create: %w", d.Id(), 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. + // 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. if aws.StringValue(group.VpcId) != "" { input := &ec2.RevokeSecurityGroupEgressInput{ GroupId: aws.String(d.Id()), @@ -219,7 +219,7 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error } if _, err := conn.RevokeSecurityGroupEgress(input); err != nil { - return fmt.Errorf("error revoking default egress rule for Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("revoking default IPv4 egress rule for Security Group (%s): %w", d.Id(), err) } input = &ec2.RevokeSecurityGroupEgressInput{ @@ -239,13 +239,11 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error } if _, err := conn.RevokeSecurityGroupEgress(input); 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 we have a NotFound or InvalidParameterValue, then we are trying to remove the default IPv6 egress of a non-IPv6 enabled SG. if !tfawserr.ErrCodeEquals(err, errCodeInvalidPermissionNotFound) && !tfawserr.ErrMessageContains(err, errCodeInvalidParameterValue, "remote-ipv6-range") { - return fmt.Errorf("error revoking default IPv6 egress rule for Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("revoking default IPv6 egress rule for Security Group (%s): %w", d.Id(), err) } } - } return resourceSecurityGroupUpdate(d, meta) From 22a1e26ab9dc8dc89f79509be4106475a6e0d6bd Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 8 Jul 2022 11:18:36 -0400 Subject: [PATCH 099/120] r/aws_security_group: Start to tidy up resource Read. --- internal/service/ec2/vpc_security_group.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index 5fc4ce9bfff1..8e1b7b4e801d 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -257,13 +257,13 @@ func resourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { sg, err := FindSecurityGroupByID(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Security Group %s not found, removing from state", d.Id()) + log.Printf("[WARN] Security Group (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error reading Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("reading Security Group (%s): %w", d.Id(), err) } remoteIngressRules := SecurityGroupIPPermGather(d.Id(), sg.IpPermissions, sg.OwnerId) @@ -293,22 +293,22 @@ func resourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { d.Set("vpc_id", sg.VpcId) if err := d.Set("ingress", ingressRules); err != nil { - return fmt.Errorf("error setting ingress: %w", err) + return fmt.Errorf("setting ingress: %w", err) } if err := d.Set("egress", egressRules); err != nil { - return fmt.Errorf("error setting egress: %w", err) + return fmt.Errorf("setting egress: %w", err) } tags := KeyValueTags(sg.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil From 39d0571045e921da23bdfacc139ea02123e13f0e Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 19 Jul 2022 16:34:10 -0400 Subject: [PATCH 100/120] r/aws_security_group: Tidy up resource Delete. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroup_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroup_ -timeout 180m === RUN TestAccVPCSecurityGroup_basic === PAUSE TestAccVPCSecurityGroup_basic === RUN TestAccVPCSecurityGroup_basicEC2Classic === PAUSE TestAccVPCSecurityGroup_basicEC2Classic === RUN TestAccVPCSecurityGroup_disappears === PAUSE TestAccVPCSecurityGroup_disappears === RUN TestAccVPCSecurityGroup_nameGenerated === PAUSE TestAccVPCSecurityGroup_nameGenerated === RUN TestAccVPCSecurityGroup_nameTerraformPrefix === PAUSE TestAccVPCSecurityGroup_nameTerraformPrefix === RUN TestAccVPCSecurityGroup_namePrefix === PAUSE TestAccVPCSecurityGroup_namePrefix === RUN TestAccVPCSecurityGroup_namePrefixTerraform === PAUSE TestAccVPCSecurityGroup_namePrefixTerraform === RUN TestAccVPCSecurityGroup_tags === PAUSE TestAccVPCSecurityGroup_tags === RUN TestAccVPCSecurityGroup_allowAll === PAUSE TestAccVPCSecurityGroup_allowAll === RUN TestAccVPCSecurityGroup_sourceSecurityGroup === PAUSE TestAccVPCSecurityGroup_sourceSecurityGroup === RUN TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules === PAUSE TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules === RUN TestAccVPCSecurityGroup_ipRangesWithSameRules === PAUSE TestAccVPCSecurityGroup_ipRangesWithSameRules === RUN TestAccVPCSecurityGroup_egressMode === PAUSE TestAccVPCSecurityGroup_egressMode === RUN TestAccVPCSecurityGroup_ingressMode === PAUSE TestAccVPCSecurityGroup_ingressMode === RUN TestAccVPCSecurityGroup_ruleGathering === PAUSE TestAccVPCSecurityGroup_ruleGathering === RUN TestAccVPCSecurityGroup_forceRevokeRulesTrue === PAUSE TestAccVPCSecurityGroup_forceRevokeRulesTrue === RUN TestAccVPCSecurityGroup_forceRevokeRulesFalse === PAUSE TestAccVPCSecurityGroup_forceRevokeRulesFalse === RUN TestAccVPCSecurityGroup_change === PAUSE TestAccVPCSecurityGroup_change === RUN TestAccVPCSecurityGroup_ipv6 === PAUSE TestAccVPCSecurityGroup_ipv6 === RUN TestAccVPCSecurityGroup_self === PAUSE TestAccVPCSecurityGroup_self === RUN TestAccVPCSecurityGroup_vpc === PAUSE TestAccVPCSecurityGroup_vpc === RUN TestAccVPCSecurityGroup_vpcNegOneIngress === PAUSE TestAccVPCSecurityGroup_vpcNegOneIngress === RUN TestAccVPCSecurityGroup_vpcProtoNumIngress === PAUSE TestAccVPCSecurityGroup_vpcProtoNumIngress === RUN TestAccVPCSecurityGroup_multiIngress === PAUSE TestAccVPCSecurityGroup_multiIngress === RUN TestAccVPCSecurityGroup_ruleDescription === PAUSE TestAccVPCSecurityGroup_ruleDescription === RUN TestAccVPCSecurityGroup_defaultEgressVPC === PAUSE TestAccVPCSecurityGroup_defaultEgressVPC === RUN TestAccVPCSecurityGroup_drift === PAUSE TestAccVPCSecurityGroup_drift === RUN TestAccVPCSecurityGroup_driftComplex === PAUSE TestAccVPCSecurityGroup_driftComplex === RUN TestAccVPCSecurityGroup_invalidCIDRBlock === PAUSE TestAccVPCSecurityGroup_invalidCIDRBlock === RUN TestAccVPCSecurityGroup_cidrAndGroups === PAUSE TestAccVPCSecurityGroup_cidrAndGroups === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === RUN TestAccVPCSecurityGroup_egressWithPrefixList === PAUSE TestAccVPCSecurityGroup_egressWithPrefixList === RUN TestAccVPCSecurityGroup_ingressWithPrefixList === PAUSE TestAccVPCSecurityGroup_ingressWithPrefixList === RUN TestAccVPCSecurityGroup_ipv4AndIPv6Egress === PAUSE TestAccVPCSecurityGroup_ipv4AndIPv6Egress === RUN TestAccVPCSecurityGroup_failWithDiffMismatch === PAUSE TestAccVPCSecurityGroup_failWithDiffMismatch === RUN TestAccVPCSecurityGroup_ruleLimitExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitExceededPrepend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededPrepend === RUN TestAccVPCSecurityGroup_ruleLimitExceededAllNew === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAllNew === RUN TestAccVPCSecurityGroup_rulesDropOnError === PAUSE TestAccVPCSecurityGroup_rulesDropOnError === CONT TestAccVPCSecurityGroup_basic === CONT TestAccVPCSecurityGroup_vpcNegOneIngress === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic (15.01s) === CONT TestAccVPCSecurityGroup_failWithDiffMismatch --- PASS: TestAccVPCSecurityGroup_basic (22.78s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededAppend --- PASS: TestAccVPCSecurityGroup_vpcNegOneIngress (23.12s) === CONT TestAccVPCSecurityGroup_rulesDropOnError --- PASS: TestAccVPCSecurityGroup_failWithDiffMismatch (24.63s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededAllNew === CONT TestAccVPCSecurityGroup_ruleLimitExceededAppend vpc_security_group_test.go:2070: Step 2/3, expected an error but got none --- FAIL: TestAccVPCSecurityGroup_ruleLimitExceededAppend (37.23s) === CONT TestAccVPCSecurityGroup_ipv4AndIPv6Egress --- PASS: TestAccVPCSecurityGroup_rulesDropOnError (40.55s) === CONT TestAccVPCSecurityGroup_ingressWithPrefixList === CONT TestAccVPCSecurityGroup_ruleLimitExceededAllNew vpc_security_group_test.go:2223: Step 2/3, expected an error but got none --- FAIL: TestAccVPCSecurityGroup_ruleLimitExceededAllNew (38.39s) === CONT TestAccVPCSecurityGroup_egressWithPrefixList --- PASS: TestAccVPCSecurityGroup_ipv4AndIPv6Egress (31.90s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededPrepend --- PASS: TestAccVPCSecurityGroup_ingressWithPrefixList (35.11s) === CONT TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend --- PASS: TestAccVPCSecurityGroup_egressWithPrefixList (36.02s) === CONT TestAccVPCSecurityGroup_forceRevokeRulesFalse === CONT TestAccVPCSecurityGroup_ruleLimitExceededPrepend vpc_security_group_test.go:2178: Step 2/3, expected an error but got none === CONT TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend vpc_security_group_test.go:2117: Step 2/3, expected an error but got none --- FAIL: TestAccVPCSecurityGroup_ruleLimitExceededPrepend (38.44s) === CONT TestAccVPCSecurityGroup_drift --- FAIL: TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend (33.88s) === CONT TestAccVPCSecurityGroup_vpc --- PASS: TestAccVPCSecurityGroup_drift (16.76s) === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC --- PASS: TestAccVPCSecurityGroup_vpc (21.76s) === CONT TestAccVPCSecurityGroup_self --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC (27.27s) === CONT TestAccVPCSecurityGroup_cidrAndGroups --- PASS: TestAccVPCSecurityGroup_self (26.29s) === CONT TestAccVPCSecurityGroup_ipv6 --- PASS: TestAccVPCSecurityGroup_cidrAndGroups (26.27s) === CONT TestAccVPCSecurityGroup_ipRangesWithSameRules --- PASS: TestAccVPCSecurityGroup_ipv6 (21.15s) === CONT TestAccVPCSecurityGroup_forceRevokeRulesTrue --- PASS: TestAccVPCSecurityGroup_ipRangesWithSameRules (23.13s) === CONT TestAccVPCSecurityGroup_ruleGathering --- PASS: TestAccVPCSecurityGroup_ruleGathering (35.64s) === CONT TestAccVPCSecurityGroup_ingressMode --- PASS: TestAccVPCSecurityGroup_ingressMode (46.97s) === CONT TestAccVPCSecurityGroup_change --- PASS: TestAccVPCSecurityGroup_change (35.98s) === CONT TestAccVPCSecurityGroup_driftComplex --- PASS: TestAccVPCSecurityGroup_driftComplex (27.53s) === CONT TestAccVPCSecurityGroup_namePrefixTerraform --- PASS: TestAccVPCSecurityGroup_namePrefixTerraform (25.87s) === CONT TestAccVPCSecurityGroup_invalidCIDRBlock --- PASS: TestAccVPCSecurityGroup_invalidCIDRBlock (1.92s) === CONT TestAccVPCSecurityGroup_ruleDescription --- PASS: TestAccVPCSecurityGroup_ruleDescription (53.56s) === CONT TestAccVPCSecurityGroup_defaultEgressVPC --- PASS: TestAccVPCSecurityGroup_defaultEgressVPC (21.75s) === CONT TestAccVPCSecurityGroup_multiIngress --- PASS: TestAccVPCSecurityGroup_multiIngress (28.36s) === CONT TestAccVPCSecurityGroup_allowAll --- PASS: TestAccVPCSecurityGroup_allowAll (23.68s) === CONT TestAccVPCSecurityGroup_sourceSecurityGroup --- PASS: TestAccVPCSecurityGroup_sourceSecurityGroup (24.54s) === CONT TestAccVPCSecurityGroup_egressMode --- PASS: TestAccVPCSecurityGroup_egressMode (47.72s) === CONT TestAccVPCSecurityGroup_nameGenerated --- PASS: TestAccVPCSecurityGroup_nameGenerated (20.78s) === CONT TestAccVPCSecurityGroup_namePrefix --- PASS: TestAccVPCSecurityGroup_namePrefix (20.63s) === CONT TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules --- PASS: TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules (27.02s) === CONT TestAccVPCSecurityGroup_disappears --- PASS: TestAccVPCSecurityGroup_disappears (17.98s) === CONT TestAccVPCSecurityGroup_basicEC2Classic --- PASS: TestAccVPCSecurityGroup_basicEC2Classic (11.14s) === CONT TestAccVPCSecurityGroup_tags --- PASS: TestAccVPCSecurityGroup_tags (48.04s) === CONT TestAccVPCSecurityGroup_vpcProtoNumIngress --- PASS: TestAccVPCSecurityGroup_vpcProtoNumIngress (21.33s) === CONT TestAccVPCSecurityGroup_nameTerraformPrefix --- PASS: TestAccVPCSecurityGroup_nameTerraformPrefix (22.17s) --- PASS: TestAccVPCSecurityGroup_forceRevokeRulesFalse (952.64s) --- PASS: TestAccVPCSecurityGroup_forceRevokeRulesTrue (981.09s) FAIL FAIL github.com/hashicorp/terraform-provider-aws/internal/service/ec2 1187.205s --- internal/service/ec2/vpc_network_interface.go | 6 +- internal/service/ec2/vpc_security_group.go | 59 +++++++++---------- internal/service/ec2/vpc_subnet.go | 2 +- 3 files changed, 32 insertions(+), 35 deletions(-) diff --git a/internal/service/ec2/vpc_network_interface.go b/internal/service/ec2/vpc_network_interface.go index 8bc55c25d528..090cc23930f8 100644 --- a/internal/service/ec2/vpc_network_interface.go +++ b/internal/service/ec2/vpc_network_interface.go @@ -1126,7 +1126,7 @@ func DeleteNetworkInterface(conn *ec2.EC2, networkInterfaceID string) error { } if err != nil { - return fmt.Errorf("error deleting EC2 Network Interface (%s): %w", networkInterfaceID, err) + return fmt.Errorf("deleting EC2 Network Interface (%s): %w", networkInterfaceID, err) } return nil @@ -1146,7 +1146,7 @@ func DetachNetworkInterface(conn *ec2.EC2, networkInterfaceID, attachmentID stri } if err != nil { - return fmt.Errorf("error detaching EC2 Network Interface (%s/%s): %w", networkInterfaceID, attachmentID, err) + return fmt.Errorf("detaching EC2 Network Interface (%s/%s): %w", networkInterfaceID, attachmentID, err) } _, err = WaitNetworkInterfaceDetached(conn, attachmentID, timeout) @@ -1156,7 +1156,7 @@ func DetachNetworkInterface(conn *ec2.EC2, networkInterfaceID, attachmentID stri } if err != nil { - return fmt.Errorf("error waiting for EC2 Network Interface (%s/%s) detach: %w", networkInterfaceID, attachmentID, err) + return fmt.Errorf("waiting for EC2 Network Interface (%s/%s) detach: %w", networkInterfaceID, attachmentID, err) } return nil diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index 8e1b7b4e801d..c2aa826af444 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -349,16 +349,18 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error conn := meta.(*conns.AWSClient).EC2Conn if err := deleteLingeringLambdaENIs(conn, "group-id", d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error deleting Lambda ENIs using Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Lambda ENIs using Security Group (%s): %w", d.Id(), 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.Id()); err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidGroupNotFound) { - return nil - } + err := forceRevokeSecurityGroupRules(conn, d.Id()) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidGroupNotFound) { + return nil + } + if err != nil { return err } } @@ -379,7 +381,7 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error deleting Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Security Group (%s): %w", d.Id(), err) } _, err = tfresource.RetryUntilNotFound(propagationTimeout, func() (interface{}, error) { @@ -387,7 +389,7 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error }) if err != nil { - return fmt.Errorf("error waiting for Security Group (%s) delete: %w", d.Id(), err) + return fmt.Errorf("waiting for Security Group (%s) delete: %w", d.Id(), err) } return nil @@ -398,34 +400,33 @@ func forceRevokeSecurityGroupRules(conn *ec2.EC2, id string) error { group, err := FindSecurityGroupByID(conn, id) if err != nil { - return fmt.Errorf("error reading Security Group (%s): %w", id, err) + return fmt.Errorf("reading Security Group (%s): %w", id, err) } if len(group.IpPermissions) > 0 { - req := &ec2.RevokeSecurityGroupIngressInput{ - GroupId: group.GroupId, + input := &ec2.RevokeSecurityGroupIngressInput{ IpPermissions: group.IpPermissions, } + if aws.StringValue(group.VpcId) == "" { - req.GroupId = nil - req.GroupName = group.GroupName + input.GroupName = group.GroupName + } else { + input.GroupId = group.GroupId } - _, err = conn.RevokeSecurityGroupIngress(req) - if err != nil { - return fmt.Errorf("error revoking Security Group (%s) ingress rules: %w", id, err) + if _, err := conn.RevokeSecurityGroupIngress(input); err != nil { + return fmt.Errorf("revoking Security Group (%s) ingress rules: %w", id, err) } } if len(group.IpPermissionsEgress) > 0 { - req := &ec2.RevokeSecurityGroupEgressInput{ + input := &ec2.RevokeSecurityGroupEgressInput{ GroupId: group.GroupId, IpPermissions: group.IpPermissionsEgress, } - _, err = conn.RevokeSecurityGroupEgress(req) - if err != nil { - return fmt.Errorf("error revoking Security Group (%s) egress rules: %w", id, err) + if _, err := conn.RevokeSecurityGroupEgress(input); err != nil { + return fmt.Errorf("revoking Security Group (%s) egress rules: %w", id, err) } } @@ -1252,7 +1253,7 @@ var securityGroupProtocolIntegers = map[string]int{ // The AWS Lambda service creates ENIs behind the scenes and keeps these around for a while // which would prevent SGs attached to such ENIs from being destroyed -func deleteLingeringLambdaENIs(conn *ec2.EC2, filterName, resourceId string, timeout time.Duration) error { +func deleteLingeringLambdaENIs(conn *ec2.EC2, filterName, resourceID string, timeout time.Duration) error { // AWS Lambda service team confirms P99 deletion time of ~35 minutes. Buffer for safety. if minimumTimeout := 45 * time.Minute; timeout < minimumTimeout { timeout = minimumTimeout @@ -1260,13 +1261,13 @@ func deleteLingeringLambdaENIs(conn *ec2.EC2, filterName, resourceId string, tim networkInterfaces, err := FindNetworkInterfaces(conn, &ec2.DescribeNetworkInterfacesInput{ Filters: BuildAttributeFilterList(map[string]string{ - filterName: resourceId, + filterName: resourceID, "description": "AWS Lambda VPC ENI*", }), }) if err != nil { - return fmt.Errorf("error listing EC2 Network Interfaces: %w", err) + return fmt.Errorf("listing EC2 Network Interfaces: %w", err) } for _, v := range networkInterfaces { @@ -1280,24 +1281,20 @@ func deleteLingeringLambdaENIs(conn *ec2.EC2, filterName, resourceId string, tim } if err != nil { - return fmt.Errorf("error waiting for Lambda ENI (%s) to become available for detachment: %w", networkInterfaceID, err) + return fmt.Errorf("waiting for Lambda ENI (%s) to become available after use: %w", networkInterfaceID, err) } v = networkInterface } if v.Attachment != nil { - err = DetachNetworkInterface(conn, networkInterfaceID, aws.StringValue(v.Attachment.AttachmentId), timeout) - - if err != nil { - return fmt.Errorf("error detaching Lambda ENI (%s): %w", networkInterfaceID, err) + if err := DetachNetworkInterface(conn, networkInterfaceID, aws.StringValue(v.Attachment.AttachmentId), timeout); err != nil { + return err } } - err = DeleteNetworkInterface(conn, networkInterfaceID) - - if err != nil { - return fmt.Errorf("error deleting Lambda ENI (%s): %w", networkInterfaceID, err) + if err := DeleteNetworkInterface(conn, networkInterfaceID); err != nil { + return err } } diff --git a/internal/service/ec2/vpc_subnet.go b/internal/service/ec2/vpc_subnet.go index c3f4ea964f39..973648a0ec59 100644 --- a/internal/service/ec2/vpc_subnet.go +++ b/internal/service/ec2/vpc_subnet.go @@ -362,7 +362,7 @@ func resourceSubnetDelete(d *schema.ResourceData, meta interface{}) error { log.Printf("[INFO] Deleting EC2 Subnet: %s", d.Id()) if err := deleteLingeringLambdaENIs(conn, "subnet-id", d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error deleting Lambda ENIs for EC2 Subnet (%s): %w", d.Id(), err) + return fmt.Errorf("error deleting Lambda ENIs using EC2 Subnet (%s): %w", d.Id(), err) } _, err := tfresource.RetryWhenAWSErrCodeEquals(d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { From bcf9d31fe6c5e6428ac8a0e3a4f017f19efe0a22 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 08:30:13 -0400 Subject: [PATCH 101/120] r/aws_default_security_group: Tidy up 'TestAccVPCDefaultSecurityGroup_VPC_basic'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_VPC_basic' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_VPC_basic -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_VPC_basic === PAUSE TestAccVPCDefaultSecurityGroup_VPC_basic === CONT TestAccVPCDefaultSecurityGroup_VPC_basic --- PASS: TestAccVPCDefaultSecurityGroup_VPC_basic (28.42s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 32.661s --- .../ec2/vpc_default_security_group_test.go | 48 +++++++++---------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 95d76b35cbce..9c9a88860810 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -6,6 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -15,6 +16,7 @@ import ( func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_default_security_group.test" vpcResourceName := "aws_vpc.test" @@ -22,10 +24,10 @@ func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { - Config: testAccVPCDefaultSecurityGroupConfig_basic, + Config: testAccVPCDefaultSecurityGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "default"), @@ -49,12 +51,11 @@ func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { }), testAccCheckDefaultSecurityGroupARN(resourceName, &group), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", acctest.ResourcePrefix), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { - Config: testAccVPCDefaultSecurityGroupConfig_basic, + Config: testAccVPCDefaultSecurityGroupConfig_basic(rName), PlanOnly: true, }, { @@ -75,7 +76,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCDefaultSecurityGroupConfig_empty, @@ -103,7 +104,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCDefaultSecurityGroupConfig_classic(), @@ -155,7 +156,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, - CheckDestroy: testAccCheckDefaultSecurityGroupDestroy, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCDefaultSecurityGroupConfig_classicEmpty(), @@ -169,12 +170,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { }) } -func testAccCheckDefaultSecurityGroupDestroy(s *terraform.State) error { - // We expect Security Group to still exist - return nil -} - -func testAccCheckDefaultSecurityGroupExists(n string, group *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckDefaultSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -187,18 +183,19 @@ func testAccCheckDefaultSecurityGroupExists(n string, group *ec2.SecurityGroup) conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - sg, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if err != nil { return err } - *group = *sg + *v = *output return nil } } -func testAccCheckDefaultSecurityGroupClassicExists(n string, group *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckDefaultSecurityGroupClassicExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -211,12 +208,13 @@ func testAccCheckDefaultSecurityGroupClassicExists(n string, group *ec2.Security conn := acctest.ProviderEC2Classic.Meta().(*conns.AWSClient).EC2Conn - sg, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) + if err != nil { return err } - *group = *sg + *v = *output return nil } @@ -234,12 +232,13 @@ func testAccCheckDefaultSecurityGroupARNClassic(resourceName string, group *ec2. } } -const testAccVPCDefaultSecurityGroupConfig_basic = ` +func testAccVPCDefaultSecurityGroupConfig_basic(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-default-security-group" + Name = %[1]q } } @@ -259,12 +258,9 @@ resource "aws_default_security_group" "test" { to_port = 8000 cidr_blocks = ["10.0.0.0/8"] } - - tags = { - Name = "tf-acc-test" - } } -` +`, rName) +} const testAccVPCDefaultSecurityGroupConfig_empty = ` resource "aws_vpc" "test" { From 5b050f21b6f3d057be4be81a3a9baa4473f2dcff Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 08:36:51 -0400 Subject: [PATCH 102/120] r/aws_default_security_group: Tidy up 'TestAccVPCDefaultSecurityGroup_VPC_empty'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_VPC_empty' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_VPC_empty -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_VPC_empty === PAUSE TestAccVPCDefaultSecurityGroup_VPC_empty === CONT TestAccVPCDefaultSecurityGroup_VPC_empty --- PASS: TestAccVPCDefaultSecurityGroup_VPC_empty (18.71s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 22.726s --- .../ec2/vpc_default_security_group_test.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 9c9a88860810..34c89cb9735f 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -70,6 +70,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_default_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -79,11 +80,13 @@ func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { - Config: testAccVPCDefaultSecurityGroupConfig_empty, + Config: testAccVPCDefaultSecurityGroupConfig_empty(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), ), }, { @@ -262,19 +265,25 @@ resource "aws_default_security_group" "test" { `, rName) } -const testAccVPCDefaultSecurityGroupConfig_empty = ` +func testAccVPCDefaultSecurityGroupConfig_empty(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "terraform-testacc-default-security-group" + Name = %[1]q } } resource "aws_default_security_group" "test" { vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} +`, rName) } -` func testAccVPCDefaultSecurityGroupConfig_classic() string { return acctest.ConfigCompose( From ce155d04e5e670bf6e0a0cf836dd136d62436ebd Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 08:41:32 -0400 Subject: [PATCH 103/120] r/aws_default_security_group: Tidy up 'TestAccVPCDefaultSecurityGroup_Classic_basic'. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_Classic_basic' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_Classic_basic -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_Classic_basic === PAUSE TestAccVPCDefaultSecurityGroup_Classic_basic === CONT TestAccVPCDefaultSecurityGroup_Classic_basic --- PASS: TestAccVPCDefaultSecurityGroup_Classic_basic (15.86s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 20.284s --- .../ec2/vpc_default_security_group_test.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 34c89cb9735f..3fc0d88d85c1 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -101,6 +101,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { var group ec2.SecurityGroup + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_default_security_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -110,7 +111,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { - Config: testAccVPCDefaultSecurityGroupConfig_classic(), + Config: testAccVPCDefaultSecurityGroupConfig_classic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDefaultSecurityGroupClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "default"), @@ -128,15 +129,15 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { testAccCheckDefaultSecurityGroupARNClassic(resourceName, &group), acctest.CheckResourceAttrAccountID(resourceName, "owner_id"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", acctest.ResourcePrefix), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), ), }, { - Config: testAccVPCDefaultSecurityGroupConfig_classic(), + Config: testAccVPCDefaultSecurityGroupConfig_classic(rName), PlanOnly: true, }, { - Config: testAccVPCDefaultSecurityGroupConfig_classic(), + Config: testAccVPCDefaultSecurityGroupConfig_classic(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -285,10 +286,8 @@ resource "aws_default_security_group" "test" { `, rName) } -func testAccVPCDefaultSecurityGroupConfig_classic() string { - return acctest.ConfigCompose( - acctest.ConfigEC2ClassicRegionProvider(), - ` +func testAccVPCDefaultSecurityGroupConfig_classic(rName string) string { + return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), fmt.Sprintf(` resource "aws_default_security_group" "test" { ingress { protocol = "6" @@ -298,10 +297,10 @@ resource "aws_default_security_group" "test" { } tags = { - Name = "tf-acc-test" + Name = %[1]q } } -`) +`, rName)) } func testAccVPCDefaultSecurityGroupConfig_classicEmpty() string { From b9add859d57d7ae1406335c61cf562040062ee1d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 08:54:39 -0400 Subject: [PATCH 104/120] r/aws_default_security_group: Tidy up 'TestAccVPCDefaultSecurityGroup_Classic_empty'. Fixes #14631. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_Classic_empty' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_Classic_empty -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_Classic_empty === PAUSE TestAccVPCDefaultSecurityGroup_Classic_empty === CONT TestAccVPCDefaultSecurityGroup_Classic_empty --- PASS: TestAccVPCDefaultSecurityGroup_Classic_empty (11.08s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 15.310s --- internal/service/ec2/vpc_default_security_group.go | 12 ++++++++---- .../service/ec2/vpc_default_security_group_test.go | 13 +++---------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group.go b/internal/service/ec2/vpc_default_security_group.go index 1bbdfd62994d..916ecae5d066 100644 --- a/internal/service/ec2/vpc_default_security_group.go +++ b/internal/service/ec2/vpc_default_security_group.go @@ -194,7 +194,8 @@ func ResourceDefaultSecurityGroup() *schema.Resource { func resourceDefaultSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig - tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig + securityGroupOpts := &ec2.DescribeSecurityGroupsInput{ Filters: []*ec2.Filter{ { @@ -248,9 +249,12 @@ func resourceDefaultSecurityGroupCreate(d *schema.ResourceData, meta interface{} log.Printf("[INFO] Default Security Group ID: %s", d.Id()) - if len(tags) > 0 { - if err := CreateTags(conn, d.Id(), tags); err != nil { - return fmt.Errorf("error adding EC2 Default Security Group (%s) tags: %w", d.Id(), err) + oTagsAll := KeyValueTags(g.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + nTagsAll := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) + + if !nTagsAll.Equal(oTagsAll) { + if err := UpdateTags(conn, d.Id(), oTagsAll.Map(), nTagsAll.Map()); err != nil { + return fmt.Errorf("updating Default Security Group (%s) tags: %w", d.Id(), err) } } diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 3fc0d88d85c1..54e836d1a2e2 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -148,11 +148,6 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { } func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { - - acctest.Skip(t, "This resource does not currently clear tags when adopting the resource") - // Additional references: - // * https://github.com/hashicorp/terraform-provider-aws/issues/14631 - var group ec2.SecurityGroup resourceName := "aws_default_security_group.test" @@ -168,6 +163,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { testAccCheckDefaultSecurityGroupClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, }, @@ -304,13 +300,10 @@ resource "aws_default_security_group" "test" { } func testAccVPCDefaultSecurityGroupConfig_classicEmpty() string { - return acctest.ConfigCompose( - acctest.ConfigEC2ClassicRegionProvider(), - ` + return acctest.ConfigCompose(acctest.ConfigEC2ClassicRegionProvider(), ` resource "aws_default_security_group" "test" { # No attributes set. -} -`) +}`) } func TestDefaultSecurityGroupMigrateState(t *testing.T) { From a098f65e878ddd5b705dc16c873c2e42a9e61fdf Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 09:00:13 -0400 Subject: [PATCH 105/120] Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_ -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_VPC_basic === PAUSE TestAccVPCDefaultSecurityGroup_VPC_basic === RUN TestAccVPCDefaultSecurityGroup_VPC_empty === PAUSE TestAccVPCDefaultSecurityGroup_VPC_empty === RUN TestAccVPCDefaultSecurityGroup_Classic_basic === PAUSE TestAccVPCDefaultSecurityGroup_Classic_basic === RUN TestAccVPCDefaultSecurityGroup_Classic_empty === PAUSE TestAccVPCDefaultSecurityGroup_Classic_empty === CONT TestAccVPCDefaultSecurityGroup_VPC_basic === CONT TestAccVPCDefaultSecurityGroup_Classic_basic === CONT TestAccVPCDefaultSecurityGroup_VPC_empty --- PASS: TestAccVPCDefaultSecurityGroup_Classic_basic (16.69s) === CONT TestAccVPCDefaultSecurityGroup_Classic_empty --- PASS: TestAccVPCDefaultSecurityGroup_VPC_empty (20.00s) --- PASS: TestAccVPCDefaultSecurityGroup_Classic_empty (8.41s) --- PASS: TestAccVPCDefaultSecurityGroup_VPC_basic (28.15s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 32.063s From b660d330135ec9ce6bc94b0b8485ba9bd8f0e949 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 10:11:06 -0400 Subject: [PATCH 106/120] r/aws_default_security_group: Reuse resourceSecurityGroupRead for resource Read. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_ -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_VPC_basic === PAUSE TestAccVPCDefaultSecurityGroup_VPC_basic === RUN TestAccVPCDefaultSecurityGroup_VPC_empty === PAUSE TestAccVPCDefaultSecurityGroup_VPC_empty === RUN TestAccVPCDefaultSecurityGroup_Classic_basic === PAUSE TestAccVPCDefaultSecurityGroup_Classic_basic === RUN TestAccVPCDefaultSecurityGroup_Classic_empty === PAUSE TestAccVPCDefaultSecurityGroup_Classic_empty === CONT TestAccVPCDefaultSecurityGroup_VPC_basic === CONT TestAccVPCDefaultSecurityGroup_Classic_basic === CONT TestAccVPCDefaultSecurityGroup_VPC_empty --- PASS: TestAccVPCDefaultSecurityGroup_Classic_basic (26.90s) === CONT TestAccVPCDefaultSecurityGroup_Classic_empty --- PASS: TestAccVPCDefaultSecurityGroup_VPC_empty (26.97s) --- PASS: TestAccVPCDefaultSecurityGroup_VPC_basic (39.09s) --- PASS: TestAccVPCDefaultSecurityGroup_Classic_empty (12.70s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 46.801s --- .../service/ec2/vpc_default_security_group.go | 293 ++---------------- internal/service/ec2/vpc_security_group.go | 121 ++++---- 2 files changed, 84 insertions(+), 330 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group.go b/internal/service/ec2/vpc_default_security_group.go index 916ecae5d066..49e2a164501d 100644 --- a/internal/service/ec2/vpc_default_security_group.go +++ b/internal/service/ec2/vpc_default_security_group.go @@ -1,20 +1,15 @@ package ec2 import ( - "bytes" "fmt" "log" - "sort" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/create" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -22,9 +17,10 @@ func ResourceDefaultSecurityGroup() *schema.Resource { //lintignore:R011 return &schema.Resource{ Create: resourceDefaultSecurityGroupCreate, - Read: resourceDefaultSecurityGroupRead, + Read: resourceSecurityGroupRead, Update: resourceDefaultSecurityGroupUpdate, - Delete: resourceDefaultSecurityGroupDelete, + Delete: schema.Noop, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -32,8 +28,12 @@ func ResourceDefaultSecurityGroup() *schema.Resource { SchemaVersion: 1, MigrateState: DefaultSecurityGroupMigrateState, + // Keep in sync with aws_security_group's schema with the following changes: + // - description is Computed-only + // - name is Computed-only + // - name_prefix is Computed-only Schema: map[string]*schema.Schema{ - "name": { + "arn": { Type: schema.TypeString, Computed: true, }, @@ -41,135 +41,13 @@ func ResourceDefaultSecurityGroup() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "vpc_id": { + "egress": securityGroupRuleSetNestedBlock, + "ingress": securityGroupRuleSetNestedBlock, + "name": { Type: schema.TypeString, - Optional: true, - ForceNew: true, Computed: true, }, - "ingress": { - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validSecurityGroupRuleDescription, - }, - "from_port": { - Type: schema.TypeInt, - Required: true, - }, - "ipv6_cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "prefix_list_ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "protocol": { - Type: schema.TypeString, - Required: true, - StateFunc: ProtocolStateFunc, - }, - "security_groups": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "self": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "to_port": { - Type: schema.TypeInt, - Required: true, - }, - }, - }, - Set: resourceDefaultSecurityGroupRuleHash, - }, - "egress": { - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validSecurityGroupRuleDescription, - }, - "from_port": { - Type: schema.TypeInt, - Required: true, - }, - "ipv6_cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, - }, - }, - "prefix_list_ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "protocol": { - Type: schema.TypeString, - Required: true, - StateFunc: ProtocolStateFunc, - }, - "security_groups": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "self": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "to_port": { - Type: schema.TypeInt, - Required: true, - }, - }, - }, - Set: resourceDefaultSecurityGroupRuleHash, - }, - "arn": { + "name_prefix": { Type: schema.TypeString, Computed: true, }, @@ -177,14 +55,20 @@ func ResourceDefaultSecurityGroup() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "tags": tftags.TagsSchema(), - "tags_all": tftags.TagsSchemaComputed(), - // This is not implemented. Added to prevent breaking changes. + // Not used. "revoke_rules_on_delete": { Type: schema.TypeBool, Default: false, Optional: true, }, + "tags": tftags.TagsSchema(), + "tags_all": tftags.TagsSchemaComputed(), + "vpc_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, }, CustomizeDiff: verify.SetTagsDiff, @@ -265,68 +149,6 @@ func resourceDefaultSecurityGroupCreate(d *schema.ResourceData, meta interface{} return resourceDefaultSecurityGroupUpdate(d, meta) } -func resourceDefaultSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).EC2Conn - defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - - group, err := FindSecurityGroupByID(conn, d.Id()) - if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Security group (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - if err != nil { - return err - } - - remoteIngressRules := SecurityGroupIPPermGather(d.Id(), group.IpPermissions, group.OwnerId) - remoteEgressRules := SecurityGroupIPPermGather(d.Id(), group.IpPermissionsEgress, group.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(group.OwnerId), - Partition: meta.(*conns.AWSClient).Partition, - Region: meta.(*conns.AWSClient).Region, - Resource: fmt.Sprintf("security-group/%s", aws.StringValue(group.GroupId)), - Service: ec2.ServiceName, - } - - d.Set("arn", sgArn.String()) - d.Set("description", group.Description) - d.Set("name", group.GroupName) - d.Set("owner_id", group.OwnerId) - d.Set("vpc_id", group.VpcId) - - if err := d.Set("ingress", ingressRules); err != nil { - return fmt.Errorf("error setting Ingress rule set for (%s): %w", d.Id(), err) - } - - if err := d.Set("egress", egressRules); err != nil { - return fmt.Errorf("error setting Egress rule set for (%s): %w", d.Id(), err) - } - - tags := KeyValueTags(group.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) - - //lintignore:AWSR002 - if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) - } - - if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) - } - - return nil -} - func resourceDefaultSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn @@ -355,12 +177,7 @@ func resourceDefaultSecurityGroupUpdate(d *schema.ResourceData, meta interface{} } } - return resourceDefaultSecurityGroupRead(d, meta) -} - -func resourceDefaultSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { - log.Printf("[WARN] Cannot destroy Default Security Group. Terraform will remove this resource from the state file, however resources may remain.") - return nil + return resourceSecurityGroupRead(d, meta) } func revokeDefaultSecurityGroupRules(meta interface{}, g *ec2.SecurityGroup) error { @@ -403,72 +220,6 @@ func revokeDefaultSecurityGroupRules(meta interface{}, g *ec2.SecurityGroup) err return nil } -func resourceDefaultSecurityGroupRuleHash(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 create.StringHashcode(buf.String()) -} - func DefaultSecurityGroupMigrateState( v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index c2aa826af444..a3da3ebfd843 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -23,15 +23,6 @@ import ( ) func ResourceSecurityGroup() *schema.Resource { - securityGroupRuleSetNestedBlock := &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: securityGroupRuleNestedBlock, - Set: SecurityGroupRuleHash, - } - //lintignore:R011 return &schema.Resource{ Create: resourceSecurityGroupCreate, @@ -51,6 +42,8 @@ func ResourceSecurityGroup() *schema.Resource { SchemaVersion: 1, MigrateState: SecurityGroupMigrateState, + // Keep in sync with aws_default_security_group's schema. + // See notes in vpc_default_security_group.go. Schema: map[string]*schema.Schema{ "arn": { Type: schema.TypeString, @@ -106,60 +99,70 @@ func ResourceSecurityGroup() *schema.Resource { // Security Group rule nested block definition. // Used in aws_security_group and aws_default_security_group ingress and egress rule sets. -var securityGroupRuleNestedBlock = &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, +var ( + securityGroupRuleSetNestedBlock = &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: securityGroupRuleNestedBlock, + Set: SecurityGroupRuleHash, + } + + securityGroupRuleNestedBlock = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidCIDRNetworkAddress, + }, }, - }, - "description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validSecurityGroupRuleDescription, - }, - "from_port": { - Type: schema.TypeInt, - Required: true, - }, - "ipv6_cidr_blocks": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ + "description": { Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, + Optional: true, + ValidateFunc: validSecurityGroupRuleDescription, + }, + "from_port": { + Type: schema.TypeInt, + Required: true, + }, + "ipv6_cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidCIDRNetworkAddress, + }, + }, + "prefix_list_ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "protocol": { + Type: schema.TypeString, + Required: true, + StateFunc: ProtocolStateFunc, + }, + "security_groups": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "self": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "to_port": { + Type: schema.TypeInt, + Required: true, }, }, - "prefix_list_ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "protocol": { - Type: schema.TypeString, - Required: true, - StateFunc: ProtocolStateFunc, - }, - "security_groups": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - "self": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "to_port": { - Type: schema.TypeInt, - Required: true, - }, - }, -} + } +) func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn From 7752a0bdf1dd8d7dc7e116ebd27d1a77cf79d861 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 10:17:28 -0400 Subject: [PATCH 107/120] r/aws_default_security_group: Use aws_security_group's MigrateState function. --- .../service/ec2/vpc_default_security_group.go | 31 +-------- .../ec2/vpc_default_security_group_test.go | 64 ------------------- .../service/ec2/vpc_security_group_migrate.go | 8 +-- .../service/ec2/vpc_security_group_test.go | 2 - 4 files changed, 6 insertions(+), 99 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group.go b/internal/service/ec2/vpc_default_security_group.go index 49e2a164501d..dfa3759aac47 100644 --- a/internal/service/ec2/vpc_default_security_group.go +++ b/internal/service/ec2/vpc_default_security_group.go @@ -7,7 +7,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/conns" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -25,8 +24,8 @@ func ResourceDefaultSecurityGroup() *schema.Resource { State: schema.ImportStatePassthrough, }, - SchemaVersion: 1, - MigrateState: DefaultSecurityGroupMigrateState, + SchemaVersion: 1, // Keep in sync with aws_security_group's schema version. + MigrateState: SecurityGroupMigrateState, // Keep in sync with aws_security_group's schema with the following changes: // - description is Computed-only @@ -219,29 +218,3 @@ func revokeDefaultSecurityGroupRules(meta interface{}, g *ec2.SecurityGroup) err return nil } - -func DefaultSecurityGroupMigrateState( - v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { - switch v { - case 0: - log.Println("[INFO] Found AWS Default Security Group state v0; migrating to v1") - return migrateDefaultSecurityGroupStateV0toV1(is) - default: - return is, fmt.Errorf("Unexpected schema version: %d", v) - } -} - -func migrateDefaultSecurityGroupStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { - if is.Empty() || is.Attributes == nil { - log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") - return is, nil - } - - log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) - - // set default for revoke_rules_on_delete - is.Attributes["revoke_rules_on_delete"] = "false" - - log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) - return is, nil -} diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 54e836d1a2e2..2a209bf9cfdc 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -305,67 +305,3 @@ resource "aws_default_security_group" "test" { # No attributes set. }`) } - -func TestDefaultSecurityGroupMigrateState(t *testing.T) { - cases := map[string]struct { - StateVersion int - Attributes map[string]string - Expected map[string]string - Meta interface{} - }{ - "v0": { - StateVersion: 0, - Attributes: map[string]string{ - "name": "test", - }, - Expected: map[string]string{ - "name": "test", - "revoke_rules_on_delete": "false", - }, - }, - } - - for tn, tc := range cases { - is := &terraform.InstanceState{ - ID: "i-abc123", - Attributes: tc.Attributes, - } - is, err := tfec2.DefaultSecurityGroupMigrateState( - tc.StateVersion, is, tc.Meta) - - if err != nil { - t.Fatalf("bad: %s, err: %#v", tn, err) - } - - for k, v := range tc.Expected { - if is.Attributes[k] != v { - t.Fatalf( - "bad: %s\n\n expected: %#v -> %#v\n got: %#v -> %#v\n in: %#v", - tn, k, v, k, is.Attributes[k], is.Attributes) - } - } - } -} - -func TestDefaultSecurityGroupMigrateState_empty(t *testing.T) { - var is *terraform.InstanceState - var meta interface{} - - // should handle nil - is, err := tfec2.DefaultSecurityGroupMigrateState(0, is, meta) - - if err != nil { - t.Fatalf("err: %#v", err) - } - if is != nil { - t.Fatalf("expected nil instancestate, got: %#v", is) - } - - // should handle non-nil but empty - is = &terraform.InstanceState{} - _, err = tfec2.DefaultSecurityGroupMigrateState(0, is, meta) - - if err != nil { - t.Fatalf("err: %#v", err) - } -} diff --git a/internal/service/ec2/vpc_security_group_migrate.go b/internal/service/ec2/vpc_security_group_migrate.go index 4cc9e74dc9b9..a83fe4313490 100644 --- a/internal/service/ec2/vpc_security_group_migrate.go +++ b/internal/service/ec2/vpc_security_group_migrate.go @@ -7,14 +7,13 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func SecurityGroupMigrateState( - v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { +func SecurityGroupMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: - log.Println("[INFO] Found AWS SecurityGroup State v0; migrating to v1") + log.Println("[INFO] Found Security Group State v0; migrating to v1") return migrateSecurityGroupStateV0toV1(is) default: - return is, fmt.Errorf("Unexpected schema version: %d", v) + return is, fmt.Errorf("unexpected schema version: %d", v) } } @@ -30,5 +29,6 @@ func migrateSecurityGroupStateV0toV1(is *terraform.InstanceState) (*terraform.In is.Attributes["revoke_rules_on_delete"] = "false" log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) + return is, nil } diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 78e0f6025a1e..2d3e4be9c3aa 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -23,8 +23,6 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// add sweeper to delete known test sgs - func TestProtocolStateFunc(t *testing.T) { cases := []struct { input interface{} From 1c626453ea9200bd06fe5034a82636113a7397e1 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 11:05:25 -0400 Subject: [PATCH 108/120] r/aws_default_security_group: Tidy up resource Create. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCDefaultSecurityGroup_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCDefaultSecurityGroup_ -timeout 180m === RUN TestAccVPCDefaultSecurityGroup_VPC_basic === PAUSE TestAccVPCDefaultSecurityGroup_VPC_basic === RUN TestAccVPCDefaultSecurityGroup_VPC_empty === PAUSE TestAccVPCDefaultSecurityGroup_VPC_empty === RUN TestAccVPCDefaultSecurityGroup_Classic_serial === RUN TestAccVPCDefaultSecurityGroup_Classic_serial/basic === RUN TestAccVPCDefaultSecurityGroup_Classic_serial/empty --- PASS: TestAccVPCDefaultSecurityGroup_Classic_serial (39.12s) --- PASS: TestAccVPCDefaultSecurityGroup_Classic_serial/basic (27.22s) --- PASS: TestAccVPCDefaultSecurityGroup_Classic_serial/empty (11.90s) === CONT TestAccVPCDefaultSecurityGroup_VPC_basic === CONT TestAccVPCDefaultSecurityGroup_VPC_empty --- PASS: TestAccVPCDefaultSecurityGroup_VPC_empty (22.89s) --- PASS: TestAccVPCDefaultSecurityGroup_VPC_basic (34.20s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 81.316s --- .../service/ec2/vpc_default_security_group.go | 143 +++--------------- .../ec2/vpc_default_security_group_test.go | 82 +++------- internal/service/ec2/vpc_default_subnet.go | 2 +- .../ec2/vpnclient_network_association_test.go | 10 +- 4 files changed, 52 insertions(+), 185 deletions(-) diff --git a/internal/service/ec2/vpc_default_security_group.go b/internal/service/ec2/vpc_default_security_group.go index dfa3759aac47..28a363a64a94 100644 --- a/internal/service/ec2/vpc_default_security_group.go +++ b/internal/service/ec2/vpc_default_security_group.go @@ -2,7 +2,6 @@ package ec2 import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" @@ -17,7 +16,7 @@ func ResourceDefaultSecurityGroup() *schema.Resource { return &schema.Resource{ Create: resourceDefaultSecurityGroupCreate, Read: resourceSecurityGroupRead, - Update: resourceDefaultSecurityGroupUpdate, + Update: resourceSecurityGroupUpdate, Delete: schema.Noop, Importer: &schema.ResourceImporter{ @@ -79,60 +78,37 @@ func resourceDefaultSecurityGroupCreate(d *schema.ResourceData, meta interface{} defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - securityGroupOpts := &ec2.DescribeSecurityGroupsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("group-name"), - Values: aws.StringSlice([]string{DefaultSecurityGroupName}), + input := &ec2.DescribeSecurityGroupsInput{ + Filters: BuildAttributeFilterList( + map[string]string{ + "group-name": DefaultSecurityGroupName, }, - }, + ), } - var vpcID string if v, ok := d.GetOk("vpc_id"); ok { - vpcID = v.(string) - securityGroupOpts.Filters = append(securityGroupOpts.Filters, &ec2.Filter{ - Name: aws.String("vpc-id"), - Values: aws.StringSlice([]string{vpcID}), - }) - } - - var err error - log.Printf("[DEBUG] Commandeer Default Security Group: %s", securityGroupOpts) - resp, err := conn.DescribeSecurityGroups(securityGroupOpts) - if err != nil { - return fmt.Errorf("Error creating Default Security Group: %w", err) - } - - var g *ec2.SecurityGroup - if vpcID != "" { - // if vpcId contains a value, then we expect just a single Security Group - // returned, as default is a protected name for each VPC, and for each - // Region on EC2 Classic - if len(resp.SecurityGroups) != 1 { - return fmt.Errorf("Error finding default security group; found (%d) groups: %s", len(resp.SecurityGroups), resp) - } - g = resp.SecurityGroups[0] + input.Filters = append(input.Filters, BuildAttributeFilterList( + map[string]string{ + "vpc-id": v.(string), + }, + )...) } else { - // we need to filter through any returned security groups for the group - // named "default", and does not belong to a VPC - for _, sg := range resp.SecurityGroups { - if sg.VpcId == nil && aws.StringValue(sg.GroupName) == DefaultSecurityGroupName { - g = sg - break - } - } + input.Filters = append(input.Filters, BuildAttributeFilterList( + map[string]string{ + "description": "default group", + }, + )...) } - if g == nil { - return fmt.Errorf("Error finding default security group: no matching group found") - } + sg, err := FindSecurityGroup(conn, input) - d.SetId(aws.StringValue(g.GroupId)) + if err != nil { + return fmt.Errorf("reading Default Security Group: %w", err) + } - log.Printf("[INFO] Default Security Group ID: %s", d.Id()) + d.SetId(aws.StringValue(sg.GroupId)) - oTagsAll := KeyValueTags(g.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + oTagsAll := KeyValueTags(sg.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) nTagsAll := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) if !nTagsAll.Equal(oTagsAll) { @@ -141,80 +117,9 @@ func resourceDefaultSecurityGroupCreate(d *schema.ResourceData, meta interface{} } } - if err := revokeDefaultSecurityGroupRules(meta, g); err != nil { + if err := forceRevokeSecurityGroupRules(conn, d.Id()); err != nil { return err } - return resourceDefaultSecurityGroupUpdate(d, meta) -} - -func resourceDefaultSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*conns.AWSClient).EC2Conn - - group, err := FindSecurityGroupByID(conn, d.Id()) - if err != nil { - return fmt.Errorf("error updating Default Security Group (%s): %w", d.Id(), err) - } - - err = resourceSecurityGroupUpdateRules(d, "ingress", meta, group) - if err != nil { - return fmt.Errorf("error updating Default Security Group (%s): %w", d.Id(), err) - } - - if d.Get("vpc_id") != nil { - err = resourceSecurityGroupUpdateRules(d, "egress", meta, group) - if err != nil { - return fmt.Errorf("error updating Default Security Group (%s): %w", d.Id(), err) - } - } - - if d.HasChange("tags_all") && !d.IsNewResource() { - o, n := d.GetChange("tags_all") - - if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating Default Security Group (%s) tags: %w", d.Id(), err) - } - } - - return resourceSecurityGroupRead(d, meta) -} - -func revokeDefaultSecurityGroupRules(meta interface{}, g *ec2.SecurityGroup) error { - conn := meta.(*conns.AWSClient).EC2Conn - - groupID := aws.StringValue(g.GroupId) - log.Printf("[WARN] Removing all ingress and egress rules found on Default Security Group (%s)", groupID) - if len(g.IpPermissionsEgress) > 0 { - req := &ec2.RevokeSecurityGroupEgressInput{ - GroupId: g.GroupId, - IpPermissions: g.IpPermissionsEgress, - } - - log.Printf("[DEBUG] Revoking default egress rules for Default Security Group for %s", groupID) - if _, err := conn.RevokeSecurityGroupEgress(req); err != nil { - return fmt.Errorf("error revoking default egress rules for Default Security Group (%s): %w", groupID, err) - } - } - if len(g.IpPermissions) > 0 { - // a limitation in EC2 Classic is that a call to RevokeSecurityGroupIngress - // cannot contain both the GroupName and the GroupId - for _, p := range g.IpPermissions { - for _, uigp := range p.UserIdGroupPairs { - if uigp.GroupId != nil && uigp.GroupName != nil { - uigp.GroupName = nil - } - } - } - req := &ec2.RevokeSecurityGroupIngressInput{ - GroupId: g.GroupId, - IpPermissions: g.IpPermissions, - } - - log.Printf("[DEBUG] Revoking default ingress rules for Default Security Group for (%s): %s", groupID, req) - if _, err := conn.RevokeSecurityGroupIngress(req); err != nil { - return fmt.Errorf("Error revoking default ingress rules for Default Security Group (%s): %w", groupID, err) - } - } - - return nil + return resourceSecurityGroupUpdate(d, meta) } diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 2a209bf9cfdc..d77047062bec 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -10,8 +10,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" - "github.com/hashicorp/terraform-provider-aws/internal/conns" - tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { @@ -29,7 +27,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_basic(t *testing.T) { { Config: testAccVPCDefaultSecurityGroupConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDefaultSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "default"), resource.TestCheckResourceAttr(resourceName, "description", "default VPC security group"), resource.TestCheckResourceAttrPair(resourceName, "vpc_id", vpcResourceName, "id"), @@ -82,7 +80,7 @@ func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { { Config: testAccVPCDefaultSecurityGroupConfig_empty(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDefaultSecurityGroupExists(resourceName, &group), + testAccCheckSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -99,12 +97,26 @@ func TestAccVPCDefaultSecurityGroup_VPC_empty(t *testing.T) { }) } -func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { +func TestAccVPCDefaultSecurityGroup_Classic_serial(t *testing.T) { + testCases := map[string]func(t *testing.T){ + "basic": testAccVPCDefaultSecurityGroup_Classic_basic, + "empty": testAccVPCDefaultSecurityGroup_Classic_empty, + } + + for name, tc := range testCases { + tc := tc + t.Run(name, func(t *testing.T) { + tc(t) + }) + } +} + +func testAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { var group ec2.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_default_security_group.test" - resource.ParallelTest(t, resource.TestCase{ + resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, @@ -113,7 +125,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { { Config: testAccVPCDefaultSecurityGroupConfig_classic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDefaultSecurityGroupClassicExists(resourceName, &group), + testAccCheckSecurityGroupEC2ClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "default"), resource.TestCheckResourceAttr(resourceName, "description", "default group"), resource.TestCheckResourceAttr(resourceName, "vpc_id", ""), @@ -147,11 +159,11 @@ func TestAccVPCDefaultSecurityGroup_Classic_basic(t *testing.T) { }) } -func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { +func testAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { var group ec2.SecurityGroup resourceName := "aws_default_security_group.test" - resource.ParallelTest(t, resource.TestCase{ + resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckEC2Classic(t) }, ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), ProviderFactories: acctest.ProviderFactories, @@ -160,7 +172,7 @@ func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { { Config: testAccVPCDefaultSecurityGroupConfig_classicEmpty(), Check: resource.ComposeTestCheckFunc( - testAccCheckDefaultSecurityGroupClassicExists(resourceName, &group), + testAccCheckSecurityGroupEC2ClassicExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -170,56 +182,6 @@ func TestAccVPCDefaultSecurityGroup_Classic_empty(t *testing.T) { }) } -func testAccCheckDefaultSecurityGroupExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 Default Security Group ID is set") - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn - - output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - - if err != nil { - return err - } - - *v = *output - - return nil - } -} - -func testAccCheckDefaultSecurityGroupClassicExists(n string, v *ec2.SecurityGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 Default Security Group ID is set") - } - - conn := acctest.ProviderEC2Classic.Meta().(*conns.AWSClient).EC2Conn - - output, err := tfec2.FindSecurityGroupByID(conn, rs.Primary.ID) - - if err != nil { - return err - } - - *v = *output - - return nil - } -} - func testAccCheckDefaultSecurityGroupARN(resourceName string, group *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { return acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "ec2", fmt.Sprintf("security-group/%s", aws.StringValue(group.GroupId)))(s) diff --git a/internal/service/ec2/vpc_default_subnet.go b/internal/service/ec2/vpc_default_subnet.go index 9a0a8151e201..40e3b028c8f0 100644 --- a/internal/service/ec2/vpc_default_subnet.go +++ b/internal/service/ec2/vpc_default_subnet.go @@ -218,7 +218,7 @@ func resourceDefaultSubnetCreate(d *schema.ResourceData, meta interface{}) error computedIPv6CIDRBlock = true } } else { - return fmt.Errorf("error reading EC2 Default Subnet (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Default Subnet (%s): %w", availabilityZone, err) } if err := modifySubnetAttributesOnCreate(conn, d, subnet, computedIPv6CIDRBlock); err != nil { diff --git a/internal/service/ec2/vpnclient_network_association_test.go b/internal/service/ec2/vpnclient_network_association_test.go index 0d80db5b7e1d..380e2b104283 100644 --- a/internal/service/ec2/vpnclient_network_association_test.go +++ b/internal/service/ec2/vpnclient_network_association_test.go @@ -40,7 +40,7 @@ func testAccClientVPNNetworkAssociation_basic(t *testing.T) { resource.TestCheckResourceAttrPair(resourceName, "id", resourceName, "association_id"), resource.TestCheckResourceAttrPair(resourceName, "client_vpn_endpoint_id", endpointResourceName, "id"), resource.TestCheckResourceAttrPair(resourceName, "subnet_id", subnetResourceName, "id"), - testAccCheckDefaultSecurityGroupExists(defaultSecurityGroupResourceName, &group), + testAccCheckSecurityGroupExists(defaultSecurityGroupResourceName, &group), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), testAccCheckClientVPNNetworkAssociationSecurityGroupID(resourceName, "security_groups.*", &group), resource.TestCheckResourceAttrPair(resourceName, "vpc_id", vpcResourceName, "id"), @@ -82,7 +82,7 @@ func testAccClientVPNNetworkAssociation_multipleSubnets(t *testing.T) { resource.TestCheckResourceAttrPair(resourceNames[0], "client_vpn_endpoint_id", endpointResourceName, "id"), resource.TestCheckResourceAttrPair(resourceNames[0], "subnet_id", subnetResourceNames[0], "id"), resource.TestCheckResourceAttrPair(resourceNames[1], "subnet_id", subnetResourceNames[1], "id"), - testAccCheckDefaultSecurityGroupExists(defaultSecurityGroupResourceName, &group), + testAccCheckSecurityGroupExists(defaultSecurityGroupResourceName, &group), resource.TestCheckResourceAttr(resourceNames[0], "security_groups.#", "1"), testAccCheckClientVPNNetworkAssociationSecurityGroupID(resourceNames[0], "security_groups.*", &group), resource.TestCheckResourceAttrPair(resourceNames[0], "vpc_id", vpcResourceName, "id"), @@ -145,8 +145,8 @@ func testAccClientVPNNetworkAssociation_securityGroups(t *testing.T) { Config: testAccClientVPNNetworkAssociationConfig_twoSecurityGroups(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClientVPNNetworkAssociationExists(resourceName, &assoc1), - testAccCheckDefaultSecurityGroupExists(securityGroup1ResourceName, &group11), - testAccCheckDefaultSecurityGroupExists(securityGroup2ResourceName, &group12), + testAccCheckSecurityGroupExists(securityGroup1ResourceName, &group11), + testAccCheckSecurityGroupExists(securityGroup2ResourceName, &group12), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "2"), testAccCheckClientVPNNetworkAssociationSecurityGroupID(resourceName, "security_groups.*", &group11), testAccCheckClientVPNNetworkAssociationSecurityGroupID(resourceName, "security_groups.*", &group12), @@ -162,7 +162,7 @@ func testAccClientVPNNetworkAssociation_securityGroups(t *testing.T) { Config: testAccClientVPNNetworkAssociationConfig_oneSecurityGroup(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckClientVPNNetworkAssociationExists(resourceName, &assoc2), - testAccCheckDefaultSecurityGroupExists(securityGroup1ResourceName, &group21), + testAccCheckSecurityGroupExists(securityGroup1ResourceName, &group21), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), testAccCheckClientVPNNetworkAssociationSecurityGroupID(resourceName, "security_groups.*", &group21), ), From 26f8cb3b50865b9c250664869389657cd9409a88 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 11:30:50 -0400 Subject: [PATCH 109/120] r/aws_security_group: Tidy up resource Update. --- internal/service/ec2/vpc_security_group.go | 170 +++++++++++---------- 1 file changed, 86 insertions(+), 84 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index a3da3ebfd843..ec90b638aacb 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -321,19 +321,22 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error conn := meta.(*conns.AWSClient).EC2Conn group, err := FindSecurityGroupByID(conn, d.Id()) + if err != nil { - return fmt.Errorf("error updating Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("reading Security Group (%s): %w", d.Id(), err) } - err = resourceSecurityGroupUpdateRules(d, "ingress", meta, group) + err = updateSecurityGroupRules(conn, d, securityGroupRuleTypeIngress, group) + if err != nil { - return fmt.Errorf("error updating Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("updating Security Group (%s) %s rules: %w", d.Id(), securityGroupRuleTypeIngress, err) } if d.Get("vpc_id") != nil { - err = resourceSecurityGroupUpdateRules(d, "egress", meta, group) + err = updateSecurityGroupRules(conn, d, securityGroupRuleTypeEgress, group) + if err != nil { - return fmt.Errorf("error updating Security Group (%s): %w", d.Id(), err) + return fmt.Errorf("updating Security Group (%s) %s rules: %w", d.Id(), securityGroupRuleTypeEgress, err) } } @@ -341,7 +344,7 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating Security Group (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating Security Group (%s) tags: %w", d.Id(), err) } } @@ -590,100 +593,99 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, return rules } -func resourceSecurityGroupUpdateRules( - d *schema.ResourceData, ruleset string, - meta interface{}, group *ec2.SecurityGroup) error { +func updateSecurityGroupRules(conn *ec2.EC2, d *schema.ResourceData, ruleType string, group *ec2.SecurityGroup) error { + if !d.HasChange(ruleType) { + return nil + } - if d.HasChange(ruleset) { - o, n := d.GetChange(ruleset) - if o == nil { - o = new(schema.Set) - } - if n == nil { - n = new(schema.Set) - } + o, n := d.GetChange(ruleType) + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } - os := SecurityGroupExpandRules(o.(*schema.Set)) - ns := SecurityGroupExpandRules(n.(*schema.Set)) + os := SecurityGroupExpandRules(o.(*schema.Set)) + ns := SecurityGroupExpandRules(n.(*schema.Set)) - remove, err := ExpandIPPerms(group, SecurityGroupCollapseRules(ruleset, os.Difference(ns).List())) - if err != nil { - return err - } - add, err := ExpandIPPerms(group, SecurityGroupCollapseRules(ruleset, ns.Difference(os).List())) - if err != nil { - return err - } + del, err := ExpandIPPerms(group, SecurityGroupCollapseRules(ruleType, os.Difference(ns).List())) - // TODO: We need to handle partial state better in the in-between - // in this update. + if err != nil { + return err + } - // 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. + add, err := ExpandIPPerms(group, SecurityGroupCollapseRules(ruleType, ns.Difference(os).List())) - if len(remove) > 0 || len(add) > 0 { - conn := meta.(*conns.AWSClient).EC2Conn + if err != nil { + return err + } - var err error - if len(remove) > 0 { - log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v", - group, ruleset, remove) + // TODO: We need to handle partial state better in the in-between + // in this update. - 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 aws.StringValue(group.VpcId) == "" { - req.GroupId = nil - req.GroupName = group.GroupName - } - _, err = conn.RevokeSecurityGroupIngress(req) - } + // 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 err != nil { - return fmt.Errorf("error revoking Security Group (%s) rules: %w", ruleset, err) - } + isVPC := aws.StringValue(group.VpcId) != "" + + if len(del) > 0 { + if ruleType == securityGroupRuleTypeEgress { + input := &ec2.RevokeSecurityGroupEgressInput{ + GroupId: group.GroupId, + IpPermissions: del, } - 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 aws.StringValue(group.VpcId) == "" { - req.GroupId = nil - req.GroupName = group.GroupName - } + _, err = conn.RevokeSecurityGroupEgress(input) + } else { + input := &ec2.RevokeSecurityGroupIngressInput{ + IpPermissions: del, + } - _, err = conn.AuthorizeSecurityGroupIngress(req) - } + if isVPC { + input.GroupId = group.GroupId + } else { + input.GroupName = group.GroupName + } - if err != nil { - return fmt.Errorf("error authorizing Security Group (%s) rules: %w", ruleset, err) - } + _, err = conn.RevokeSecurityGroupIngress(input) + } + + if err != nil { + return fmt.Errorf("revoking Security Group (%s) rules: %w", ruleType, err) + } + } + + if len(add) > 0 { + if ruleType == securityGroupRuleTypeEgress { + input := &ec2.AuthorizeSecurityGroupEgressInput{ + GroupId: group.GroupId, + IpPermissions: add, } + + _, err = conn.AuthorizeSecurityGroupEgress(input) + } else { + input := &ec2.AuthorizeSecurityGroupIngressInput{ + IpPermissions: add, + } + + if isVPC { + input.GroupId = group.GroupId + } else { + input.GroupName = group.GroupName + } + + _, err = conn.AuthorizeSecurityGroupIngress(input) + } + + if err != nil { + return fmt.Errorf("authorizing Security Group (%s) rules: %w", ruleType, err) } } + return nil } From 4a8035f1df97baff6fcc01c546ad9b3c947a481d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 12:05:39 -0400 Subject: [PATCH 110/120] r/aws_security_group: Use IPv4 and IPv6 specific CIDR block validators. --- internal/service/ec2/vpc_security_group.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index ec90b638aacb..7a56fb29345d 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -116,7 +116,7 @@ var ( Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, + ValidateFunc: verify.ValidIPv4CIDRNetworkAddress, }, }, "description": { @@ -133,7 +133,7 @@ var ( Optional: true, Elem: &schema.Schema{ Type: schema.TypeString, - ValidateFunc: verify.ValidCIDRNetworkAddress, + ValidateFunc: verify.ValidIPv6CIDRNetworkAddress, }, }, "prefix_list_ids": { From 573b1067e27ea8bb27fbf7217bcadf72b72460cf Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 12:16:04 -0400 Subject: [PATCH 111/120] r/aws_security_group: Restore 'Set:schema.HashString' on rule description. --- internal/service/ec2/vpc_security_group.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index 7a56fb29345d..be954b7f4c57 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -150,6 +150,7 @@ var ( Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, // Required to ensure consistent hashing }, "self": { Type: schema.TypeBool, From 1f08f7891d10e6453ecb8d136af3226b9f2bef77 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 12:51:19 -0400 Subject: [PATCH 112/120] % EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT=60 make testacc TESTARGS='-run=TestAccVPCSecurityGroup_' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroup_ -timeout 180m === RUN TestAccVPCSecurityGroup_basic === PAUSE TestAccVPCSecurityGroup_basic === RUN TestAccVPCSecurityGroup_basicEC2Classic === PAUSE TestAccVPCSecurityGroup_basicEC2Classic === RUN TestAccVPCSecurityGroup_disappears === PAUSE TestAccVPCSecurityGroup_disappears === RUN TestAccVPCSecurityGroup_nameGenerated === PAUSE TestAccVPCSecurityGroup_nameGenerated === RUN TestAccVPCSecurityGroup_nameTerraformPrefix === PAUSE TestAccVPCSecurityGroup_nameTerraformPrefix === RUN TestAccVPCSecurityGroup_namePrefix === PAUSE TestAccVPCSecurityGroup_namePrefix === RUN TestAccVPCSecurityGroup_namePrefixTerraform === PAUSE TestAccVPCSecurityGroup_namePrefixTerraform === RUN TestAccVPCSecurityGroup_tags === PAUSE TestAccVPCSecurityGroup_tags === RUN TestAccVPCSecurityGroup_allowAll === PAUSE TestAccVPCSecurityGroup_allowAll === RUN TestAccVPCSecurityGroup_sourceSecurityGroup === PAUSE TestAccVPCSecurityGroup_sourceSecurityGroup === RUN TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules === PAUSE TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules === RUN TestAccVPCSecurityGroup_ipRangesWithSameRules === PAUSE TestAccVPCSecurityGroup_ipRangesWithSameRules === RUN TestAccVPCSecurityGroup_egressMode === PAUSE TestAccVPCSecurityGroup_egressMode === RUN TestAccVPCSecurityGroup_ingressMode === PAUSE TestAccVPCSecurityGroup_ingressMode === RUN TestAccVPCSecurityGroup_ruleGathering === PAUSE TestAccVPCSecurityGroup_ruleGathering === RUN TestAccVPCSecurityGroup_forceRevokeRulesTrue === PAUSE TestAccVPCSecurityGroup_forceRevokeRulesTrue === RUN TestAccVPCSecurityGroup_forceRevokeRulesFalse === PAUSE TestAccVPCSecurityGroup_forceRevokeRulesFalse === RUN TestAccVPCSecurityGroup_change === PAUSE TestAccVPCSecurityGroup_change === RUN TestAccVPCSecurityGroup_ipv6 === PAUSE TestAccVPCSecurityGroup_ipv6 === RUN TestAccVPCSecurityGroup_self === PAUSE TestAccVPCSecurityGroup_self === RUN TestAccVPCSecurityGroup_vpc === PAUSE TestAccVPCSecurityGroup_vpc === RUN TestAccVPCSecurityGroup_vpcNegOneIngress === PAUSE TestAccVPCSecurityGroup_vpcNegOneIngress === RUN TestAccVPCSecurityGroup_vpcProtoNumIngress === PAUSE TestAccVPCSecurityGroup_vpcProtoNumIngress === RUN TestAccVPCSecurityGroup_multiIngress === PAUSE TestAccVPCSecurityGroup_multiIngress === RUN TestAccVPCSecurityGroup_ruleDescription === PAUSE TestAccVPCSecurityGroup_ruleDescription === RUN TestAccVPCSecurityGroup_defaultEgressVPC === PAUSE TestAccVPCSecurityGroup_defaultEgressVPC === RUN TestAccVPCSecurityGroup_drift === PAUSE TestAccVPCSecurityGroup_drift === RUN TestAccVPCSecurityGroup_driftComplex === PAUSE TestAccVPCSecurityGroup_driftComplex === RUN TestAccVPCSecurityGroup_invalidCIDRBlock === PAUSE TestAccVPCSecurityGroup_invalidCIDRBlock === RUN TestAccVPCSecurityGroup_cidrAndGroups === PAUSE TestAccVPCSecurityGroup_cidrAndGroups === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC === RUN TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === PAUSE TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === RUN TestAccVPCSecurityGroup_egressWithPrefixList === PAUSE TestAccVPCSecurityGroup_egressWithPrefixList === RUN TestAccVPCSecurityGroup_ingressWithPrefixList === PAUSE TestAccVPCSecurityGroup_ingressWithPrefixList === RUN TestAccVPCSecurityGroup_ipv4AndIPv6Egress === PAUSE TestAccVPCSecurityGroup_ipv4AndIPv6Egress === RUN TestAccVPCSecurityGroup_failWithDiffMismatch === PAUSE TestAccVPCSecurityGroup_failWithDiffMismatch === RUN TestAccVPCSecurityGroup_ruleLimitExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === PAUSE TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend === RUN TestAccVPCSecurityGroup_ruleLimitExceededPrepend === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededPrepend === RUN TestAccVPCSecurityGroup_ruleLimitExceededAllNew === PAUSE TestAccVPCSecurityGroup_ruleLimitExceededAllNew === RUN TestAccVPCSecurityGroup_rulesDropOnError === PAUSE TestAccVPCSecurityGroup_rulesDropOnError === CONT TestAccVPCSecurityGroup_basic === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic === CONT TestAccVPCSecurityGroup_vpcNegOneIngress --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsClassic (16.85s) === CONT TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC --- PASS: TestAccVPCSecurityGroup_vpcNegOneIngress (25.33s) === CONT TestAccVPCSecurityGroup_cidrAndGroups --- PASS: TestAccVPCSecurityGroup_basic (28.81s) === CONT TestAccVPCSecurityGroup_invalidCIDRBlock --- PASS: TestAccVPCSecurityGroup_invalidCIDRBlock (2.46s) === CONT TestAccVPCSecurityGroup_driftComplex --- PASS: TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC (28.59s) === CONT TestAccVPCSecurityGroup_drift --- PASS: TestAccVPCSecurityGroup_cidrAndGroups (29.66s) === CONT TestAccVPCSecurityGroup_defaultEgressVPC --- PASS: TestAccVPCSecurityGroup_driftComplex (28.62s) === CONT TestAccVPCSecurityGroup_ruleDescription --- PASS: TestAccVPCSecurityGroup_drift (20.65s) === CONT TestAccVPCSecurityGroup_multiIngress --- PASS: TestAccVPCSecurityGroup_defaultEgressVPC (25.78s) === CONT TestAccVPCSecurityGroup_vpcProtoNumIngress --- PASS: TestAccVPCSecurityGroup_multiIngress (31.34s) === CONT TestAccVPCSecurityGroup_ipv4AndIPv6Egress --- PASS: TestAccVPCSecurityGroup_vpcProtoNumIngress (26.64s) === CONT TestAccVPCSecurityGroup_failWithDiffMismatch --- PASS: TestAccVPCSecurityGroup_ruleDescription (60.02s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededAppend --- PASS: TestAccVPCSecurityGroup_ipv4AndIPv6Egress (36.65s) === CONT TestAccVPCSecurityGroup_ipRangesWithSameRules --- PASS: TestAccVPCSecurityGroup_failWithDiffMismatch (28.51s) === CONT TestAccVPCSecurityGroup_vpc --- PASS: TestAccVPCSecurityGroup_vpc (25.98s) === CONT TestAccVPCSecurityGroup_self --- PASS: TestAccVPCSecurityGroup_ipRangesWithSameRules (29.04s) === CONT TestAccVPCSecurityGroup_ipv6 --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededAppend (55.11s) === CONT TestAccVPCSecurityGroup_change --- PASS: TestAccVPCSecurityGroup_self (24.88s) === CONT TestAccVPCSecurityGroup_forceRevokeRulesFalse --- PASS: TestAccVPCSecurityGroup_ipv6 (25.66s) === CONT TestAccVPCSecurityGroup_forceRevokeRulesTrue --- PASS: TestAccVPCSecurityGroup_change (41.08s) === CONT TestAccVPCSecurityGroup_ruleGathering --- PASS: TestAccVPCSecurityGroup_ruleGathering (37.20s) === CONT TestAccVPCSecurityGroup_ingressMode --- PASS: TestAccVPCSecurityGroup_ingressMode (48.33s) === CONT TestAccVPCSecurityGroup_egressMode --- PASS: TestAccVPCSecurityGroup_egressMode (48.64s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededPrepend --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededPrepend (49.44s) === CONT TestAccVPCSecurityGroup_ruleLimitExceededAllNew --- PASS: TestAccVPCSecurityGroup_ruleLimitExceededAllNew (48.51s) === CONT TestAccVPCSecurityGroup_namePrefixTerraform --- PASS: TestAccVPCSecurityGroup_namePrefixTerraform (22.76s) === CONT TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules --- PASS: TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules (26.38s) === CONT TestAccVPCSecurityGroup_tags --- PASS: TestAccVPCSecurityGroup_tags (49.67s) === CONT TestAccVPCSecurityGroup_sourceSecurityGroup --- PASS: TestAccVPCSecurityGroup_sourceSecurityGroup (24.44s) === CONT TestAccVPCSecurityGroup_ingressWithPrefixList --- PASS: TestAccVPCSecurityGroup_ingressWithPrefixList (37.17s) === CONT TestAccVPCSecurityGroup_egressWithPrefixList --- PASS: TestAccVPCSecurityGroup_egressWithPrefixList (36.89s) === CONT TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend --- PASS: TestAccVPCSecurityGroup_ruleLimitCIDRBlockExceededAppend (38.34s) === CONT TestAccVPCSecurityGroup_allowAll --- PASS: TestAccVPCSecurityGroup_allowAll (25.48s) === CONT TestAccVPCSecurityGroup_nameGenerated --- PASS: TestAccVPCSecurityGroup_nameGenerated (21.74s) === CONT TestAccVPCSecurityGroup_namePrefix --- PASS: TestAccVPCSecurityGroup_namePrefix (21.96s) === CONT TestAccVPCSecurityGroup_nameTerraformPrefix --- PASS: TestAccVPCSecurityGroup_nameTerraformPrefix (24.10s) === CONT TestAccVPCSecurityGroup_disappears --- PASS: TestAccVPCSecurityGroup_disappears (19.44s) === CONT TestAccVPCSecurityGroup_basicEC2Classic --- PASS: TestAccVPCSecurityGroup_basicEC2Classic (12.70s) === CONT TestAccVPCSecurityGroup_rulesDropOnError --- PASS: TestAccVPCSecurityGroup_rulesDropOnError (42.90s) --- PASS: TestAccVPCSecurityGroup_forceRevokeRulesFalse (958.56s) --- PASS: TestAccVPCSecurityGroup_forceRevokeRulesTrue (991.82s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 1185.611s From 02f1a32a264442c189816bbb8e2c66ac761cf0f2 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 14:41:47 -0400 Subject: [PATCH 113/120] r/aws_security_group: Validate that security group names aren't prefixed with 'sg-'. Acceptance test output: % EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT=60 make testacc TESTARGS='-run=TestAccVPCSecurityGroup_basic\|TestAccVPCSecurityGroup_name' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroup_basic\|TestAccVPCSecurityGroup_name -timeout 180m === RUN TestAccVPCSecurityGroup_basic === PAUSE TestAccVPCSecurityGroup_basic === RUN TestAccVPCSecurityGroup_basicEC2Classic === PAUSE TestAccVPCSecurityGroup_basicEC2Classic === RUN TestAccVPCSecurityGroup_nameGenerated === PAUSE TestAccVPCSecurityGroup_nameGenerated === RUN TestAccVPCSecurityGroup_nameTerraformPrefix === PAUSE TestAccVPCSecurityGroup_nameTerraformPrefix === RUN TestAccVPCSecurityGroup_namePrefix === PAUSE TestAccVPCSecurityGroup_namePrefix === RUN TestAccVPCSecurityGroup_namePrefixTerraform === PAUSE TestAccVPCSecurityGroup_namePrefixTerraform === CONT TestAccVPCSecurityGroup_basic === CONT TestAccVPCSecurityGroup_nameTerraformPrefix === CONT TestAccVPCSecurityGroup_nameGenerated --- PASS: TestAccVPCSecurityGroup_basic (37.02s) === CONT TestAccVPCSecurityGroup_basicEC2Classic --- PASS: TestAccVPCSecurityGroup_nameGenerated (37.57s) === CONT TestAccVPCSecurityGroup_namePrefixTerraform --- PASS: TestAccVPCSecurityGroup_nameTerraformPrefix (37.76s) === CONT TestAccVPCSecurityGroup_namePrefix --- PASS: TestAccVPCSecurityGroup_basicEC2Classic (34.82s) --- PASS: TestAccVPCSecurityGroup_namePrefix (39.35s) --- PASS: TestAccVPCSecurityGroup_namePrefixTerraform (40.42s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 93.314s --- internal/service/ec2/vpc_security_group.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index be954b7f4c57..070b92412b0c 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "log" + "regexp" "sort" "strconv" "strings" @@ -13,6 +14,7 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -64,7 +66,10 @@ func ResourceSecurityGroup() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: validation.StringLenBetween(0, 255), + ValidateFunc: validation.All( + validation.StringLenBetween(0, 255), + validation.StringDoesNotMatch(regexp.MustCompile(`^sg-`), "cannot begin with sg-"), + ), }, "name_prefix": { Type: schema.TypeString, @@ -72,7 +77,10 @@ func ResourceSecurityGroup() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name"}, - ValidateFunc: validation.StringLenBetween(0, 100), + ValidateFunc: validation.All( + validation.StringLenBetween(0, 255-resource.UniqueIDSuffixLength), + validation.StringDoesNotMatch(regexp.MustCompile(`^sg-`), "cannot begin with sg-"), + ), }, "owner_id": { Type: schema.TypeString, From cac850f4953906555c2d4a20cb66d78c1429440b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 14:43:15 -0400 Subject: [PATCH 114/120] Add CHANGELOG entry. --- .changelog/15011.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .changelog/15011.txt diff --git a/.changelog/15011.txt b/.changelog/15011.txt new file mode 100644 index 000000000000..99810e79b322 --- /dev/null +++ b/.changelog/15011.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_security_group: Additional plan-time validation for `name` and `name_prefix` +``` \ No newline at end of file From 3dbd2cd49e80a90803dd4ba881caebe360d09751 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 15:15:51 -0400 Subject: [PATCH 115/120] r/aws_security_group_rule: Add custom Create timeout. Acceptance test output: % make testacc TESTARGS='-run=TestAccVPCSecurityGroupRule_Ingress_vpc' PKG=ec2 ACCTEST_PARALLELISM=3 ==> Checking that code complies with gofmt requirements... TF_ACC=1 go test ./internal/service/ec2/... -v -count 1 -parallel 3 -run=TestAccVPCSecurityGroupRule_Ingress_vpc -timeout 180m === RUN TestAccVPCSecurityGroupRule_Ingress_vpc === PAUSE TestAccVPCSecurityGroupRule_Ingress_vpc === CONT TestAccVPCSecurityGroupRule_Ingress_vpc --- PASS: TestAccVPCSecurityGroupRule_Ingress_vpc (21.11s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/ec2 25.615s --- internal/service/ec2/vpc_security_group_rule.go | 6 +++++- website/docs/r/security_group_rule.html.markdown | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 8c11167f167e..1ac65e8871db 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -34,6 +34,10 @@ func ResourceSecurityGroupRule() *schema.Resource { StateContext: resourceSecurityGroupRuleImport, }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(5 * time.Minute), + }, + SchemaVersion: 2, MigrateState: SecurityGroupRuleMigrateState, @@ -188,7 +192,7 @@ information and instructions for recovery. Error: %w`, securityGroupID, err) return fmt.Errorf("authorizing Security Group (%s) Rule (%s): %w", securityGroupID, id, err) } - _, err = tfresource.RetryWhenNotFound(5*time.Minute, func() (interface{}, error) { + _, err = tfresource.RetryWhenNotFound(d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { sg, err := FindSecurityGroupByID(conn, securityGroupID) if err != nil { diff --git a/website/docs/r/security_group_rule.html.markdown b/website/docs/r/security_group_rule.html.markdown index 499564394e19..65dc65b4d184 100644 --- a/website/docs/r/security_group_rule.html.markdown +++ b/website/docs/r/security_group_rule.html.markdown @@ -114,6 +114,12 @@ In addition to all arguments above, the following attributes are exported: * `id` - ID of the security group rule. +## Timeouts + +`aws_security_group_rule` provides the following [Timeouts](https://www.terraform.io/docs/configuration/blocks/resources/syntax.html#operation-timeouts) configuration options: + +- `create` - (Default `5 minutes`) Used for security group rule creation + ## Import Security Group Rules can be imported using the `security_group_id`, `type`, `protocol`, `from_port`, `to_port`, and source(s)/destination(s) (e.g., `cidr_block`) separated by underscores (`_`). All parts are required. From 0eb46108d877f8804c631c006b91df9b8c9d9db5 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 15:17:41 -0400 Subject: [PATCH 116/120] Add CHANGELOG entry. --- .changelog/24340.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .changelog/24340.txt diff --git a/.changelog/24340.txt b/.changelog/24340.txt new file mode 100644 index 000000000000..24cadc229c27 --- /dev/null +++ b/.changelog/24340.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_security_group_rule: Add configurable Create timeout +``` \ No newline at end of file From 96d228507e51cd4b1724efe485affcac90036669 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 15:22:06 -0400 Subject: [PATCH 117/120] Revert "Change 5 minute timeout to 60 minute timeout when creating security_group_rules" This reverts commit d4843842c5ba3dec7ab0bb57d885fc638ca0fb4b. --- internal/service/ec2/security_group_rule.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/ec2/security_group_rule.go b/internal/service/ec2/security_group_rule.go index bd77b87e1ea2..ec5f80f79f07 100644 --- a/internal/service/ec2/security_group_rule.go +++ b/internal/service/ec2/security_group_rule.go @@ -227,7 +227,7 @@ information and instructions for recovery. Error: %w`, sg_id, autherr) id := IPPermissionIDHash(sg_id, ruleType, perm) log.Printf("[DEBUG] Computed group rule ID %s", id) - err = resource.Retry(60*time.Minute, func() *resource.RetryError { + err = resource.Retry(5*time.Minute, func() *resource.RetryError { sg, err := FindSecurityGroupByID(conn, sg_id) if err != nil { From e015ef36f1f370de8752c82ebe2f68090bf5c920 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 15:24:21 -0400 Subject: [PATCH 118/120] Revert "Match IPv6 CIDRs as lower-case" This reverts commit 5d5e1eafe9b8305984516c27f5cbe68a906bf6f5. --- .../service/ec2/vpc_security_group_rule.go | 8 +-- .../vpc_security_group_rules_matching_test.go | 60 ------------------- 2 files changed, 2 insertions(+), 66 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index 25b3c8d3a628..1d114b450423 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -452,15 +452,11 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission, isVPC bool) * remaining = len(p.Ipv6Ranges) for _, ipv6 := range p.Ipv6Ranges { - if ipv6.CidrIpv6 == nil { - continue - } - expectedCidrIpv6 := strings.ToLower(aws.StringValue(ipv6.CidrIpv6)) for _, ipv6ip := range r.Ipv6Ranges { - if ipv6ip.CidrIpv6 == nil { + if ipv6.CidrIpv6 == nil || ipv6ip.CidrIpv6 == nil { continue } - if expectedCidrIpv6 == aws.StringValue(ipv6ip.CidrIpv6) { + if aws.StringValue(ipv6.CidrIpv6) == aws.StringValue(ipv6ip.CidrIpv6) { remaining-- } } diff --git a/internal/service/ec2/vpc_security_group_rules_matching_test.go b/internal/service/ec2/vpc_security_group_rules_matching_test.go index 681b4111f8eb..058f08a19830 100644 --- a/internal/service/ec2/vpc_security_group_rules_matching_test.go +++ b/internal/service/ec2/vpc_security_group_rules_matching_test.go @@ -585,66 +585,6 @@ func TestRulesMixedMatching(t *testing.T) { }, }, }, - // ipv6 - { - local: []interface{}{ - map[string]interface{}{ - "from_port": 80, - "to_port": 8000, - "protocol": "tcp", - "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, - "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), - }, - }, - remote: []map[string]interface{}{ - { - "from_port": int64(80), - "to_port": int64(8000), - "protocol": "tcp", - "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, - "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), - }, - }, - saves: []map[string]interface{}{ - { - "from_port": 80, - "to_port": 8000, - "protocol": "tcp", - "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, - "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), - }, - }, - }, - // ipv6: local/remote differ in capitalization - { - local: []interface{}{ - map[string]interface{}{ - "from_port": 80, - "to_port": 8000, - "protocol": "tcp", - "cidr_ipv6_blocks": []interface{}{"2001:0DB8:85A3:0000::/64"}, - "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), - }, - }, - remote: []map[string]interface{}{ - { - "from_port": int64(80), - "to_port": int64(8000), - "protocol": "tcp", - "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, - "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), - }, - }, - saves: []map[string]interface{}{ - { - "from_port": 80, - "to_port": 8000, - "protocol": "tcp", - "cidr_ipv6_blocks": []interface{}{"2001:0db8:85a3:0000::/64"}, - "security_groups": schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), - }, - }, - }, } for i, c := range cases { saves := tfec2.MatchRules("ingress", c.local, c.remote) From 6f346f4e0e445f921f154d378de2bd58ac69eec3 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 15:57:12 -0400 Subject: [PATCH 119/120] Fix terrafmt errors. --- .../ec2/vpc_security_group_rule_test.go | 22 +++++++++---------- .../service/ec2/vpc_security_group_test.go | 22 +++++++++---------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 10d77f42a7d6..db96922c9daa 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -2532,12 +2532,12 @@ resource "aws_ec2_managed_prefix_list" "test" { } resource "aws_security_group_rule" "test" { - type = "ingress" - protocol = "6" - from_port = 80 - to_port = 8000 - prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] - self = true + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] + self = true security_group_id = aws_security_group.test.id } @@ -2572,11 +2572,11 @@ resource "aws_ec2_managed_prefix_list" "test" { } resource "aws_security_group_rule" "test" { - type = "ingress" - protocol = "6" - from_port = 80 - to_port = 8000 - prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] + type = "ingress" + protocol = "6" + from_port = 80 + to_port = 8000 + prefix_list_ids = [aws_ec2_managed_prefix_list.test.id] source_security_group_id = aws_security_group.test[1].id diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 2d3e4be9c3aa..f56ddab4db63 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -3686,22 +3686,22 @@ resource "aws_vpc" "test" { } resource "aws_security_group" "test" { - name = "%[1]s-1" - vpc_id = aws_vpc.test.id + name = "%[1]s-1" + vpc_id = aws_vpc.test.id - tags = { - Name = %[1]q - } + tags = { + Name = %[1]q } +} - resource "aws_security_group" "test2" { - name = "%[1]s-2" - vpc_id = aws_vpc.test.id +resource "aws_security_group" "test2" { + name = "%[1]s-2" + vpc_id = aws_vpc.test.id - tags = { - Name = %[1]q - } + tags = { + Name = %[1]q } +} resource "aws_security_group_rule" "allow_security_group" { type = "ingress" From e7dbef30836b1023e6383bebe68328ca0c698617 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 20 Jul 2022 17:18:24 -0400 Subject: [PATCH 120/120] Fix terrafmt errors. --- internal/service/ec2/vpc_security_group_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index f56ddab4db63..774a5c22fee5 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -3688,16 +3688,16 @@ resource "aws_vpc" "test" { resource "aws_security_group" "test" { name = "%[1]s-1" vpc_id = aws_vpc.test.id - + tags = { Name = %[1]q } } - + resource "aws_security_group" "test2" { name = "%[1]s-2" vpc_id = aws_vpc.test.id - + tags = { Name = %[1]q }