From aa0b6019f88759e2e4e3a227b31f2cea80f692d0 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Sun, 22 May 2016 08:25:30 -0700 Subject: [PATCH] provider/aws: aws_vpc data source --- builtin/providers/aws/data_source_aws_vpc.go | 121 ++++++++++++++++++ .../providers/aws/data_source_aws_vpc_test.go | 95 ++++++++++++++ builtin/providers/aws/provider.go | 1 + .../docs/providers/aws/d/vpc.html.markdown | 79 ++++++++++++ website/source/layouts/aws.erb | 3 + 5 files changed, 299 insertions(+) create mode 100644 builtin/providers/aws/data_source_aws_vpc.go create mode 100644 builtin/providers/aws/data_source_aws_vpc_test.go create mode 100644 website/source/docs/providers/aws/d/vpc.html.markdown diff --git a/builtin/providers/aws/data_source_aws_vpc.go b/builtin/providers/aws/data_source_aws_vpc.go new file mode 100644 index 000000000..ffcad8cc6 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_vpc.go @@ -0,0 +1,121 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceAwsVpc() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsVpcRead, + + Schema: map[string]*schema.Schema{ + "cidr_block": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "dhcp_options_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "default": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + + "filter": ec2CustomFiltersSchema(), + + "id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "instance_tenancy": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "state": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "tags": tagsSchemaComputed(), + }, + } +} + +func dataSourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + req := &ec2.DescribeVpcsInput{} + + if id := d.Get("id"); id != "" { + req.VpcIds = []*string{aws.String(id.(string))} + } + + // We specify "default" as boolean, but EC2 filters want + // it to be serialized as a string. Note that setting it to + // "false" here does not actually filter by it *not* being + // the default, because Terraform can't distinguish between + // "false" and "not set". + isDefaultStr := "" + if d.Get("default").(bool) { + isDefaultStr = "true" + } + + req.Filters = buildEC2AttributeFilterList( + map[string]string{ + "cidr": d.Get("cidr_block").(string), + "dhcp-options-id": d.Get("dhcp_options_id").(string), + "isDefault": isDefaultStr, + "state": d.Get("state").(string), + }, + ) + req.Filters = append(req.Filters, buildEC2TagFilterList( + tagsFromMap(d.Get("tags").(map[string]interface{})), + )...) + req.Filters = append(req.Filters, buildEC2CustomFilterList( + d.Get("filter").(*schema.Set), + )...) + if len(req.Filters) == 0 { + // Don't send an empty filters list; the EC2 API won't accept it. + req.Filters = nil + } + + log.Printf("[DEBUG] DescribeVpcs %s\n", req) + resp, err := conn.DescribeVpcs(req) + if err != nil { + return err + } + if resp == nil || len(resp.Vpcs) == 0 { + return fmt.Errorf("no matching VPC found") + } + if len(resp.Vpcs) > 1 { + return fmt.Errorf("multiple VPCs matched; use additional constraints to reduce matches to a single VPC") + } + + vpc := resp.Vpcs[0] + + d.SetId(*vpc.VpcId) + d.Set("id", vpc.VpcId) + d.Set("cidr_block", vpc.CidrBlock) + d.Set("dhcp_options_id", vpc.DhcpOptionsId) + d.Set("instance_tenancy", vpc.InstanceTenancy) + d.Set("default", vpc.IsDefault) + d.Set("state", vpc.State) + d.Set("tags", tagsToMap(vpc.Tags)) + + return nil +} diff --git a/builtin/providers/aws/data_source_aws_vpc_test.go b/builtin/providers/aws/data_source_aws_vpc_test.go new file mode 100644 index 000000000..5b0916f45 --- /dev/null +++ b/builtin/providers/aws/data_source_aws_vpc_test.go @@ -0,0 +1,95 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccDataSourceAwsVpc(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDataSourceAwsVpcConfig, + Check: resource.ComposeTestCheckFunc( + testAccDataSourceAwsVpcCheck("data.aws_vpc.by_id"), + testAccDataSourceAwsVpcCheck("data.aws_vpc.by_cidr"), + testAccDataSourceAwsVpcCheck("data.aws_vpc.by_tag"), + testAccDataSourceAwsVpcCheck("data.aws_vpc.by_filter"), + ), + }, + }, + }) +} + +func testAccDataSourceAwsVpcCheck(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["id"] { + return fmt.Errorf( + "id is %s; want %s", + attr["id"], + vpcRs.Primary.Attributes["id"], + ) + } + + if attr["cidr_block"] != "172.16.0.0/16" { + return fmt.Errorf("bad cidr_block %s", attr["cidr_block"]) + } + if attr["tags.Name"] != "terraform-testacc-vpc-data-source" { + return fmt.Errorf("bad Name tag %s", attr["tags.Name"]) + } + + return nil + } +} + +const testAccDataSourceAwsVpcConfig = ` +provider "aws" { + region = "us-west-2" +} + +resource "aws_vpc" "test" { + cidr_block = "172.16.0.0/16" + + tags { + Name = "terraform-testacc-vpc-data-source" + } +} + +data "aws_vpc" "by_id" { + id = "${aws_vpc.test.id}" +} + +data "aws_vpc" "by_cidr" { + cidr_block = "${aws_vpc.test.cidr_block}" +} + +data "aws_vpc" "by_tag" { + tags { + Name = "${aws_vpc.test.tags["Name"]}" + } +} + +data "aws_vpc" "by_filter" { + filter { + name = "cidr" + values = ["${aws_vpc.test.cidr_block}"] + } +} +` diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index a9505dfeb..eceea6b46 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -154,6 +154,7 @@ func Provider() terraform.ResourceProvider { "aws_redshift_service_account": dataSourceAwsRedshiftServiceAccount(), "aws_s3_bucket_object": dataSourceAwsS3BucketObject(), "aws_subnet": dataSourceAwsSubnet(), + "aws_vpc": dataSourceAwsVpc(), }, ResourcesMap: map[string]*schema.Resource{ diff --git a/website/source/docs/providers/aws/d/vpc.html.markdown b/website/source/docs/providers/aws/d/vpc.html.markdown new file mode 100644 index 000000000..2f4bf6f97 --- /dev/null +++ b/website/source/docs/providers/aws/d/vpc.html.markdown @@ -0,0 +1,79 @@ +--- +layout: "aws" +page_title: "AWS: aws_vpc" +sidebar_current: "docs-aws-datasource-vpc" +description: |- + Provides details about a specific VPC +--- + +# aws\_vpc + +`aws_vpc` provides details about a specific VPC. + +This resource can prove useful when a module accepts a vpc id as +an input variable and needs to, for example, determine the CIDR block of that +VPC. + +## Example Usage + +The following example shows how one might accept a VPC id as a variable +and use this data source to obtain the data necessary to create a subnet +within it. + +``` +variable "vpc_id" {} + +data "aws_vpc" "selected" { + id = "${var.vpc_id}" +} + +resource "aws_subnet" "example" { + vpc_id = "${aws_vpc.selected.id}" + availability_zone = "us-west-2a" + cidr_block = "${cidrsubnet(aws_vpc.selected.cidr_block, 4, 1)}" +} +``` + +## Argument Reference + +The arguments of this data source act as filters for querying the available +VPCs in the current region. The given filters must match exactly one +VPC whose data will be exported as attributes. + +* `cidr_block` - (Optional) The cidr block of the desired VPC. + +* `dhcp_options_id` - (Optional) The DHCP options id of the desired VPC. + +* `default` - (Optional) Boolean constraint on whether the desired VPC is + the default VPC for the region. + +* `filter` - (Optional) Custom filter block as described below. + +* `id` - (Optional) The id of the specific VPC to retrieve. + +* `state` - (Optional) The current state of the desired VPC. + Can be either `"pending"` or `"available"`. + +* `tags` - (Optional) A mapping of tags, each pair of which must exactly match + a pair on the desired VPC. + +More complex filters can be expressed using one or more `filter` sub-blocks, +which take the following arguments: + +* `name` - (Required) The name of the field to filter by, as defined by + [the underlying AWS API](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcs.html). + +* `values` - (Required) Set of values that are accepted for the given field. + A VPC will be selected if any one of the given values matches. + +## Attributes Reference + +All of the argument attributes except `filter` blocks are also exported as +result attributes. This data source will complete the data by populating +any fields that are not included in the configuration with the data for +the selected VPC. + +The following attribute is additionally exported: + +* `instance_tenancy` - The allowed tenancy of instances launched into the + selected VPC. May be any of `"default"`, `"dedicated"`, or `"host"`. diff --git a/website/source/layouts/aws.erb b/website/source/layouts/aws.erb index 590f6f56e..14703ec9b 100644 --- a/website/source/layouts/aws.erb +++ b/website/source/layouts/aws.erb @@ -47,6 +47,9 @@ > aws_subnet + > + aws_vpc +