github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/profitbricks/data_source_location.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 dataSourceLocation() *schema.Resource {
    12  	return &schema.Resource{
    13  		Read: dataSourceLocationRead,
    14  		Schema: map[string]*schema.Schema{
    15  			"name": {
    16  				Type:     schema.TypeString,
    17  				Optional: true,
    18  			},
    19  			"feature": {
    20  				Type:     schema.TypeString,
    21  				Optional: true,
    22  			},
    23  		},
    24  	}
    25  }
    26  
    27  func dataSourceLocationRead(d *schema.ResourceData, meta interface{}) error {
    28  	locations := profitbricks.ListLocations()
    29  
    30  	if locations.StatusCode > 299 {
    31  		return fmt.Errorf("An error occured while fetching ProfitBricks locations %s", locations.Response)
    32  	}
    33  
    34  	name, nameOk := d.GetOk("name")
    35  	feature, featureOk := d.GetOk("features")
    36  
    37  	if !nameOk && !featureOk {
    38  		return fmt.Errorf("Either 'name' or 'feature' must be provided.")
    39  	}
    40  	results := []profitbricks.Location{}
    41  
    42  	for _, loc := range locations.Items {
    43  		if loc.Properties.Name == name.(string) || strings.Contains(loc.Properties.Name, name.(string)) {
    44  			results = append(results, loc)
    45  		}
    46  	}
    47  
    48  	if featureOk {
    49  		locationResults := []profitbricks.Location{}
    50  		for _, loc := range results {
    51  			for _, f := range loc.Properties.Features {
    52  				if f == feature.(string) {
    53  					locationResults = append(locationResults, loc)
    54  				}
    55  			}
    56  		}
    57  		results = locationResults
    58  	}
    59  	log.Printf("[INFO] Results length %d *************", len(results))
    60  
    61  	if len(results) > 1 {
    62  		log.Printf("[INFO] Results length greater than 1")
    63  		return fmt.Errorf("There is more than one location that match the search criteria")
    64  	}
    65  
    66  	if len(results) == 0 {
    67  		return fmt.Errorf("There are no locations that match the search criteria")
    68  	}
    69  
    70  	d.SetId(results[0].Id)
    71  
    72  	return nil
    73  }