github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/aws/data_source_aws_region.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/aws/aws-sdk-go/aws"
     8  	"github.com/aws/aws-sdk-go/service/ec2"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  )
    11  
    12  func dataSourceAwsRegion() *schema.Resource {
    13  	return &schema.Resource{
    14  		Read: dataSourceAwsRegionRead,
    15  
    16  		Schema: map[string]*schema.Schema{
    17  			"name": &schema.Schema{
    18  				Type:     schema.TypeString,
    19  				Optional: true,
    20  				Computed: true,
    21  			},
    22  
    23  			"current": &schema.Schema{
    24  				Type:     schema.TypeBool,
    25  				Optional: true,
    26  				Computed: true,
    27  			},
    28  
    29  			"endpoint": &schema.Schema{
    30  				Type:     schema.TypeString,
    31  				Optional: true,
    32  				Computed: true,
    33  			},
    34  		},
    35  	}
    36  }
    37  
    38  func dataSourceAwsRegionRead(d *schema.ResourceData, meta interface{}) error {
    39  	conn := meta.(*AWSClient).ec2conn
    40  	currentRegion := meta.(*AWSClient).region
    41  
    42  	req := &ec2.DescribeRegionsInput{}
    43  
    44  	req.RegionNames = make([]*string, 0, 2)
    45  	if name := d.Get("name").(string); name != "" {
    46  		req.RegionNames = append(req.RegionNames, aws.String(name))
    47  	}
    48  
    49  	if d.Get("current").(bool) {
    50  		req.RegionNames = append(req.RegionNames, aws.String(currentRegion))
    51  	}
    52  
    53  	req.Filters = buildEC2AttributeFilterList(
    54  		map[string]string{
    55  			"endpoint": d.Get("endpoint").(string),
    56  		},
    57  	)
    58  	if len(req.Filters) == 0 {
    59  		// Don't send an empty filters list; the EC2 API won't accept it.
    60  		req.Filters = nil
    61  	}
    62  
    63  	log.Printf("[DEBUG] DescribeRegions %s\n", req)
    64  	resp, err := conn.DescribeRegions(req)
    65  	if err != nil {
    66  		return err
    67  	}
    68  	if resp == nil || len(resp.Regions) == 0 {
    69  		return fmt.Errorf("no matching regions found")
    70  	}
    71  	if len(resp.Regions) > 1 {
    72  		return fmt.Errorf("multiple regions matched; use additional constraints to reduce matches to a single region")
    73  	}
    74  
    75  	region := resp.Regions[0]
    76  
    77  	d.SetId(*region.RegionName)
    78  	d.Set("id", region.RegionName)
    79  	d.Set("name", region.RegionName)
    80  	d.Set("endpoint", region.Endpoint)
    81  	d.Set("current", *region.RegionName == currentRegion)
    82  
    83  	return nil
    84  }