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

     1  package azurerm
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/terraform/helper/schema"
     8  )
     9  
    10  func tagsSchema() *schema.Schema {
    11  	return &schema.Schema{
    12  		Type:         schema.TypeMap,
    13  		Optional:     true,
    14  		Computed:     true,
    15  		ValidateFunc: validateAzureRMTags,
    16  	}
    17  }
    18  
    19  func tagValueToString(v interface{}) (string, error) {
    20  	switch value := v.(type) {
    21  	case string:
    22  		return value, nil
    23  	case int:
    24  		return fmt.Sprintf("%d", value), nil
    25  	default:
    26  		return "", fmt.Errorf("unknown tag type %T in tag value", value)
    27  	}
    28  }
    29  
    30  func validateAzureRMTags(v interface{}, k string) (ws []string, es []error) {
    31  	tagsMap := v.(map[string]interface{})
    32  
    33  	if len(tagsMap) > 15 {
    34  		es = append(es, errors.New("a maximum of 15 tags can be applied to each ARM resource"))
    35  	}
    36  
    37  	for k, v := range tagsMap {
    38  		if len(k) > 512 {
    39  			es = append(es, fmt.Errorf("the maximum length for a tag key is 512 characters: %q is %d characters", k, len(k)))
    40  		}
    41  
    42  		value, err := tagValueToString(v)
    43  		if err != nil {
    44  			es = append(es, err)
    45  		} else if len(value) > 256 {
    46  			es = append(es, fmt.Errorf("the maximum length for a tag value is 256 characters: the value for %q is %d characters", k, len(value)))
    47  		}
    48  	}
    49  
    50  	return
    51  }
    52  
    53  func expandTags(tagsMap map[string]interface{}) *map[string]*string {
    54  	output := make(map[string]*string, len(tagsMap))
    55  
    56  	for i, v := range tagsMap {
    57  		//Validate should have ignored this error already
    58  		value, _ := tagValueToString(v)
    59  		output[i] = &value
    60  	}
    61  
    62  	return &output
    63  }
    64  
    65  func flattenAndSetTags(d *schema.ResourceData, tagsMap *map[string]*string) {
    66  	if tagsMap == nil {
    67  		d.Set("tags", make(map[string]interface{}))
    68  		return
    69  	}
    70  
    71  	output := make(map[string]interface{}, len(*tagsMap))
    72  
    73  	for i, v := range *tagsMap {
    74  		output[i] = *v
    75  	}
    76  
    77  	d.Set("tags", output)
    78  }