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

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"strings"
     7  
     8  	"sync"
     9  
    10  	"github.com/hashicorp/go-multierror"
    11  	"github.com/hashicorp/terraform/helper/mutexkv"
    12  	"github.com/hashicorp/terraform/helper/resource"
    13  	"github.com/hashicorp/terraform/helper/schema"
    14  	"github.com/hashicorp/terraform/terraform"
    15  	riviera "github.com/jen20/riviera/azure"
    16  )
    17  
    18  // Provider returns a terraform.ResourceProvider.
    19  func Provider() terraform.ResourceProvider {
    20  	return &schema.Provider{
    21  		Schema: map[string]*schema.Schema{
    22  			"subscription_id": {
    23  				Type:        schema.TypeString,
    24  				Required:    true,
    25  				DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
    26  			},
    27  
    28  			"client_id": {
    29  				Type:        schema.TypeString,
    30  				Required:    true,
    31  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
    32  			},
    33  
    34  			"client_secret": {
    35  				Type:        schema.TypeString,
    36  				Required:    true,
    37  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
    38  			},
    39  
    40  			"tenant_id": {
    41  				Type:        schema.TypeString,
    42  				Required:    true,
    43  				DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
    44  			},
    45  		},
    46  
    47  		DataSourcesMap: map[string]*schema.Resource{
    48  			"azurerm_client_config": dataSourceArmClientConfig(),
    49  		},
    50  
    51  		ResourcesMap: map[string]*schema.Resource{
    52  			// These resources use the Azure ARM SDK
    53  			"azurerm_availability_set": resourceArmAvailabilitySet(),
    54  			"azurerm_cdn_endpoint":     resourceArmCdnEndpoint(),
    55  			"azurerm_cdn_profile":      resourceArmCdnProfile(),
    56  
    57  			"azurerm_eventhub_namespace": resourceArmEventHubNamespace(),
    58  
    59  			"azurerm_lb":                      resourceArmLoadBalancer(),
    60  			"azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(),
    61  			"azurerm_lb_nat_rule":             resourceArmLoadBalancerNatRule(),
    62  			"azurerm_lb_nat_pool":             resourceArmLoadBalancerNatPool(),
    63  			"azurerm_lb_probe":                resourceArmLoadBalancerProbe(),
    64  			"azurerm_lb_rule":                 resourceArmLoadBalancerRule(),
    65  
    66  			"azurerm_key_vault":                 resourceArmKeyVault(),
    67  			"azurerm_local_network_gateway":     resourceArmLocalNetworkGateway(),
    68  			"azurerm_network_interface":         resourceArmNetworkInterface(),
    69  			"azurerm_network_security_group":    resourceArmNetworkSecurityGroup(),
    70  			"azurerm_network_security_rule":     resourceArmNetworkSecurityRule(),
    71  			"azurerm_public_ip":                 resourceArmPublicIp(),
    72  			"azurerm_route":                     resourceArmRoute(),
    73  			"azurerm_route_table":               resourceArmRouteTable(),
    74  			"azurerm_servicebus_namespace":      resourceArmServiceBusNamespace(),
    75  			"azurerm_servicebus_subscription":   resourceArmServiceBusSubscription(),
    76  			"azurerm_servicebus_topic":          resourceArmServiceBusTopic(),
    77  			"azurerm_storage_account":           resourceArmStorageAccount(),
    78  			"azurerm_storage_blob":              resourceArmStorageBlob(),
    79  			"azurerm_storage_container":         resourceArmStorageContainer(),
    80  			"azurerm_storage_share":             resourceArmStorageShare(),
    81  			"azurerm_storage_queue":             resourceArmStorageQueue(),
    82  			"azurerm_storage_table":             resourceArmStorageTable(),
    83  			"azurerm_subnet":                    resourceArmSubnet(),
    84  			"azurerm_template_deployment":       resourceArmTemplateDeployment(),
    85  			"azurerm_traffic_manager_endpoint":  resourceArmTrafficManagerEndpoint(),
    86  			"azurerm_traffic_manager_profile":   resourceArmTrafficManagerProfile(),
    87  			"azurerm_virtual_machine":           resourceArmVirtualMachine(),
    88  			"azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(),
    89  			"azurerm_virtual_network":           resourceArmVirtualNetwork(),
    90  			"azurerm_virtual_network_peering":   resourceArmVirtualNetworkPeering(),
    91  
    92  			// These resources use the Riviera SDK
    93  			"azurerm_dns_a_record":      resourceArmDnsARecord(),
    94  			"azurerm_dns_aaaa_record":   resourceArmDnsAAAARecord(),
    95  			"azurerm_dns_cname_record":  resourceArmDnsCNameRecord(),
    96  			"azurerm_dns_mx_record":     resourceArmDnsMxRecord(),
    97  			"azurerm_dns_ns_record":     resourceArmDnsNsRecord(),
    98  			"azurerm_dns_srv_record":    resourceArmDnsSrvRecord(),
    99  			"azurerm_dns_txt_record":    resourceArmDnsTxtRecord(),
   100  			"azurerm_dns_zone":          resourceArmDnsZone(),
   101  			"azurerm_resource_group":    resourceArmResourceGroup(),
   102  			"azurerm_search_service":    resourceArmSearchService(),
   103  			"azurerm_sql_database":      resourceArmSqlDatabase(),
   104  			"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
   105  			"azurerm_sql_server":        resourceArmSqlServer(),
   106  		},
   107  		ConfigureFunc: providerConfigure,
   108  	}
   109  }
   110  
   111  // Config is the configuration structure used to instantiate a
   112  // new Azure management client.
   113  type Config struct {
   114  	ManagementURL string
   115  
   116  	SubscriptionID string
   117  	ClientID       string
   118  	ClientSecret   string
   119  	TenantID       string
   120  
   121  	validateCredentialsOnce sync.Once
   122  }
   123  
   124  func (c *Config) validate() error {
   125  	var err *multierror.Error
   126  
   127  	if c.SubscriptionID == "" {
   128  		err = multierror.Append(err, fmt.Errorf("Subscription ID must be configured for the AzureRM provider"))
   129  	}
   130  	if c.ClientID == "" {
   131  		err = multierror.Append(err, fmt.Errorf("Client ID must be configured for the AzureRM provider"))
   132  	}
   133  	if c.ClientSecret == "" {
   134  		err = multierror.Append(err, fmt.Errorf("Client Secret must be configured for the AzureRM provider"))
   135  	}
   136  	if c.TenantID == "" {
   137  		err = multierror.Append(err, fmt.Errorf("Tenant ID must be configured for the AzureRM provider"))
   138  	}
   139  
   140  	return err.ErrorOrNil()
   141  }
   142  
   143  func providerConfigure(d *schema.ResourceData) (interface{}, error) {
   144  	config := &Config{
   145  		SubscriptionID: d.Get("subscription_id").(string),
   146  		ClientID:       d.Get("client_id").(string),
   147  		ClientSecret:   d.Get("client_secret").(string),
   148  		TenantID:       d.Get("tenant_id").(string),
   149  	}
   150  
   151  	if err := config.validate(); err != nil {
   152  		return nil, err
   153  	}
   154  
   155  	client, err := config.getArmClient()
   156  	if err != nil {
   157  		return nil, err
   158  	}
   159  
   160  	err = registerAzureResourceProvidersWithSubscription(client.rivieraClient)
   161  	if err != nil {
   162  		return nil, err
   163  	}
   164  
   165  	return client, nil
   166  }
   167  
   168  func registerProviderWithSubscription(providerName string, client *riviera.Client) error {
   169  	request := client.NewRequest()
   170  	request.Command = riviera.RegisterResourceProvider{
   171  		Namespace: providerName,
   172  	}
   173  
   174  	response, err := request.Execute()
   175  	if err != nil {
   176  		return fmt.Errorf("Cannot request provider registration for Azure Resource Manager: %s.", err)
   177  	}
   178  
   179  	if !response.IsSuccessful() {
   180  		return fmt.Errorf("Credentials for accessing the Azure Resource Manager API are likely " +
   181  			"to be incorrect, or\n  the service principal does not have permission to use " +
   182  			"the Azure Service Management\n  API.")
   183  	}
   184  
   185  	return nil
   186  }
   187  
   188  var providerRegistrationOnce sync.Once
   189  
   190  // registerAzureResourceProvidersWithSubscription uses the providers client to register
   191  // all Azure resource providers which the Terraform provider may require (regardless of
   192  // whether they are actually used by the configuration or not). It was confirmed by Microsoft
   193  // that this is the approach their own internal tools also take.
   194  func registerAzureResourceProvidersWithSubscription(client *riviera.Client) error {
   195  	var err error
   196  	providerRegistrationOnce.Do(func() {
   197  		// We register Microsoft.Compute during client initialization
   198  		providers := []string{"Microsoft.Network", "Microsoft.Cdn", "Microsoft.Storage", "Microsoft.Sql", "Microsoft.Search", "Microsoft.Resources", "Microsoft.ServiceBus", "Microsoft.KeyVault", "Microsoft.EventHub"}
   199  
   200  		var wg sync.WaitGroup
   201  		wg.Add(len(providers))
   202  		for _, providerName := range providers {
   203  			go func(p string) {
   204  				defer wg.Done()
   205  				if innerErr := registerProviderWithSubscription(p, client); err != nil {
   206  					err = innerErr
   207  				}
   208  			}(providerName)
   209  		}
   210  		wg.Wait()
   211  	})
   212  
   213  	return err
   214  }
   215  
   216  // azureRMNormalizeLocation is a function which normalises human-readable region/location
   217  // names (e.g. "West US") to the values used and returned by the Azure API (e.g. "westus").
   218  // In state we track the API internal version as it is easier to go from the human form
   219  // to the canonical form than the other way around.
   220  func azureRMNormalizeLocation(location interface{}) string {
   221  	input := location.(string)
   222  	return strings.Replace(strings.ToLower(input), " ", "", -1)
   223  }
   224  
   225  // armMutexKV is the instance of MutexKV for ARM resources
   226  var armMutexKV = mutexkv.NewMutexKV()
   227  
   228  func azureStateRefreshFunc(resourceURI string, client *ArmClient, command riviera.APICall) resource.StateRefreshFunc {
   229  	return func() (interface{}, string, error) {
   230  		req := client.rivieraClient.NewRequestForURI(resourceURI)
   231  		req.Command = command
   232  
   233  		res, err := req.Execute()
   234  		if err != nil {
   235  			return nil, "", fmt.Errorf("Error executing %T command in azureStateRefreshFunc", req.Command)
   236  		}
   237  
   238  		var value reflect.Value
   239  		if reflect.ValueOf(res.Parsed).Kind() == reflect.Ptr {
   240  			value = reflect.ValueOf(res.Parsed).Elem()
   241  		} else {
   242  			value = reflect.ValueOf(res.Parsed)
   243  		}
   244  
   245  		for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
   246  			tag := value.Type().Field(i).Tag // returns the tag string
   247  			tagValue := tag.Get("mapstructure")
   248  			if tagValue == "provisioningState" {
   249  				return res.Parsed, value.Field(i).Elem().String(), nil
   250  			}
   251  		}
   252  
   253  		panic(fmt.Errorf("azureStateRefreshFunc called on structure %T with no mapstructure:provisioningState tag. This is a bug", res.Parsed))
   254  	}
   255  }
   256  
   257  // Resource group names can be capitalised, but we store them in lowercase.
   258  // Use a custom diff function to avoid creation of new resources.
   259  func resourceAzurermResourceGroupNameDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
   260  	return strings.ToLower(old) == strings.ToLower(new)
   261  }