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

     1  package azurerm
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"net/http"
     8  	"strings"
     9  
    10  	"github.com/Azure/azure-sdk-for-go/arm/cdn"
    11  	"github.com/hashicorp/terraform/helper/hashcode"
    12  	"github.com/hashicorp/terraform/helper/schema"
    13  )
    14  
    15  func resourceArmCdnEndpoint() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceArmCdnEndpointCreate,
    18  		Read:   resourceArmCdnEndpointRead,
    19  		Update: resourceArmCdnEndpointUpdate,
    20  		Delete: resourceArmCdnEndpointDelete,
    21  
    22  		Schema: map[string]*schema.Schema{
    23  			"name": {
    24  				Type:     schema.TypeString,
    25  				Required: true,
    26  				ForceNew: true,
    27  			},
    28  
    29  			"location": {
    30  				Type:      schema.TypeString,
    31  				Required:  true,
    32  				ForceNew:  true,
    33  				StateFunc: azureRMNormalizeLocation,
    34  			},
    35  
    36  			"resource_group_name": {
    37  				Type:     schema.TypeString,
    38  				Required: true,
    39  				ForceNew: true,
    40  			},
    41  
    42  			"profile_name": {
    43  				Type:     schema.TypeString,
    44  				Required: true,
    45  				ForceNew: true,
    46  			},
    47  
    48  			"origin_host_header": {
    49  				Type:     schema.TypeString,
    50  				Optional: true,
    51  				Computed: true,
    52  			},
    53  
    54  			"is_http_allowed": {
    55  				Type:     schema.TypeBool,
    56  				Optional: true,
    57  				Default:  true,
    58  			},
    59  
    60  			"is_https_allowed": {
    61  				Type:     schema.TypeBool,
    62  				Optional: true,
    63  				Default:  true,
    64  			},
    65  
    66  			"origin": {
    67  				Type:     schema.TypeSet,
    68  				Required: true,
    69  				ForceNew: true,
    70  				Elem: &schema.Resource{
    71  					Schema: map[string]*schema.Schema{
    72  						"name": {
    73  							Type:     schema.TypeString,
    74  							Required: true,
    75  						},
    76  
    77  						"host_name": {
    78  							Type:     schema.TypeString,
    79  							Required: true,
    80  						},
    81  
    82  						"http_port": {
    83  							Type:     schema.TypeInt,
    84  							Optional: true,
    85  							Computed: true,
    86  						},
    87  
    88  						"https_port": {
    89  							Type:     schema.TypeInt,
    90  							Optional: true,
    91  							Computed: true,
    92  						},
    93  					},
    94  				},
    95  				Set: resourceArmCdnEndpointOriginHash,
    96  			},
    97  
    98  			"origin_path": {
    99  				Type:     schema.TypeString,
   100  				Optional: true,
   101  				Computed: true,
   102  			},
   103  
   104  			"querystring_caching_behaviour": {
   105  				Type:         schema.TypeString,
   106  				Optional:     true,
   107  				Default:      "IgnoreQueryString",
   108  				ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour,
   109  			},
   110  
   111  			"content_types_to_compress": {
   112  				Type:     schema.TypeSet,
   113  				Optional: true,
   114  				Computed: true,
   115  				Elem: &schema.Schema{
   116  					Type: schema.TypeString,
   117  				},
   118  				Set: schema.HashString,
   119  			},
   120  
   121  			"is_compression_enabled": {
   122  				Type:     schema.TypeBool,
   123  				Optional: true,
   124  				Default:  false,
   125  			},
   126  
   127  			"host_name": {
   128  				Type:     schema.TypeString,
   129  				Computed: true,
   130  			},
   131  
   132  			"tags": tagsSchema(),
   133  		},
   134  	}
   135  }
   136  
   137  func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error {
   138  	client := meta.(*ArmClient)
   139  	cdnEndpointsClient := client.cdnEndpointsClient
   140  
   141  	log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.")
   142  
   143  	name := d.Get("name").(string)
   144  	location := d.Get("location").(string)
   145  	resGroup := d.Get("resource_group_name").(string)
   146  	profileName := d.Get("profile_name").(string)
   147  	http_allowed := d.Get("is_http_allowed").(bool)
   148  	https_allowed := d.Get("is_https_allowed").(bool)
   149  	compression_enabled := d.Get("is_compression_enabled").(bool)
   150  	caching_behaviour := d.Get("querystring_caching_behaviour").(string)
   151  	tags := d.Get("tags").(map[string]interface{})
   152  
   153  	properties := cdn.EndpointPropertiesCreateParameters{
   154  		IsHTTPAllowed:              &http_allowed,
   155  		IsHTTPSAllowed:             &https_allowed,
   156  		IsCompressionEnabled:       &compression_enabled,
   157  		QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour),
   158  	}
   159  
   160  	origins, originsErr := expandAzureRmCdnEndpointOrigins(d)
   161  	if originsErr != nil {
   162  		return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr)
   163  	}
   164  	if len(origins) > 0 {
   165  		properties.Origins = &origins
   166  	}
   167  
   168  	if v, ok := d.GetOk("origin_host_header"); ok {
   169  		host_header := v.(string)
   170  		properties.OriginHostHeader = &host_header
   171  	}
   172  
   173  	if v, ok := d.GetOk("origin_path"); ok {
   174  		origin_path := v.(string)
   175  		properties.OriginPath = &origin_path
   176  	}
   177  
   178  	if v, ok := d.GetOk("content_types_to_compress"); ok {
   179  		var content_types []string
   180  		ctypes := v.(*schema.Set).List()
   181  		for _, ct := range ctypes {
   182  			str := ct.(string)
   183  			content_types = append(content_types, str)
   184  		}
   185  
   186  		properties.ContentTypesToCompress = &content_types
   187  	}
   188  
   189  	cdnEndpoint := cdn.EndpointCreateParameters{
   190  		Location:   &location,
   191  		Properties: &properties,
   192  		Tags:       expandTags(tags),
   193  	}
   194  
   195  	_, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup, make(chan struct{}))
   196  	if err != nil {
   197  		return err
   198  	}
   199  
   200  	read, err := cdnEndpointsClient.Get(name, profileName, resGroup)
   201  	if err != nil {
   202  		return err
   203  	}
   204  	if read.ID == nil {
   205  		return fmt.Errorf("Cannot read CND Endpoint %s/%s (resource group %s) ID", profileName, name, resGroup)
   206  	}
   207  
   208  	d.SetId(*read.ID)
   209  
   210  	return resourceArmCdnEndpointRead(d, meta)
   211  }
   212  
   213  func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error {
   214  	cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient
   215  
   216  	id, err := parseAzureResourceID(d.Id())
   217  	if err != nil {
   218  		return err
   219  	}
   220  	resGroup := id.ResourceGroup
   221  	name := id.Path["endpoints"]
   222  	profileName := id.Path["profiles"]
   223  	if profileName == "" {
   224  		profileName = id.Path["Profiles"]
   225  	}
   226  	log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup)
   227  	resp, err := cdnEndpointsClient.Get(name, profileName, resGroup)
   228  	if err != nil {
   229  		if resp.StatusCode == http.StatusNotFound {
   230  			d.SetId("")
   231  			return nil
   232  		}
   233  		return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err)
   234  	}
   235  
   236  	d.Set("name", resp.Name)
   237  	d.Set("host_name", resp.Properties.HostName)
   238  	d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled)
   239  	d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed)
   240  	d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed)
   241  	d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior)
   242  	if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" {
   243  		d.Set("origin_host_header", resp.Properties.OriginHostHeader)
   244  	}
   245  	if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" {
   246  		d.Set("origin_path", resp.Properties.OriginPath)
   247  	}
   248  	if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 {
   249  		d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress))
   250  	}
   251  	d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins))
   252  
   253  	flattenAndSetTags(d, resp.Tags)
   254  
   255  	return nil
   256  }
   257  
   258  func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error {
   259  	cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient
   260  
   261  	if !d.HasChange("tags") {
   262  		return nil
   263  	}
   264  
   265  	name := d.Get("name").(string)
   266  	resGroup := d.Get("resource_group_name").(string)
   267  	profileName := d.Get("profile_name").(string)
   268  	http_allowed := d.Get("is_http_allowed").(bool)
   269  	https_allowed := d.Get("is_https_allowed").(bool)
   270  	compression_enabled := d.Get("is_compression_enabled").(bool)
   271  	caching_behaviour := d.Get("querystring_caching_behaviour").(string)
   272  	newTags := d.Get("tags").(map[string]interface{})
   273  
   274  	properties := cdn.EndpointPropertiesUpdateParameters{
   275  		IsHTTPAllowed:              &http_allowed,
   276  		IsHTTPSAllowed:             &https_allowed,
   277  		IsCompressionEnabled:       &compression_enabled,
   278  		QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour),
   279  	}
   280  
   281  	if d.HasChange("origin_host_header") {
   282  		host_header := d.Get("origin_host_header").(string)
   283  		properties.OriginHostHeader = &host_header
   284  	}
   285  
   286  	if d.HasChange("origin_path") {
   287  		origin_path := d.Get("origin_path").(string)
   288  		properties.OriginPath = &origin_path
   289  	}
   290  
   291  	if d.HasChange("content_types_to_compress") {
   292  		var content_types []string
   293  		ctypes := d.Get("content_types_to_compress").(*schema.Set).List()
   294  		for _, ct := range ctypes {
   295  			str := ct.(string)
   296  			content_types = append(content_types, str)
   297  		}
   298  
   299  		properties.ContentTypesToCompress = &content_types
   300  	}
   301  
   302  	updateProps := cdn.EndpointUpdateParameters{
   303  		Tags:       expandTags(newTags),
   304  		Properties: &properties,
   305  	}
   306  
   307  	_, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup, make(chan struct{}))
   308  	if err != nil {
   309  		return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err)
   310  	}
   311  
   312  	return resourceArmCdnEndpointRead(d, meta)
   313  }
   314  
   315  func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error {
   316  	client := meta.(*ArmClient).cdnEndpointsClient
   317  
   318  	id, err := parseAzureResourceID(d.Id())
   319  	if err != nil {
   320  		return err
   321  	}
   322  	resGroup := id.ResourceGroup
   323  	profileName := id.Path["profiles"]
   324  	if profileName == "" {
   325  		profileName = id.Path["Profiles"]
   326  	}
   327  	name := id.Path["endpoints"]
   328  
   329  	accResp, err := client.DeleteIfExists(name, profileName, resGroup, make(chan struct{}))
   330  	if err != nil {
   331  		if accResp.StatusCode == http.StatusNotFound {
   332  			return nil
   333  		}
   334  		return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err)
   335  	}
   336  
   337  	return err
   338  }
   339  
   340  func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) {
   341  	value := strings.ToLower(v.(string))
   342  	cachingTypes := map[string]bool{
   343  		"ignorequerystring": true,
   344  		"bypasscaching":     true,
   345  		"usequerystring":    true,
   346  	}
   347  
   348  	if !cachingTypes[value] {
   349  		errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString"))
   350  	}
   351  	return
   352  }
   353  
   354  func resourceArmCdnEndpointOriginHash(v interface{}) int {
   355  	var buf bytes.Buffer
   356  	m := v.(map[string]interface{})
   357  	buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
   358  	buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string)))
   359  
   360  	return hashcode.String(buf.String())
   361  }
   362  
   363  func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) {
   364  	configs := d.Get("origin").(*schema.Set).List()
   365  	origins := make([]cdn.DeepCreatedOrigin, 0, len(configs))
   366  
   367  	for _, configRaw := range configs {
   368  		data := configRaw.(map[string]interface{})
   369  
   370  		host_name := data["host_name"].(string)
   371  
   372  		properties := cdn.DeepCreatedOriginProperties{
   373  			HostName: &host_name,
   374  		}
   375  
   376  		if v, ok := data["https_port"]; ok {
   377  			https_port := int32(v.(int))
   378  			properties.HTTPSPort = &https_port
   379  
   380  		}
   381  
   382  		if v, ok := data["http_port"]; ok {
   383  			http_port := int32(v.(int))
   384  			properties.HTTPPort = &http_port
   385  		}
   386  
   387  		name := data["name"].(string)
   388  
   389  		origin := cdn.DeepCreatedOrigin{
   390  			Name:       &name,
   391  			Properties: &properties,
   392  		}
   393  
   394  		origins = append(origins, origin)
   395  	}
   396  
   397  	return origins, nil
   398  }
   399  
   400  func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} {
   401  	result := make([]map[string]interface{}, 0, len(*list))
   402  	for _, i := range *list {
   403  		l := map[string]interface{}{
   404  			"name":      *i.Name,
   405  			"host_name": *i.Properties.HostName,
   406  		}
   407  
   408  		if i.Properties.HTTPPort != nil {
   409  			l["http_port"] = *i.Properties.HTTPPort
   410  		}
   411  		if i.Properties.HTTPSPort != nil {
   412  			l["https_port"] = *i.Properties.HTTPSPort
   413  		}
   414  		result = append(result, l)
   415  	}
   416  	return result
   417  }
   418  
   419  func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} {
   420  	vs := make([]interface{}, 0, len(*list))
   421  	for _, v := range *list {
   422  		vs = append(vs, v)
   423  	}
   424  	return vs
   425  }