github.com/nathanielks/terraform@v0.6.1-0.20170509030759-13e1a62319dc/builtin/providers/azurerm/provider.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"crypto/sha1"
     5  	"encoding/base64"
     6  	"encoding/hex"
     7  	"fmt"
     8  	"log"
     9  	"reflect"
    10  	"strings"
    11  	"sync"
    12  
    13  	"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
    14  	"github.com/hashicorp/go-multierror"
    15  	"github.com/hashicorp/terraform/helper/mutexkv"
    16  	"github.com/hashicorp/terraform/helper/resource"
    17  	"github.com/hashicorp/terraform/helper/schema"
    18  	"github.com/hashicorp/terraform/terraform"
    19  	riviera "github.com/jen20/riviera/azure"
    20  )
    21  
    22  // Provider returns a terraform.ResourceProvider.
    23  func Provider() terraform.ResourceProvider {
    24  	var p *schema.Provider
    25  	p = &schema.Provider{
    26  		Schema: map[string]*schema.Schema{
    27  			"subscription_id": {
    28  				Type:        schema.TypeString,
    29  				Required:    true,
    30  				DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
    31  			},
    32  
    33  			"client_id": {
    34  				Type:        schema.TypeString,
    35  				Required:    true,
    36  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
    37  			},
    38  
    39  			"client_secret": {
    40  				Type:        schema.TypeString,
    41  				Required:    true,
    42  				DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
    43  			},
    44  
    45  			"tenant_id": {
    46  				Type:        schema.TypeString,
    47  				Required:    true,
    48  				DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
    49  			},
    50  
    51  			"environment": {
    52  				Type:        schema.TypeString,
    53  				Required:    true,
    54  				DefaultFunc: schema.EnvDefaultFunc("ARM_ENVIRONMENT", "public"),
    55  			},
    56  
    57  			"skip_provider_registration": {
    58  				Type:        schema.TypeBool,
    59  				Optional:    true,
    60  				DefaultFunc: schema.EnvDefaultFunc("ARM_SKIP_PROVIDER_REGISTRATION", false),
    61  			},
    62  		},
    63  
    64  		DataSourcesMap: map[string]*schema.Resource{
    65  			"azurerm_client_config": dataSourceArmClientConfig(),
    66  		},
    67  
    68  		ResourcesMap: map[string]*schema.Resource{
    69  			// These resources use the Azure ARM SDK
    70  			"azurerm_availability_set":   resourceArmAvailabilitySet(),
    71  			"azurerm_cdn_endpoint":       resourceArmCdnEndpoint(),
    72  			"azurerm_cdn_profile":        resourceArmCdnProfile(),
    73  			"azurerm_container_registry": resourceArmContainerRegistry(),
    74  			"azurerm_container_service":  resourceArmContainerService(),
    75  
    76  			"azurerm_eventhub":                    resourceArmEventHub(),
    77  			"azurerm_eventhub_authorization_rule": resourceArmEventHubAuthorizationRule(),
    78  			"azurerm_eventhub_consumer_group":     resourceArmEventHubConsumerGroup(),
    79  			"azurerm_eventhub_namespace":          resourceArmEventHubNamespace(),
    80  
    81  			"azurerm_lb":                      resourceArmLoadBalancer(),
    82  			"azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(),
    83  			"azurerm_lb_nat_rule":             resourceArmLoadBalancerNatRule(),
    84  			"azurerm_lb_nat_pool":             resourceArmLoadBalancerNatPool(),
    85  			"azurerm_lb_probe":                resourceArmLoadBalancerProbe(),
    86  			"azurerm_lb_rule":                 resourceArmLoadBalancerRule(),
    87  
    88  			"azurerm_managed_disk": resourceArmManagedDisk(),
    89  
    90  			"azurerm_key_vault":                 resourceArmKeyVault(),
    91  			"azurerm_local_network_gateway":     resourceArmLocalNetworkGateway(),
    92  			"azurerm_network_interface":         resourceArmNetworkInterface(),
    93  			"azurerm_network_security_group":    resourceArmNetworkSecurityGroup(),
    94  			"azurerm_network_security_rule":     resourceArmNetworkSecurityRule(),
    95  			"azurerm_public_ip":                 resourceArmPublicIp(),
    96  			"azurerm_redis_cache":               resourceArmRedisCache(),
    97  			"azurerm_route":                     resourceArmRoute(),
    98  			"azurerm_route_table":               resourceArmRouteTable(),
    99  			"azurerm_servicebus_namespace":      resourceArmServiceBusNamespace(),
   100  			"azurerm_servicebus_subscription":   resourceArmServiceBusSubscription(),
   101  			"azurerm_servicebus_topic":          resourceArmServiceBusTopic(),
   102  			"azurerm_sql_elasticpool":           resourceArmSqlElasticPool(),
   103  			"azurerm_storage_account":           resourceArmStorageAccount(),
   104  			"azurerm_storage_blob":              resourceArmStorageBlob(),
   105  			"azurerm_storage_container":         resourceArmStorageContainer(),
   106  			"azurerm_storage_share":             resourceArmStorageShare(),
   107  			"azurerm_storage_queue":             resourceArmStorageQueue(),
   108  			"azurerm_storage_table":             resourceArmStorageTable(),
   109  			"azurerm_subnet":                    resourceArmSubnet(),
   110  			"azurerm_template_deployment":       resourceArmTemplateDeployment(),
   111  			"azurerm_traffic_manager_endpoint":  resourceArmTrafficManagerEndpoint(),
   112  			"azurerm_traffic_manager_profile":   resourceArmTrafficManagerProfile(),
   113  			"azurerm_virtual_machine_extension": resourceArmVirtualMachineExtensions(),
   114  			"azurerm_virtual_machine":           resourceArmVirtualMachine(),
   115  			"azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(),
   116  			"azurerm_virtual_network":           resourceArmVirtualNetwork(),
   117  			"azurerm_virtual_network_peering":   resourceArmVirtualNetworkPeering(),
   118  
   119  			// These resources use the Riviera SDK
   120  			"azurerm_dns_a_record":      resourceArmDnsARecord(),
   121  			"azurerm_dns_aaaa_record":   resourceArmDnsAAAARecord(),
   122  			"azurerm_dns_cname_record":  resourceArmDnsCNameRecord(),
   123  			"azurerm_dns_mx_record":     resourceArmDnsMxRecord(),
   124  			"azurerm_dns_ns_record":     resourceArmDnsNsRecord(),
   125  			"azurerm_dns_srv_record":    resourceArmDnsSrvRecord(),
   126  			"azurerm_dns_txt_record":    resourceArmDnsTxtRecord(),
   127  			"azurerm_dns_zone":          resourceArmDnsZone(),
   128  			"azurerm_resource_group":    resourceArmResourceGroup(),
   129  			"azurerm_search_service":    resourceArmSearchService(),
   130  			"azurerm_sql_database":      resourceArmSqlDatabase(),
   131  			"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
   132  			"azurerm_sql_server":        resourceArmSqlServer(),
   133  		},
   134  	}
   135  
   136  	p.ConfigureFunc = providerConfigure(p)
   137  
   138  	return p
   139  }
   140  
   141  // Config is the configuration structure used to instantiate a
   142  // new Azure management client.
   143  type Config struct {
   144  	ManagementURL string
   145  
   146  	SubscriptionID           string
   147  	ClientID                 string
   148  	ClientSecret             string
   149  	TenantID                 string
   150  	Environment              string
   151  	SkipProviderRegistration bool
   152  
   153  	validateCredentialsOnce sync.Once
   154  }
   155  
   156  func (c *Config) validate() error {
   157  	var err *multierror.Error
   158  
   159  	if c.SubscriptionID == "" {
   160  		err = multierror.Append(err, fmt.Errorf("Subscription ID must be configured for the AzureRM provider"))
   161  	}
   162  	if c.ClientID == "" {
   163  		err = multierror.Append(err, fmt.Errorf("Client ID must be configured for the AzureRM provider"))
   164  	}
   165  	if c.ClientSecret == "" {
   166  		err = multierror.Append(err, fmt.Errorf("Client Secret must be configured for the AzureRM provider"))
   167  	}
   168  	if c.TenantID == "" {
   169  		err = multierror.Append(err, fmt.Errorf("Tenant ID must be configured for the AzureRM provider"))
   170  	}
   171  	if c.Environment == "" {
   172  		err = multierror.Append(err, fmt.Errorf("Environment must be configured for the AzureRM provider"))
   173  	}
   174  
   175  	return err.ErrorOrNil()
   176  }
   177  
   178  func providerConfigure(p *schema.Provider) schema.ConfigureFunc {
   179  	return func(d *schema.ResourceData) (interface{}, error) {
   180  		config := &Config{
   181  			SubscriptionID:           d.Get("subscription_id").(string),
   182  			ClientID:                 d.Get("client_id").(string),
   183  			ClientSecret:             d.Get("client_secret").(string),
   184  			TenantID:                 d.Get("tenant_id").(string),
   185  			Environment:              d.Get("environment").(string),
   186  			SkipProviderRegistration: d.Get("skip_provider_registration").(bool),
   187  		}
   188  
   189  		if err := config.validate(); err != nil {
   190  			return nil, err
   191  		}
   192  
   193  		client, err := config.getArmClient()
   194  		if err != nil {
   195  			return nil, err
   196  		}
   197  
   198  		client.StopContext = p.StopContext()
   199  
   200  		// replaces the context between tests
   201  		p.MetaReset = func() error {
   202  			client.StopContext = p.StopContext()
   203  			return nil
   204  		}
   205  
   206  		// List all the available providers and their registration state to avoid unnecessary
   207  		// requests. This also lets us check if the provider credentials are correct.
   208  		providerList, err := client.providers.List(nil, "")
   209  		if err != nil {
   210  			return nil, fmt.Errorf("Unable to list provider registration status, it is possible that this is due to invalid "+
   211  				"credentials or the service principal does not have permission to use the Resource Manager API, Azure "+
   212  				"error: %s", err)
   213  		}
   214  
   215  		if !config.SkipProviderRegistration {
   216  			err = registerAzureResourceProvidersWithSubscription(*providerList.Value, client.providers)
   217  			if err != nil {
   218  				return nil, err
   219  			}
   220  		}
   221  
   222  		return client, nil
   223  	}
   224  }
   225  
   226  func registerProviderWithSubscription(providerName string, client resources.ProvidersClient) error {
   227  	_, err := client.Register(providerName)
   228  	if err != nil {
   229  		return fmt.Errorf("Cannot register provider %s with Azure Resource Manager: %s.", providerName, err)
   230  	}
   231  
   232  	return nil
   233  }
   234  
   235  var providerRegistrationOnce sync.Once
   236  
   237  // registerAzureResourceProvidersWithSubscription uses the providers client to register
   238  // all Azure resource providers which the Terraform provider may require (regardless of
   239  // whether they are actually used by the configuration or not). It was confirmed by Microsoft
   240  // that this is the approach their own internal tools also take.
   241  func registerAzureResourceProvidersWithSubscription(providerList []resources.Provider, client resources.ProvidersClient) error {
   242  	var err error
   243  	providerRegistrationOnce.Do(func() {
   244  		providers := map[string]struct{}{
   245  			"Microsoft.Compute":           struct{}{},
   246  			"Microsoft.Cache":             struct{}{},
   247  			"Microsoft.ContainerRegistry": struct{}{},
   248  			"Microsoft.ContainerService":  struct{}{},
   249  			"Microsoft.Network":           struct{}{},
   250  			"Microsoft.Cdn":               struct{}{},
   251  			"Microsoft.Storage":           struct{}{},
   252  			"Microsoft.Sql":               struct{}{},
   253  			"Microsoft.Search":            struct{}{},
   254  			"Microsoft.Resources":         struct{}{},
   255  			"Microsoft.ServiceBus":        struct{}{},
   256  			"Microsoft.KeyVault":          struct{}{},
   257  			"Microsoft.EventHub":          struct{}{},
   258  		}
   259  
   260  		// filter out any providers already registered
   261  		for _, p := range providerList {
   262  			if _, ok := providers[*p.Namespace]; !ok {
   263  				continue
   264  			}
   265  
   266  			if strings.ToLower(*p.RegistrationState) == "registered" {
   267  				log.Printf("[DEBUG] Skipping provider registration for namespace %s\n", *p.Namespace)
   268  				delete(providers, *p.Namespace)
   269  			}
   270  		}
   271  
   272  		var wg sync.WaitGroup
   273  		wg.Add(len(providers))
   274  		for providerName := range providers {
   275  			go func(p string) {
   276  				defer wg.Done()
   277  				log.Printf("[DEBUG] Registering provider with namespace %s\n", p)
   278  				if innerErr := registerProviderWithSubscription(p, client); err != nil {
   279  					err = innerErr
   280  				}
   281  			}(providerName)
   282  		}
   283  		wg.Wait()
   284  	})
   285  
   286  	return err
   287  }
   288  
   289  // armMutexKV is the instance of MutexKV for ARM resources
   290  var armMutexKV = mutexkv.NewMutexKV()
   291  
   292  func azureStateRefreshFunc(resourceURI string, client *ArmClient, command riviera.APICall) resource.StateRefreshFunc {
   293  	return func() (interface{}, string, error) {
   294  		req := client.rivieraClient.NewRequestForURI(resourceURI)
   295  		req.Command = command
   296  
   297  		res, err := req.Execute()
   298  		if err != nil {
   299  			return nil, "", fmt.Errorf("Error executing %T command in azureStateRefreshFunc", req.Command)
   300  		}
   301  
   302  		var value reflect.Value
   303  		if reflect.ValueOf(res.Parsed).Kind() == reflect.Ptr {
   304  			value = reflect.ValueOf(res.Parsed).Elem()
   305  		} else {
   306  			value = reflect.ValueOf(res.Parsed)
   307  		}
   308  
   309  		for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
   310  			tag := value.Type().Field(i).Tag // returns the tag string
   311  			tagValue := tag.Get("mapstructure")
   312  			if tagValue == "provisioningState" {
   313  				return res.Parsed, value.Field(i).Elem().String(), nil
   314  			}
   315  		}
   316  
   317  		panic(fmt.Errorf("azureStateRefreshFunc called on structure %T with no mapstructure:provisioningState tag. This is a bug", res.Parsed))
   318  	}
   319  }
   320  
   321  // Resource group names can be capitalised, but we store them in lowercase.
   322  // Use a custom diff function to avoid creation of new resources.
   323  func resourceAzurermResourceGroupNameDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
   324  	return strings.ToLower(old) == strings.ToLower(new)
   325  }
   326  
   327  // ignoreCaseDiffSuppressFunc is a DiffSuppressFunc from helper/schema that is
   328  // used to ignore any case-changes in a return value.
   329  func ignoreCaseDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
   330  	return strings.ToLower(old) == strings.ToLower(new)
   331  }
   332  
   333  // ignoreCaseStateFunc is a StateFunc from helper/schema that converts the
   334  // supplied value to lower before saving to state for consistency.
   335  func ignoreCaseStateFunc(val interface{}) string {
   336  	return strings.ToLower(val.(string))
   337  }
   338  
   339  func userDataStateFunc(v interface{}) string {
   340  	switch s := v.(type) {
   341  	case string:
   342  		s = base64Encode(s)
   343  		hash := sha1.Sum([]byte(s))
   344  		return hex.EncodeToString(hash[:])
   345  	default:
   346  		return ""
   347  	}
   348  }
   349  
   350  // base64Encode encodes data if the input isn't already encoded using
   351  // base64.StdEncoding.EncodeToString. If the input is already base64 encoded,
   352  // return the original input unchanged.
   353  func base64Encode(data string) string {
   354  	// Check whether the data is already Base64 encoded; don't double-encode
   355  	if isBase64Encoded(data) {
   356  		return data
   357  	}
   358  	// data has not been encoded encode and return
   359  	return base64.StdEncoding.EncodeToString([]byte(data))
   360  }
   361  
   362  func isBase64Encoded(data string) bool {
   363  	_, err := base64.StdEncoding.DecodeString(data)
   364  	return err == nil
   365  }