github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/builtin/providers/aws/resource_aws_subnet_test.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/aws/aws-sdk-go/aws" 8 "github.com/aws/aws-sdk-go/aws/awserr" 9 "github.com/aws/aws-sdk-go/service/ec2" 10 "github.com/hashicorp/terraform/helper/resource" 11 "github.com/hashicorp/terraform/terraform" 12 ) 13 14 func TestAccAWSSubnet_basic(t *testing.T) { 15 var v ec2.Subnet 16 17 testCheck := func(*terraform.State) error { 18 if *v.CidrBlock != "10.1.1.0/24" { 19 return fmt.Errorf("bad cidr: %s", *v.CidrBlock) 20 } 21 22 if *v.MapPublicIpOnLaunch != true { 23 return fmt.Errorf("bad MapPublicIpOnLaunch: %t", *v.MapPublicIpOnLaunch) 24 } 25 26 return nil 27 } 28 29 resource.Test(t, resource.TestCase{ 30 PreCheck: func() { testAccPreCheck(t) }, 31 Providers: testAccProviders, 32 CheckDestroy: testAccCheckSubnetDestroy, 33 Steps: []resource.TestStep{ 34 resource.TestStep{ 35 Config: testAccSubnetConfig, 36 Check: resource.ComposeTestCheckFunc( 37 testAccCheckSubnetExists( 38 "aws_subnet.foo", &v), 39 testCheck, 40 ), 41 }, 42 }, 43 }) 44 } 45 46 func testAccCheckSubnetDestroy(s *terraform.State) error { 47 conn := testAccProvider.Meta().(*AWSClient).ec2conn 48 49 for _, rs := range s.RootModule().Resources { 50 if rs.Type != "aws_subnet" { 51 continue 52 } 53 54 // Try to find the resource 55 resp, err := conn.DescribeSubnets(&ec2.DescribeSubnetsInput{ 56 SubnetIds: []*string{aws.String(rs.Primary.ID)}, 57 }) 58 if err == nil { 59 if len(resp.Subnets) > 0 { 60 return fmt.Errorf("still exist.") 61 } 62 63 return nil 64 } 65 66 // Verify the error is what we want 67 ec2err, ok := err.(awserr.Error) 68 if !ok { 69 return err 70 } 71 if ec2err.Code() != "InvalidSubnetID.NotFound" { 72 return err 73 } 74 } 75 76 return nil 77 } 78 79 func testAccCheckSubnetExists(n string, v *ec2.Subnet) resource.TestCheckFunc { 80 return func(s *terraform.State) error { 81 rs, ok := s.RootModule().Resources[n] 82 if !ok { 83 return fmt.Errorf("Not found: %s", n) 84 } 85 86 if rs.Primary.ID == "" { 87 return fmt.Errorf("No ID is set") 88 } 89 90 conn := testAccProvider.Meta().(*AWSClient).ec2conn 91 resp, err := conn.DescribeSubnets(&ec2.DescribeSubnetsInput{ 92 SubnetIds: []*string{aws.String(rs.Primary.ID)}, 93 }) 94 if err != nil { 95 return err 96 } 97 if len(resp.Subnets) == 0 { 98 return fmt.Errorf("Subnet not found") 99 } 100 101 *v = *resp.Subnets[0] 102 103 return nil 104 } 105 } 106 107 const testAccSubnetConfig = ` 108 resource "aws_vpc" "foo" { 109 cidr_block = "10.1.0.0/16" 110 } 111 112 resource "aws_subnet" "foo" { 113 cidr_block = "10.1.1.0/24" 114 vpc_id = "${aws_vpc.foo.id}" 115 map_public_ip_on_launch = true 116 tags { 117 Name = "tf-subnet-acc-test" 118 } 119 } 120 `