github.com/erriapo/terraform@v0.6.12-0.20160203182612-0340ea72354f/builtin/providers/azurerm/provider.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
    10  	"github.com/hashicorp/go-multierror"
    11  	"github.com/hashicorp/terraform/helper/mutexkv"
    12  	"github.com/hashicorp/terraform/helper/schema"
    13  	"github.com/hashicorp/terraform/terraform"
    14  )
    15  
    16  // Provider returns a terraform.ResourceProvider.
    17  func Provider() terraform.ResourceProvider {
    18  	return &schema.Provider{
    19  		Schema: map[string]*schema.Schema{
    20  			"subscription_id": &schema.Schema{
    21  				Type:        schema.TypeString,
    22  				Required:    true,
    23  				DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
    24  			},
    25  
    26  			"client_id": &schema.Schema{
    27  				Type:        schema.TypeString,
    28  				Required:    true,
    29  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
    30  			},
    31  
    32  			"client_secret": &schema.Schema{
    33  				Type:        schema.TypeString,
    34  				Required:    true,
    35  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
    36  			},
    37  
    38  			"tenant_id": &schema.Schema{
    39  				Type:        schema.TypeString,
    40  				Required:    true,
    41  				DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
    42  			},
    43  		},
    44  
    45  		ResourcesMap: map[string]*schema.Resource{
    46  			"azurerm_resource_group":         resourceArmResourceGroup(),
    47  			"azurerm_virtual_network":        resourceArmVirtualNetwork(),
    48  			"azurerm_local_network_gateway":  resourceArmLocalNetworkGateway(),
    49  			"azurerm_availability_set":       resourceArmAvailabilitySet(),
    50  			"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
    51  			"azurerm_network_security_rule":  resourceArmNetworkSecurityRule(),
    52  			"azurerm_public_ip":              resourceArmPublicIp(),
    53  			"azurerm_subnet":                 resourceArmSubnet(),
    54  			"azurerm_network_interface":      resourceArmNetworkInterface(),
    55  			"azurerm_route_table":            resourceArmRouteTable(),
    56  			"azurerm_route":                  resourceArmRoute(),
    57  			"azurerm_cdn_profile":            resourceArmCdnProfile(),
    58  			"azurerm_cdn_endpoint":           resourceArmCdnEndpoint(),
    59  			"azurerm_storage_account":        resourceArmStorageAccount(),
    60  			"azurerm_storage_container":      resourceArmStorageContainer(),
    61  			"azurerm_storage_blob":           resourceArmStorageBlob(),
    62  			"azurerm_storage_queue":          resourceArmStorageQueue(),
    63  		},
    64  		ConfigureFunc: providerConfigure,
    65  	}
    66  }
    67  
    68  // Config is the configuration structure used to instantiate a
    69  // new Azure management client.
    70  type Config struct {
    71  	ManagementURL string
    72  
    73  	SubscriptionID string
    74  	ClientID       string
    75  	ClientSecret   string
    76  	TenantID       string
    77  }
    78  
    79  func (c Config) validate() error {
    80  	var err *multierror.Error
    81  
    82  	if c.SubscriptionID == "" {
    83  		err = multierror.Append(err, fmt.Errorf("Subscription ID must be configured for the AzureRM provider"))
    84  	}
    85  	if c.ClientID == "" {
    86  		err = multierror.Append(err, fmt.Errorf("Client ID must be configured for the AzureRM provider"))
    87  	}
    88  	if c.ClientSecret == "" {
    89  		err = multierror.Append(err, fmt.Errorf("Client Secret must be configured for the AzureRM provider"))
    90  	}
    91  	if c.TenantID == "" {
    92  		err = multierror.Append(err, fmt.Errorf("Tenant ID must be configured for the AzureRM provider"))
    93  	}
    94  
    95  	return err.ErrorOrNil()
    96  }
    97  
    98  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
    99  	config := Config{
   100  		SubscriptionID: d.Get("subscription_id").(string),
   101  		ClientID:       d.Get("client_id").(string),
   102  		ClientSecret:   d.Get("client_secret").(string),
   103  		TenantID:       d.Get("tenant_id").(string),
   104  	}
   105  
   106  	if err := config.validate(); err != nil {
   107  		return nil, err
   108  	}
   109  
   110  	client, err := config.getArmClient()
   111  	if err != nil {
   112  		return nil, err
   113  	}
   114  
   115  	err = registerAzureResourceProvidersWithSubscription(&config, client)
   116  	if err != nil {
   117  		return nil, err
   118  	}
   119  
   120  	return client, nil
   121  }
   122  
   123  // registerAzureResourceProvidersWithSubscription uses the providers client to register
   124  // all Azure resource providers which the Terraform provider may require (regardless of
   125  // whether they are actually used by the configuration or not). It was confirmed by Microsoft
   126  // that this is the approach their own internal tools also take.
   127  func registerAzureResourceProvidersWithSubscription(config *Config, client *ArmClient) error {
   128  	providerClient := client.providers
   129  
   130  	providers := []string{"Microsoft.Network", "Microsoft.Compute", "Microsoft.Cdn", "Microsoft.Storage"}
   131  
   132  	for _, v := range providers {
   133  		res, err := providerClient.Register(v)
   134  		if err != nil {
   135  			return err
   136  		}
   137  
   138  		if res.StatusCode != http.StatusOK {
   139  			return fmt.Errorf("Error registering provider %q with subscription %q", v, config.SubscriptionID)
   140  		}
   141  	}
   142  
   143  	return nil
   144  }
   145  
   146  // azureRMNormalizeLocation is a function which normalises human-readable region/location
   147  // names (e.g. "West US") to the values used and returned by the Azure API (e.g. "westus").
   148  // In state we track the API internal version as it is easier to go from the human form
   149  // to the canonical form than the other way around.
   150  func azureRMNormalizeLocation(location interface{}) string {
   151  	input := location.(string)
   152  	return strings.Replace(strings.ToLower(input), " ", "", -1)
   153  }
   154  
   155  // pollIndefinitelyAsNeeded is a terrible hack which is necessary because the Azure
   156  // Storage API (and perhaps others) can have response times way beyond the default
   157  // retry timeouts, with no apparent upper bound. This effectively causes the client
   158  // to continue polling when it reaches the configured timeout. My investigations
   159  // suggest that this is neccesary when deleting and recreating a storage account with
   160  // the same name in a short (though undetermined) time period.
   161  //
   162  // It is possible that this will give Terraform the appearance of being slow in
   163  // future: I have attempted to mitigate this by logging whenever this happens. We
   164  // may want to revisit this with configurable timeouts in the future as clearly
   165  // unbounded wait loops is not ideal. It does seem preferable to the current situation
   166  // where our polling loop will time out _with an operation in progress_, but no ID
   167  // for the resource - so the state will not know about it, and conflicts will occur
   168  // on the next run.
   169  func pollIndefinitelyAsNeeded(client autorest.Client, response *http.Response, acceptableCodes ...int) (*http.Response, error) {
   170  	var resp *http.Response
   171  	var err error
   172  
   173  	for {
   174  		resp, err = client.PollAsNeeded(response, acceptableCodes...)
   175  		if err != nil {
   176  			if resp.StatusCode != http.StatusAccepted {
   177  				log.Printf("[DEBUG] Starting new polling loop for %q", response.Request.URL.Path)
   178  				continue
   179  			}
   180  
   181  			return resp, err
   182  		}
   183  
   184  		return resp, nil
   185  	}
   186  }
   187  
   188  // armMutexKV is the instance of MutexKV for ARM resources
   189  var armMutexKV = mutexkv.NewMutexKV()