Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provider/aws: test exposing sg rule race #3064

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 66 additions & 19 deletions builtin/providers/aws/resource_aws_security_group_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func resourceAwsSecurityGroupRule() *schema.Resource {
Read: resourceAwsSecurityGroupRuleRead,
Delete: resourceAwsSecurityGroupRuleDelete,

SchemaVersion: 1,
SchemaVersion: 2,
MigrateState: resourceAwsSecurityGroupRuleMigrateState,

Schema: map[string]*schema.Schema{
Expand Down Expand Up @@ -67,14 +67,15 @@ func resourceAwsSecurityGroupRule() *schema.Resource {
Optional: true,
ForceNew: true,
Computed: true,
ConflictsWith: []string{"cidr_blocks"},
ConflictsWith: []string{"cidr_blocks", "self"},
},

"self": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
ConflictsWith: []string{"cidr_blocks"},
},
},
}
Expand Down Expand Up @@ -142,7 +143,7 @@ information and instructions for recovery. Error message: %s`, awsErr.Message())
ruleType, autherr)
}

d.SetId(ipPermissionIDHash(ruleType, perm))
d.SetId(ipPermissionIDHash(sg_id, ruleType, perm))

return resourceAwsSecurityGroupRuleRead(d, meta)
}
Expand All @@ -158,24 +159,69 @@ func resourceAwsSecurityGroupRuleRead(d *schema.ResourceData, meta interface{})
}

var rule *ec2.IpPermission
var rules []*ec2.IpPermission
ruleType := d.Get("type").(string)
var rl []*ec2.IpPermission
switch ruleType {
case "ingress":
rl = sg.IpPermissions
rules = sg.IpPermissions
default:
rl = sg.IpPermissionsEgress
rules = sg.IpPermissionsEgress
}

for _, r := range rl {
if d.Id() == ipPermissionIDHash(ruleType, r) {
rule = r
p := expandIPPerm(d, sg)

if len(rules) == 0 {
return fmt.Errorf(
"[WARN] No %s rules were found for Security Group (%s) looking for Security Group Rule (%s)",
ruleType, *sg.GroupName, d.Id())
}

for _, r := range rules {
if r.ToPort != nil && *p.ToPort != *r.ToPort {
continue
}

if r.FromPort != nil && *p.FromPort != *r.FromPort {
continue
}

if 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 == *rip.CidrIp {
remaining--
}
}
}

if remaining > 0 {
continue
}

remaining = len(p.UserIdGroupPairs)
for _, ip := range p.UserIdGroupPairs {
for _, rip := range r.UserIdGroupPairs {
if *ip.GroupId == *rip.GroupId {
remaining--
}
}
}

if remaining > 0 {
continue
}

log.Printf("[DEBUG] Found rule for Security Group Rule (%s): %s", d.Id(), r)
rule = r
}

if rule == nil {
log.Printf("[DEBUG] Unable to find matching %s Security Group Rule for Group %s",
ruleType, sg_id)
log.Printf("[DEBUG] Unable to find matching %s Security Group Rule (%s) for Group %s",
ruleType, d.Id(), sg_id)
d.SetId("")
return nil
}
Expand All @@ -186,14 +232,14 @@ func resourceAwsSecurityGroupRuleRead(d *schema.ResourceData, meta interface{})
d.Set("type", ruleType)

var cb []string
for _, c := range rule.IpRanges {
for _, c := range p.IpRanges {
cb = append(cb, *c.CidrIp)
}

d.Set("cidr_blocks", cb)

if len(rule.UserIdGroupPairs) > 0 {
s := rule.UserIdGroupPairs[0]
if len(p.UserIdGroupPairs) > 0 {
s := p.UserIdGroupPairs[0]
d.Set("source_security_group_id", *s.GroupId)
}

Expand Down Expand Up @@ -285,8 +331,9 @@ func (b ByGroupPair) Less(i, j int) bool {
panic("mismatched security group rules, may be a terraform bug")
}

func ipPermissionIDHash(ruleType string, ip *ec2.IpPermission) string {
func ipPermissionIDHash(sg_id, ruleType string, ip *ec2.IpPermission) string {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("%s-", sg_id))
if ip.FromPort != nil && *ip.FromPort > 0 {
buf.WriteString(fmt.Sprintf("%d-", *ip.FromPort))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ func resourceAwsSecurityGroupRuleMigrateState(
case 0:
log.Println("[INFO] Found AWS Security Group State v0; migrating to v1")
return migrateSGRuleStateV0toV1(is)
case 1:
log.Println("[INFO] Found AWS Security Group State v1; migrating to v2")
// migrating to version 2 of the schema is the same as 0->1, since the
// method signature has changed now and will use the security group id in
// the hash
return migrateSGRuleStateV0toV1(is)
default:
return is, fmt.Errorf("Unexpected schema version: %d", v)
}
Expand All @@ -37,7 +43,7 @@ func migrateSGRuleStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceS
}

log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes)
newID := ipPermissionIDHash(is.Attributes["type"], perm)
newID := ipPermissionIDHash(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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestAWSSecurityGroupRuleMigrateState(t *testing.T) {
"from_port": "0",
"source_security_group_id": "sg-11877275",
},
Expected: "sg-3766347571",
Expected: "sg-2889201120",
},
"v0_2": {
StateVersion: 0,
Expand All @@ -44,7 +44,7 @@ func TestAWSSecurityGroupRuleMigrateState(t *testing.T) {
"cidr_blocks.2": "172.16.3.0/24",
"cidr_blocks.3": "172.16.4.0/24",
"cidr_blocks.#": "4"},
Expected: "sg-4100229787",
Expected: "sg-1826358977",
},
}

Expand Down
Loading