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

     1  package pagerduty
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"regexp"
     7  
     8  	pagerduty "github.com/PagerDuty/go-pagerduty"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  )
    11  
    12  func dataSourcePagerDutyVendor() *schema.Resource {
    13  	return &schema.Resource{
    14  		Read: dataSourcePagerDutyVendorRead,
    15  
    16  		Schema: map[string]*schema.Schema{
    17  			"name_regex": {
    18  				Type:     schema.TypeString,
    19  				Required: true,
    20  			},
    21  			"name": {
    22  				Type:     schema.TypeString,
    23  				Computed: true,
    24  			},
    25  			"type": {
    26  				Type:     schema.TypeString,
    27  				Computed: true,
    28  			},
    29  		},
    30  	}
    31  }
    32  
    33  func dataSourcePagerDutyVendorRead(d *schema.ResourceData, meta interface{}) error {
    34  	client := meta.(*pagerduty.Client)
    35  
    36  	log.Printf("[INFO] Reading PagerDuty vendors")
    37  
    38  	resp, err := getVendors(client)
    39  
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	r := regexp.MustCompile("(?i)" + d.Get("name_regex").(string))
    45  
    46  	var vendors []pagerduty.Vendor
    47  	var vendorNames []string
    48  
    49  	for _, v := range resp {
    50  		if r.MatchString(v.Name) {
    51  			vendors = append(vendors, v)
    52  			vendorNames = append(vendorNames, v.Name)
    53  		}
    54  	}
    55  
    56  	if len(vendors) == 0 {
    57  		return fmt.Errorf("Unable to locate any vendor using the regex string: %s", r.String())
    58  	} else if len(vendors) > 1 {
    59  		return fmt.Errorf("Your query returned more than one result using the regex string: %#v. Found vendors: %#v", r.String(), vendorNames)
    60  	}
    61  
    62  	vendor := vendors[0]
    63  
    64  	genericServiceType := vendor.GenericServiceType
    65  
    66  	switch {
    67  	case genericServiceType == "email":
    68  		genericServiceType = "generic_email_inbound_integration"
    69  	case genericServiceType == "api":
    70  		genericServiceType = "generic_events_api_inbound_integration"
    71  	}
    72  
    73  	d.SetId(vendor.ID)
    74  	d.Set("name", vendor.Name)
    75  	d.Set("type", genericServiceType)
    76  
    77  	return nil
    78  }