-
Notifications
You must be signed in to change notification settings - Fork 9.3k
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
New Resource: aws_vpc_ipv4_cidr_block_association #3723
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c006eb2
New Resource: aws_vpc_associate_cidr_block
stack72 3e43f34
Restore original 'aws_vpc.assign_generated_ipv6_cidr_block' functiona…
ewbankkit 839d50b
'aws_vpc_associate_cidr_block' -> 'aws_vpc_secondary_ipv4_cidr_block'.
ewbankkit ecad19d
'ipv4_cidr_block' -> 'cidr_block'.
ewbankkit 0439357
'aws_vpc_secondary_ipv4_cidr_block' -> 'aws_vpc_ipv4_cidr_block_assoc…
506cc15
Minor changes after code review.
ff10478
Correctly handle VPC IPv4 CIDR block association state changes.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
package aws | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"time" | ||
|
||
"github.com/aws/aws-sdk-go/aws" | ||
"github.com/aws/aws-sdk-go/service/ec2" | ||
"github.com/hashicorp/terraform/helper/resource" | ||
"github.com/hashicorp/terraform/helper/schema" | ||
"github.com/hashicorp/terraform/helper/validation" | ||
) | ||
|
||
const ( | ||
VpcCidrBlockStateCodeDeleted = "deleted" | ||
) | ||
|
||
func resourceAwsVpcIpv4CidrBlockAssociation() *schema.Resource { | ||
return &schema.Resource{ | ||
Create: resourceAwsVpcIpv4CidrBlockAssociationCreate, | ||
Read: resourceAwsVpcIpv4CidrBlockAssociationRead, | ||
Delete: resourceAwsVpcIpv4CidrBlockAssociationDelete, | ||
|
||
Schema: map[string]*schema.Schema{ | ||
"vpc_id": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
}, | ||
|
||
"cidr_block": { | ||
Type: schema.TypeString, | ||
Required: true, | ||
ForceNew: true, | ||
ValidateFunc: validation.CIDRNetwork(16, 28), // The allowed block size is between a /28 netmask and /16 netmask. | ||
}, | ||
}, | ||
|
||
Timeouts: &schema.ResourceTimeout{ | ||
Create: schema.DefaultTimeout(10 * time.Minute), | ||
Delete: schema.DefaultTimeout(10 * time.Minute), | ||
}, | ||
} | ||
} | ||
|
||
func resourceAwsVpcIpv4CidrBlockAssociationCreate(d *schema.ResourceData, meta interface{}) error { | ||
conn := meta.(*AWSClient).ec2conn | ||
|
||
req := &ec2.AssociateVpcCidrBlockInput{ | ||
VpcId: aws.String(d.Get("vpc_id").(string)), | ||
CidrBlock: aws.String(d.Get("cidr_block").(string)), | ||
} | ||
log.Printf("[DEBUG] Creating VPC IPv4 CIDR block association: %#v", req) | ||
resp, err := conn.AssociateVpcCidrBlock(req) | ||
if err != nil { | ||
return fmt.Errorf("Error creating VPC IPv4 CIDR block association: %s", err) | ||
} | ||
|
||
d.SetId(aws.StringValue(resp.CidrBlockAssociation.AssociationId)) | ||
|
||
stateConf := &resource.StateChangeConf{ | ||
Pending: []string{ec2.VpcCidrBlockStateCodeAssociating}, | ||
Target: []string{ec2.VpcCidrBlockStateCodeAssociated}, | ||
Refresh: vpcIpv4CidrBlockAssociationStateRefresh(conn, d.Get("vpc_id").(string), d.Id()), | ||
Timeout: d.Timeout(schema.TimeoutCreate), | ||
Delay: 10 * time.Second, | ||
MinTimeout: 5 * time.Second, | ||
} | ||
_, err = stateConf.WaitForState() | ||
if err != nil { | ||
return fmt.Errorf("Error waiting for IPv4 CIDR block association (%s) to become available: %s", d.Id(), err) | ||
} | ||
|
||
return resourceAwsVpcIpv4CidrBlockAssociationRead(d, meta) | ||
} | ||
|
||
func resourceAwsVpcIpv4CidrBlockAssociationRead(d *schema.ResourceData, meta interface{}) error { | ||
conn := meta.(*AWSClient).ec2conn | ||
|
||
assocRaw, state, err := vpcIpv4CidrBlockAssociationStateRefresh(conn, d.Get("vpc_id").(string), d.Id())() | ||
if err != nil { | ||
return fmt.Errorf("Error reading IPv4 CIDR block association: %s", err) | ||
} | ||
if state == VpcCidrBlockStateCodeDeleted { | ||
log.Printf("[WARN] IPv4 CIDR block association (%s) not found, removing from state", d.Id()) | ||
d.SetId("") | ||
return nil | ||
} | ||
|
||
assoc := assocRaw.(*ec2.VpcCidrBlockAssociation) | ||
d.Set("cidr_block", assoc.CidrBlock) | ||
|
||
return nil | ||
} | ||
|
||
func resourceAwsVpcIpv4CidrBlockAssociationDelete(d *schema.ResourceData, meta interface{}) error { | ||
conn := meta.(*AWSClient).ec2conn | ||
|
||
log.Printf("[DEBUG] Deleting VPC IPv4 CIDR block association: %s", d.Id()) | ||
_, err := conn.DisassociateVpcCidrBlock(&ec2.DisassociateVpcCidrBlockInput{ | ||
AssociationId: aws.String(d.Id()), | ||
}) | ||
if err != nil { | ||
if isAWSErr(err, "InvalidVpcID.NotFound", "") { | ||
return nil | ||
} | ||
return fmt.Errorf("Error deleting VPC IPv4 CIDR block association: %s", err) | ||
} | ||
|
||
stateConf := &resource.StateChangeConf{ | ||
Pending: []string{ec2.VpcCidrBlockStateCodeDisassociating}, | ||
Target: []string{ec2.VpcCidrBlockStateCodeDisassociated, VpcCidrBlockStateCodeDeleted}, | ||
Refresh: vpcIpv4CidrBlockAssociationStateRefresh(conn, d.Get("vpc_id").(string), d.Id()), | ||
Timeout: d.Timeout(schema.TimeoutDelete), | ||
Delay: 10 * time.Second, | ||
MinTimeout: 5 * time.Second, | ||
} | ||
_, err = stateConf.WaitForState() | ||
if err != nil { | ||
return fmt.Errorf("Error waiting for VPC IPv4 CIDR block association (%s) to be deleted: %s", d.Id(), err.Error()) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func vpcIpv4CidrBlockAssociationStateRefresh(conn *ec2.EC2, vpcId, assocId string) resource.StateRefreshFunc { | ||
return func() (interface{}, string, error) { | ||
vpc, err := vpcDescribe(conn, vpcId) | ||
if err != nil { | ||
return nil, "", err | ||
} | ||
|
||
if vpc != nil { | ||
for _, cidrAssociation := range vpc.CidrBlockAssociationSet { | ||
if aws.StringValue(cidrAssociation.AssociationId) == assocId { | ||
return cidrAssociation, aws.StringValue(cidrAssociation.CidrBlockState.State), nil | ||
} | ||
} | ||
} | ||
|
||
return "", VpcCidrBlockStateCodeDeleted, nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
package aws | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/aws/aws-sdk-go/aws" | ||
"github.com/aws/aws-sdk-go/aws/awserr" | ||
"github.com/aws/aws-sdk-go/service/ec2" | ||
"github.com/hashicorp/terraform/helper/resource" | ||
"github.com/hashicorp/terraform/terraform" | ||
) | ||
|
||
func TestAccAwsVpcIpv4CidrBlockAssociation_basic(t *testing.T) { | ||
var associationSecondary, associationTertiary ec2.VpcCidrBlockAssociation | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
CheckDestroy: testAccCheckAwsVpcIpv4CidrBlockAssociationDestroy, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: testAccAwsVpcIpv4CidrBlockAssociationConfig, | ||
Check: resource.ComposeTestCheckFunc( | ||
testAccCheckAwsVpcIpv4CidrBlockAssociationExists("aws_vpc_ipv4_cidr_block_association.secondary_cidr", &associationSecondary), | ||
testAccCheckAdditionalAwsVpcIpv4CidrBlock(&associationSecondary, "172.2.0.0/16"), | ||
testAccCheckAwsVpcIpv4CidrBlockAssociationExists("aws_vpc_ipv4_cidr_block_association.tertiary_cidr", &associationTertiary), | ||
testAccCheckAdditionalAwsVpcIpv4CidrBlock(&associationTertiary, "170.2.0.0/16"), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func testAccCheckAdditionalAwsVpcIpv4CidrBlock(association *ec2.VpcCidrBlockAssociation, expected string) resource.TestCheckFunc { | ||
return func(s *terraform.State) error { | ||
CIDRBlock := association.CidrBlock | ||
if *CIDRBlock != expected { | ||
return fmt.Errorf("Bad CIDR: %s", *association.CidrBlock) | ||
} | ||
|
||
return nil | ||
} | ||
} | ||
|
||
func testAccCheckAwsVpcIpv4CidrBlockAssociationDestroy(s *terraform.State) error { | ||
conn := testAccProvider.Meta().(*AWSClient).ec2conn | ||
|
||
for _, rs := range s.RootModule().Resources { | ||
if rs.Type != "aws_vpc_ipv4_cidr_block_association" { | ||
continue | ||
} | ||
|
||
// Try to find the VPC | ||
DescribeVpcOpts := &ec2.DescribeVpcsInput{ | ||
VpcIds: []*string{aws.String(rs.Primary.Attributes["vpc_id"])}, | ||
} | ||
resp, err := conn.DescribeVpcs(DescribeVpcOpts) | ||
if err == nil { | ||
vpc := resp.Vpcs[0] | ||
|
||
for _, ipv4Association := range vpc.CidrBlockAssociationSet { | ||
if *ipv4Association.AssociationId == rs.Primary.ID { | ||
return fmt.Errorf("VPC CIDR block association still exists") | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// Verify the error is what we want | ||
ec2err, ok := err.(awserr.Error) | ||
if !ok { | ||
return err | ||
} | ||
if ec2err.Code() != "InvalidVpcID.NotFound" { | ||
return err | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func testAccCheckAwsVpcIpv4CidrBlockAssociationExists(n string, association *ec2.VpcCidrBlockAssociation) 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 VPC ID is set") | ||
} | ||
|
||
conn := testAccProvider.Meta().(*AWSClient).ec2conn | ||
DescribeVpcOpts := &ec2.DescribeVpcsInput{ | ||
VpcIds: []*string{aws.String(rs.Primary.Attributes["vpc_id"])}, | ||
} | ||
resp, err := conn.DescribeVpcs(DescribeVpcOpts) | ||
if err != nil { | ||
return err | ||
} | ||
if len(resp.Vpcs) == 0 { | ||
return fmt.Errorf("VPC not found") | ||
} | ||
|
||
vpc := resp.Vpcs[0] | ||
found := false | ||
for _, cidrAssociation := range vpc.CidrBlockAssociationSet { | ||
if *cidrAssociation.AssociationId == rs.Primary.ID { | ||
*association = *cidrAssociation | ||
found = true | ||
} | ||
} | ||
|
||
if !found { | ||
return fmt.Errorf("VPC CIDR block association not found") | ||
} | ||
|
||
return nil | ||
} | ||
} | ||
|
||
const testAccAwsVpcIpv4CidrBlockAssociationConfig = ` | ||
resource "aws_vpc" "foo" { | ||
cidr_block = "10.1.0.0/16" | ||
tags { | ||
Name = "terraform-testacc-vpc-ipv4-cidr-block-association" | ||
} | ||
} | ||
|
||
resource "aws_vpc_ipv4_cidr_block_association" "secondary_cidr" { | ||
vpc_id = "${aws_vpc.foo.id}" | ||
cidr_block = "172.2.0.0/16" | ||
} | ||
|
||
resource "aws_vpc_ipv4_cidr_block_association" "tertiary_cidr" { | ||
vpc_id = "${aws_vpc.foo.id}" | ||
cidr_block = "170.2.0.0/16" | ||
} | ||
` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added
vpcDescribe
here to be reused in future refactorings.