github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/pagerduty/data_source_pagerduty_user.go (about)

     1  package pagerduty
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	pagerduty "github.com/PagerDuty/go-pagerduty"
     8  	"github.com/hashicorp/terraform/helper/schema"
     9  )
    10  
    11  func dataSourcePagerDutyUser() *schema.Resource {
    12  	return &schema.Resource{
    13  		Read: dataSourcePagerDutyUserRead,
    14  
    15  		Schema: map[string]*schema.Schema{
    16  			"name": {
    17  				Type:     schema.TypeString,
    18  				Computed: true,
    19  			},
    20  			"email": {
    21  				Type:     schema.TypeString,
    22  				Required: true,
    23  			},
    24  		},
    25  	}
    26  }
    27  
    28  func dataSourcePagerDutyUserRead(d *schema.ResourceData, meta interface{}) error {
    29  	client := meta.(*pagerduty.Client)
    30  
    31  	log.Printf("[INFO] Reading PagerDuty user")
    32  
    33  	searchEmail := d.Get("email").(string)
    34  
    35  	o := &pagerduty.ListUsersOptions{
    36  		Query: searchEmail,
    37  	}
    38  
    39  	resp, err := client.ListUsers(*o)
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	var found *pagerduty.User
    45  
    46  	for _, user := range resp.Users {
    47  		if user.Email == searchEmail {
    48  			found = &user
    49  			break
    50  		}
    51  	}
    52  
    53  	if found == nil {
    54  		return fmt.Errorf("Unable to locate any user with the email: %s", searchEmail)
    55  	}
    56  
    57  	d.SetId(found.ID)
    58  	d.Set("name", found.Name)
    59  	d.Set("email", found.Email)
    60  
    61  	return nil
    62  }