github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/builtin/providers/opsgenie/resource_opsgenie_team.go (about)

     1  package opsgenie
     2  
     3  import (
     4  	"log"
     5  
     6  	"fmt"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/opsgenie/opsgenie-go-sdk/team"
    11  	"regexp"
    12  )
    13  
    14  func resourceOpsGenieTeam() *schema.Resource {
    15  	return &schema.Resource{
    16  		Create: resourceOpsGenieTeamCreate,
    17  		Read:   resourceOpsGenieTeamRead,
    18  		Update: resourceOpsGenieTeamUpdate,
    19  		Delete: resourceOpsGenieTeamDelete,
    20  		Importer: &schema.ResourceImporter{
    21  			State: schema.ImportStatePassthrough,
    22  		},
    23  		Schema: map[string]*schema.Schema{
    24  			"name": {
    25  				Type:         schema.TypeString,
    26  				Required:     true,
    27  				ValidateFunc: validateOpsGenieTeamName,
    28  			},
    29  			"member": {
    30  				Type:     schema.TypeList,
    31  				Optional: true,
    32  				Elem: &schema.Resource{
    33  					Schema: map[string]*schema.Schema{
    34  						"username": {
    35  							Type:     schema.TypeString,
    36  							Required: true,
    37  						},
    38  
    39  						"role": {
    40  							Type:         schema.TypeString,
    41  							Optional:     true,
    42  							Default:      "user",
    43  							ValidateFunc: validateOpsGenieTeamRole,
    44  						},
    45  					},
    46  				},
    47  			},
    48  		},
    49  	}
    50  }
    51  
    52  func resourceOpsGenieTeamCreate(d *schema.ResourceData, meta interface{}) error {
    53  	client := meta.(*OpsGenieClient).teams
    54  
    55  	name := d.Get("name").(string)
    56  
    57  	createRequest := team.CreateTeamRequest{
    58  		Name:    name,
    59  		Members: expandOpsGenieTeamMembers(d),
    60  	}
    61  
    62  	log.Printf("[INFO] Creating OpsGenie team '%s'", name)
    63  
    64  	createResponse, err := client.Create(createRequest)
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	err = checkOpsGenieResponse(createResponse.Code, createResponse.Status)
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	getRequest := team.GetTeamRequest{
    75  		Name: name,
    76  	}
    77  
    78  	getResponse, err := client.Get(getRequest)
    79  	if err != nil {
    80  		return err
    81  	}
    82  
    83  	d.SetId(getResponse.Id)
    84  
    85  	return resourceOpsGenieTeamRead(d, meta)
    86  }
    87  
    88  func resourceOpsGenieTeamRead(d *schema.ResourceData, meta interface{}) error {
    89  	client := meta.(*OpsGenieClient).teams
    90  
    91  	listRequest := team.ListTeamsRequest{}
    92  	listResponse, err := client.List(listRequest)
    93  	if err != nil {
    94  		return err
    95  	}
    96  
    97  	var found *team.GetTeamResponse
    98  	for _, team := range listResponse.Teams {
    99  		if team.Id == d.Id() {
   100  			found = &team
   101  			break
   102  		}
   103  	}
   104  
   105  	if found == nil {
   106  		d.SetId("")
   107  		log.Printf("[INFO] Team %q not found. Removing from state", d.Get("name").(string))
   108  		return nil
   109  	}
   110  
   111  	getRequest := team.GetTeamRequest{
   112  		Id: d.Id(),
   113  	}
   114  
   115  	getResponse, err := client.Get(getRequest)
   116  	if err != nil {
   117  		return err
   118  	}
   119  
   120  	d.Set("name", getResponse.Name)
   121  	d.Set("member", flattenOpsGenieTeamMembers(getResponse.Members))
   122  
   123  	return nil
   124  }
   125  
   126  func resourceOpsGenieTeamUpdate(d *schema.ResourceData, meta interface{}) error {
   127  	client := meta.(*OpsGenieClient).teams
   128  	name := d.Get("name").(string)
   129  
   130  	updateRequest := team.UpdateTeamRequest{
   131  		Id:      d.Id(),
   132  		Name:    name,
   133  		Members: expandOpsGenieTeamMembers(d),
   134  	}
   135  
   136  	log.Printf("[INFO] Updating OpsGenie team '%s'", name)
   137  
   138  	updateResponse, err := client.Update(updateRequest)
   139  	if err != nil {
   140  		return err
   141  	}
   142  
   143  	err = checkOpsGenieResponse(updateResponse.Code, updateResponse.Status)
   144  	if err != nil {
   145  		return err
   146  	}
   147  
   148  	return nil
   149  }
   150  
   151  func resourceOpsGenieTeamDelete(d *schema.ResourceData, meta interface{}) error {
   152  	log.Printf("[INFO] Deleting OpsGenie team '%s'", d.Get("name").(string))
   153  	client := meta.(*OpsGenieClient).teams
   154  
   155  	deleteRequest := team.DeleteTeamRequest{
   156  		Id: d.Id(),
   157  	}
   158  
   159  	_, err := client.Delete(deleteRequest)
   160  	if err != nil {
   161  		return err
   162  	}
   163  
   164  	return nil
   165  }
   166  
   167  func flattenOpsGenieTeamMembers(input []team.Member) []interface{} {
   168  	members := make([]interface{}, 0, len(input))
   169  	for _, inputMember := range input {
   170  		outputMember := make(map[string]interface{})
   171  		outputMember["username"] = inputMember.User
   172  		outputMember["role"] = inputMember.Role
   173  
   174  		members = append(members, outputMember)
   175  	}
   176  
   177  	return members
   178  }
   179  
   180  func expandOpsGenieTeamMembers(d *schema.ResourceData) []team.Member {
   181  	input := d.Get("member").([]interface{})
   182  
   183  	members := make([]team.Member, 0, len(input))
   184  	if input == nil {
   185  		return members
   186  	}
   187  
   188  	for _, v := range input {
   189  		config := v.(map[string]interface{})
   190  
   191  		username := config["username"].(string)
   192  		role := config["role"].(string)
   193  
   194  		member := team.Member{
   195  			User: username,
   196  			Role: role,
   197  		}
   198  
   199  		members = append(members, member)
   200  	}
   201  
   202  	return members
   203  }
   204  
   205  func validateOpsGenieTeamName(v interface{}, k string) (ws []string, errors []error) {
   206  	value := v.(string)
   207  	if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(value) {
   208  		errors = append(errors, fmt.Errorf(
   209  			"only alpha numeric characters and underscores are allowed in %q: %q", k, value))
   210  	}
   211  
   212  	if len(value) >= 100 {
   213  		errors = append(errors, fmt.Errorf("%q cannot be longer than 100 characters: %q %d", k, value, len(value)))
   214  	}
   215  
   216  	return
   217  }
   218  
   219  func validateOpsGenieTeamRole(v interface{}, k string) (ws []string, errors []error) {
   220  	value := strings.ToLower(v.(string))
   221  	families := map[string]bool{
   222  		"admin": true,
   223  		"user":  true,
   224  	}
   225  
   226  	if !families[value] {
   227  		errors = append(errors, fmt.Errorf("OpsGenie Team Role can only be 'Admin' or 'User'"))
   228  	}
   229  
   230  	return
   231  }