Skip to content

Commit

Permalink
provider/aws: aws_region data source
Browse files Browse the repository at this point in the history
The primary purpose of this data source is to ask the question "what is
my current region?", but it can also be used to retrieve the endpoint
hostname for a particular (possibly non-current) region, should that be
useful for some esoteric case.
  • Loading branch information
apparentlymart committed May 24, 2016
1 parent aa40644 commit d31fa9c
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
78 changes: 78 additions & 0 deletions builtin/providers/aws/data_source_aws_region.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
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 dataSourceAwsRegion() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsRegionRead,

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

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

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

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

req := &ec2.DescribeRegionsInput{}

req.RegionNames = make([]*string, 0, 2)
if name := d.Get("name").(string); name != "" {
req.RegionNames = append(req.RegionNames, aws.String(name))
}

if d.Get("current").(bool) {
req.RegionNames = append(req.RegionNames, aws.String(currentRegion))
}

req.Filters = buildEC2FilterList(d, map[string]string{
"endpoint": "endpoint",
})

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

region := resp.Regions[0]

d.SetId(*region.RegionName)
d.Set("id", region.RegionName)
d.Set("name", region.RegionName)
d.Set("endpoint", region.Endpoint)
d.Set("current", *region.RegionName == currentRegion)

return nil
}
1 change: 1 addition & 0 deletions builtin/providers/aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ func Provider() terraform.ResourceProvider {
DataSourcesMap: map[string]*schema.Resource{
"aws_availability_zone": dataSourceAwsAvailabilityZone(),
"aws_availability_zones": dataSourceAwsAvailabilityZones(),
"aws_region": dataSourceAwsRegion(),
"aws_subnet": dataSourceAwsSubnet(),
"aws_vpc": dataSourceAwsVpc(),
},
Expand Down

0 comments on commit d31fa9c

Please sign in to comment.