github.com/anfernee/terraform@v0.6.16-0.20160430000239-06e5085a92f2/builtin/providers/azurerm/provider.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"reflect"
     8  	"strings"
     9  
    10  	"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
    11  	"github.com/hashicorp/go-multierror"
    12  	"github.com/hashicorp/terraform/helper/mutexkv"
    13  	"github.com/hashicorp/terraform/helper/resource"
    14  	"github.com/hashicorp/terraform/helper/schema"
    15  	"github.com/hashicorp/terraform/terraform"
    16  	riviera "github.com/jen20/riviera/azure"
    17  	"sync"
    18  )
    19  
    20  // Provider returns a terraform.ResourceProvider.
    21  func Provider() terraform.ResourceProvider {
    22  	return &schema.Provider{
    23  		Schema: map[string]*schema.Schema{
    24  			"subscription_id": &schema.Schema{
    25  				Type:        schema.TypeString,
    26  				Required:    true,
    27  				DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
    28  			},
    29  
    30  			"client_id": &schema.Schema{
    31  				Type:        schema.TypeString,
    32  				Required:    true,
    33  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
    34  			},
    35  
    36  			"client_secret": &schema.Schema{
    37  				Type:        schema.TypeString,
    38  				Required:    true,
    39  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
    40  			},
    41  
    42  			"tenant_id": &schema.Schema{
    43  				Type:        schema.TypeString,
    44  				Required:    true,
    45  				DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
    46  			},
    47  		},
    48  
    49  		ResourcesMap: map[string]*schema.Resource{
    50  			"azurerm_availability_set":       resourceArmAvailabilitySet(),
    51  			"azurerm_cdn_endpoint":           resourceArmCdnEndpoint(),
    52  			"azurerm_cdn_profile":            resourceArmCdnProfile(),
    53  			"azurerm_dns_a_record":           resourceArmDnsARecord(),
    54  			"azurerm_dns_aaaa_record":        resourceArmDnsAAAARecord(),
    55  			"azurerm_dns_cname_record":       resourceArmDnsCNameRecord(),
    56  			"azurerm_dns_mx_record":          resourceArmDnsMxRecord(),
    57  			"azurerm_dns_ns_record":          resourceArmDnsNsRecord(),
    58  			"azurerm_dns_srv_record":         resourceArmDnsSrvRecord(),
    59  			"azurerm_dns_txt_record":         resourceArmDnsTxtRecord(),
    60  			"azurerm_dns_zone":               resourceArmDnsZone(),
    61  			"azurerm_local_network_gateway":  resourceArmLocalNetworkGateway(),
    62  			"azurerm_network_interface":      resourceArmNetworkInterface(),
    63  			"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
    64  			"azurerm_network_security_rule":  resourceArmNetworkSecurityRule(),
    65  			"azurerm_public_ip":              resourceArmPublicIp(),
    66  			"azurerm_resource_group":         resourceArmResourceGroup(),
    67  			"azurerm_route":                  resourceArmRoute(),
    68  			"azurerm_route_table":            resourceArmRouteTable(),
    69  			"azurerm_search_service":         resourceArmSearchService(),
    70  			"azurerm_sql_database":           resourceArmSqlDatabase(),
    71  			"azurerm_sql_firewall_rule":      resourceArmSqlFirewallRule(),
    72  			"azurerm_sql_server":             resourceArmSqlServer(),
    73  			"azurerm_storage_account":        resourceArmStorageAccount(),
    74  			"azurerm_storage_blob":           resourceArmStorageBlob(),
    75  			"azurerm_storage_container":      resourceArmStorageContainer(),
    76  			"azurerm_storage_queue":          resourceArmStorageQueue(),
    77  			"azurerm_subnet":                 resourceArmSubnet(),
    78  			"azurerm_template_deployment":    resourceArmTemplateDeployment(),
    79  			"azurerm_virtual_machine":        resourceArmVirtualMachine(),
    80  			"azurerm_virtual_network":        resourceArmVirtualNetwork(),
    81  		},
    82  		ConfigureFunc: providerConfigure,
    83  	}
    84  }
    85  
    86  // Config is the configuration structure used to instantiate a
    87  // new Azure management client.
    88  type Config struct {
    89  	ManagementURL string
    90  
    91  	SubscriptionID string
    92  	ClientID       string
    93  	ClientSecret   string
    94  	TenantID       string
    95  
    96  	validateCredentialsOnce sync.Once
    97  }
    98  
    99  func (c *Config) validate() error {
   100  	var err *multierror.Error
   101  
   102  	if c.SubscriptionID == "" {
   103  		err = multierror.Append(err, fmt.Errorf("Subscription ID must be configured for the AzureRM provider"))
   104  	}
   105  	if c.ClientID == "" {
   106  		err = multierror.Append(err, fmt.Errorf("Client ID must be configured for the AzureRM provider"))
   107  	}
   108  	if c.ClientSecret == "" {
   109  		err = multierror.Append(err, fmt.Errorf("Client Secret must be configured for the AzureRM provider"))
   110  	}
   111  	if c.TenantID == "" {
   112  		err = multierror.Append(err, fmt.Errorf("Tenant ID must be configured for the AzureRM provider"))
   113  	}
   114  
   115  	return err.ErrorOrNil()
   116  }
   117  
   118  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
   119  	config := &Config{
   120  		SubscriptionID: d.Get("subscription_id").(string),
   121  		ClientID:       d.Get("client_id").(string),
   122  		ClientSecret:   d.Get("client_secret").(string),
   123  		TenantID:       d.Get("tenant_id").(string),
   124  	}
   125  
   126  	if err := config.validate(); err != nil {
   127  		return nil, err
   128  	}
   129  
   130  	client, err := config.getArmClient()
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  
   135  	err = registerAzureResourceProvidersWithSubscription(client.rivieraClient)
   136  	if err != nil {
   137  		return nil, err
   138  	}
   139  
   140  	return client, nil
   141  }
   142  
   143  func registerProviderWithSubscription(providerName string, client *riviera.Client) error {
   144  	request := client.NewRequest()
   145  	request.Command = riviera.RegisterResourceProvider{
   146  		Namespace: providerName,
   147  	}
   148  
   149  	response, err := request.Execute()
   150  	if err != nil {
   151  		return fmt.Errorf("Cannot request provider registration for Azure Resource Manager: %s.", err)
   152  	}
   153  
   154  	if !response.IsSuccessful() {
   155  		return fmt.Errorf("Credentials for acessing the Azure Resource Manager API are likely " +
   156  			"to be incorrect, or\n  the service principal does not have permission to use " +
   157  			"the Azure Service Management\n  API.")
   158  	}
   159  
   160  	return nil
   161  }
   162  
   163  var providerRegistrationOnce sync.Once
   164  
   165  // registerAzureResourceProvidersWithSubscription uses the providers client to register
   166  // all Azure resource providers which the Terraform provider may require (regardless of
   167  // whether they are actually used by the configuration or not). It was confirmed by Microsoft
   168  // that this is the approach their own internal tools also take.
   169  func registerAzureResourceProvidersWithSubscription(client *riviera.Client) error {
   170  	var err error
   171  	providerRegistrationOnce.Do(func() {
   172  		// We register Microsoft.Compute during client initialization
   173  		providers := []string{"Microsoft.Network", "Microsoft.Cdn", "Microsoft.Storage", "Microsoft.Sql", "Microsoft.Search", "Microsoft.Resources"}
   174  
   175  		var wg sync.WaitGroup
   176  		wg.Add(len(providers))
   177  		for _, providerName := range providers {
   178  			go func(p string) {
   179  				defer wg.Done()
   180  				if innerErr := registerProviderWithSubscription(p, client); err != nil {
   181  					err = innerErr
   182  				}
   183  			}(providerName)
   184  		}
   185  		wg.Wait()
   186  	})
   187  
   188  	return err
   189  }
   190  
   191  // azureRMNormalizeLocation is a function which normalises human-readable region/location
   192  // names (e.g. "West US") to the values used and returned by the Azure API (e.g. "westus").
   193  // In state we track the API internal version as it is easier to go from the human form
   194  // to the canonical form than the other way around.
   195  func azureRMNormalizeLocation(location interface{}) string {
   196  	input := location.(string)
   197  	return strings.Replace(strings.ToLower(input), " ", "", -1)
   198  }
   199  
   200  // pollIndefinitelyAsNeeded is a terrible hack which is necessary because the Azure
   201  // Storage API (and perhaps others) can have response times way beyond the default
   202  // retry timeouts, with no apparent upper bound. This effectively causes the client
   203  // to continue polling when it reaches the configured timeout. My investigations
   204  // suggest that this is neccesary when deleting and recreating a storage account with
   205  // the same name in a short (though undetermined) time period.
   206  //
   207  // It is possible that this will give Terraform the appearance of being slow in
   208  // future: I have attempted to mitigate this by logging whenever this happens. We
   209  // may want to revisit this with configurable timeouts in the future as clearly
   210  // unbounded wait loops is not ideal. It does seem preferable to the current situation
   211  // where our polling loop will time out _with an operation in progress_, but no ID
   212  // for the resource - so the state will not know about it, and conflicts will occur
   213  // on the next run.
   214  func pollIndefinitelyAsNeeded(client autorest.Client, response *http.Response, acceptableCodes ...int) (*http.Response, error) {
   215  	var resp *http.Response
   216  	var err error
   217  
   218  	for {
   219  		resp, err = client.PollAsNeeded(response, acceptableCodes...)
   220  		if err != nil {
   221  			if resp.StatusCode != http.StatusAccepted {
   222  				log.Printf("[DEBUG] Starting new polling loop for %q", response.Request.URL.Path)
   223  				continue
   224  			}
   225  
   226  			return resp, err
   227  		}
   228  
   229  		return resp, nil
   230  	}
   231  }
   232  
   233  // armMutexKV is the instance of MutexKV for ARM resources
   234  var armMutexKV = mutexkv.NewMutexKV()
   235  
   236  func azureStateRefreshFunc(resourceURI string, client *ArmClient, command riviera.APICall) resource.StateRefreshFunc {
   237  	return func() (interface{}, string, error) {
   238  		req := client.rivieraClient.NewRequestForURI(resourceURI)
   239  		req.Command = command
   240  
   241  		res, err := req.Execute()
   242  		if err != nil {
   243  			return nil, "", fmt.Errorf("Error executing %T command in azureStateRefreshFunc", req.Command)
   244  		}
   245  
   246  		var value reflect.Value
   247  		if reflect.ValueOf(res.Parsed).Kind() == reflect.Ptr {
   248  			value = reflect.ValueOf(res.Parsed).Elem()
   249  		} else {
   250  			value = reflect.ValueOf(res.Parsed)
   251  		}
   252  
   253  		for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
   254  			tag := value.Type().Field(i).Tag // returns the tag string
   255  			tagValue := tag.Get("mapstructure")
   256  			if tagValue == "provisioningState" {
   257  				return res.Parsed, value.Field(i).Elem().String(), nil
   258  			}
   259  		}
   260  
   261  		panic(fmt.Errorf("azureStateRefreshFunc called on structure %T with no mapstructure:provisioningState tag. This is a bug", res.Parsed))
   262  	}
   263  }