github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/profitbricks/data_source_datacenter.go (about)

     1  package profitbricks
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/hashicorp/terraform/helper/schema"
     6  	"github.com/profitbricks/profitbricks-sdk-go"
     7  	"log"
     8  	"strings"
     9  )
    10  
    11  func dataSourceDataCenter() *schema.Resource {
    12  	return &schema.Resource{
    13  		Read: dataSourceDataCenterRead,
    14  		Schema: map[string]*schema.Schema{
    15  			"name": {
    16  				Type:     schema.TypeString,
    17  				Required: true,
    18  			},
    19  			"location": {
    20  				Type:     schema.TypeString,
    21  				Optional: true,
    22  			},
    23  		},
    24  	}
    25  }
    26  
    27  func dataSourceDataCenterRead(d *schema.ResourceData, meta interface{}) error {
    28  	datacenters := profitbricks.ListDatacenters()
    29  
    30  	if datacenters.StatusCode > 299 {
    31  		return fmt.Errorf("An error occured while fetching datacenters %s", datacenters.Response)
    32  	}
    33  
    34  	name := d.Get("name").(string)
    35  	location, locationOk := d.GetOk("location")
    36  
    37  	results := []profitbricks.Datacenter{}
    38  
    39  	for _, dc := range datacenters.Items {
    40  		if dc.Properties.Name == name || strings.Contains(dc.Properties.Name, name) {
    41  			results = append(results, dc)
    42  		}
    43  	}
    44  
    45  	if locationOk {
    46  		log.Printf("[INFO] searching dcs by location***********")
    47  		locationResults := []profitbricks.Datacenter{}
    48  		for _, dc := range results {
    49  			if dc.Properties.Location == location.(string) {
    50  				locationResults = append(locationResults, dc)
    51  			}
    52  		}
    53  		results = locationResults
    54  	}
    55  	log.Printf("[INFO] Results length %d *************", len(results))
    56  
    57  	if len(results) > 1 {
    58  		log.Printf("[INFO] Results length greater than 1")
    59  		return fmt.Errorf("There is more than one datacenters that match the search criteria")
    60  	}
    61  
    62  	if len(results) == 0 {
    63  		return fmt.Errorf("There are no datacenters that match the search criteria")
    64  	}
    65  
    66  	d.SetId(results[0].Id)
    67  
    68  	return nil
    69  }