Skip to content

Commit

Permalink
provider/aws: aws_subnet data source
Browse files Browse the repository at this point in the history
  • Loading branch information
apparentlymart committed May 22, 2016
1 parent 18803d9 commit 2937298
Show file tree
Hide file tree
Showing 5 changed files with 223 additions and 5 deletions.
121 changes: 121 additions & 0 deletions builtin/providers/aws/data_source_aws_subnet.go
Original file line number Diff line number Diff line change
@@ -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 dataSourceAwsSubnet() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsSubnetRead,

Schema: map[string]*schema.Schema{
"availability_zone": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},

"cidr_block": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},

"default_for_az": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
},

"filter": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"values": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},

"id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},

"state": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},

"tags": tagsSchemaComputed(),

"vpc_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}

func dataSourceAwsSubnetRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn

req := &ec2.DescribeSubnetsInput{}

// FIXME: This doesn't actually work for some reason... this returns
// the empty string even when it's set in the configuration.
if id := d.Get("id"); id != "" {
req.SubnetIds = []*string{aws.String(id.(string))}
}

req.Filters = buildEC2FilterList(d, map[string]string{
"availability_zone": "availabilityZone",
"cidr_block": "cidrBlock",
"default_for_az": "defaultForAz",
"state": "state",
"vpc_id": "vpc-id",
})

log.Printf("[DEBUG] DescribeSubnets %#v\n", req)
resp, err := conn.DescribeSubnets(req)
if err != nil {
return err
}
if resp == nil || len(resp.Subnets) == 0 {
return fmt.Errorf("no matching subnet found")
}
if len(resp.Subnets) > 1 {
return fmt.Errorf("multiple subnets matched; use additional constraints to reduce matches to a single subnet")
}

subnet := resp.Subnets[0]

d.SetId(*subnet.SubnetId)
d.Set("id", subnet.SubnetId)
d.Set("vpc_id", subnet.VpcId)
d.Set("availability_zone", subnet.AvailabilityZone)
d.Set("cidr_block", subnet.CidrBlock)
d.Set("default_for_az", subnet.DefaultForAz)
d.Set("state", subnet.State)
d.Set("tags", tagsToMap(subnet.Tags))

return nil
}
83 changes: 83 additions & 0 deletions builtin/providers/aws/ec2_filters.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package aws

import (
"fmt"
"strconv"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"

"github.com/hashicorp/terraform/helper/schema"
)

func buildEC2FilterList(
d *schema.ResourceData,
attrs map[string]string,
) []*ec2.Filter {

var customFilters []interface{}
if filterSetI, ok := d.GetOk("filter"); ok {
customFilters = filterSetI.(*schema.Set).List()
}

var tags map[string]interface{}
if tagsI, ok := d.GetOk("tags"); ok {
tags = tagsI.(map[string]interface{})
}

filterCount := len(attrs) + len(customFilters) + len(tags)
filters := make([]*ec2.Filter, 0, filterCount)

for attrName, filterName := range attrs {
if valI, ok := d.GetOk(attrName); ok {
var val string

switch valI.(type) {
case string:
val = valI.(string)
case bool:
if valB := valI.(bool); valB {
val = "true"
} else {
val = "false"
}
case int:
val = strconv.Itoa(valI.(int))
default:
panic(fmt.Errorf("Unsupported filter type %#v", valI))
}

filters = append(filters, &ec2.Filter{
Name: aws.String(filterName),
Values: []*string{&val},
})
}
}

for _, customFilterI := range customFilters {
customFilterMapI := customFilterI.(map[string]interface{})
name := customFilterMapI["name"].(string)
valuesI := customFilterMapI["values"].(*schema.Set).List()
values := make([]*string, len(valuesI))
for i, valueI := range valuesI {
values[i] = aws.String(valueI.(string))
}

filters = append(filters, &ec2.Filter{
Name: &name,
Values: values,
})
}

for name, valueI := range tags {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s=%s", name, valueI.(string))),
})
}

if len(filters) == 0 {
return nil
}

return filters
}
4 changes: 4 additions & 0 deletions builtin/providers/aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ func Provider() terraform.ResourceProvider {
},
},

DataSourcesMap: map[string]*schema.Resource{
"aws_subnet": dataSourceAwsSubnet(),
},

ResourcesMap: map[string]*schema.Resource{
"aws_ami": resourceAwsAmi(),
"aws_ami_copy": resourceAwsAmiCopy(),
Expand Down
8 changes: 8 additions & 0 deletions builtin/providers/aws/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ func tagsSchema() *schema.Schema {
}
}

func tagsSchemaComputed() *schema.Schema {
return &schema.Schema{
Type: schema.TypeMap,
Optional: true,
Computed: true,
}
}

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags"
func setTags(conn *ec2.EC2, d *schema.ResourceData) error {
Expand Down
12 changes: 7 additions & 5 deletions terraform/eval_read_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,13 @@ func (n *EvalReadDataDiff) Eval(ctx EvalContext) (interface{}, error) {

// id is always computed, because we're always "creating a new resource"
diff.init()
diff.Attributes["id"] = &ResourceAttrDiff{
Old: "",
NewComputed: true,
RequiresNew: true,
Type: DiffAttrOutput,
if _, ok := diff.Attributes["id"]; !ok {
diff.Attributes["id"] = &ResourceAttrDiff{
Old: "",
NewComputed: true,
RequiresNew: true,
Type: DiffAttrOutput,
}
}
}

Expand Down

0 comments on commit 2937298

Please sign in to comment.