github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/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_storage_account":           resourceArmStorageAccount(),
   103  			"azurerm_storage_blob":              resourceArmStorageBlob(),
   104  			"azurerm_storage_container":         resourceArmStorageContainer(),
   105  			"azurerm_storage_share":             resourceArmStorageShare(),
   106  			"azurerm_storage_queue":             resourceArmStorageQueue(),
   107  			"azurerm_storage_table":             resourceArmStorageTable(),
   108  			"azurerm_subnet":                    resourceArmSubnet(),
   109  			"azurerm_template_deployment":       resourceArmTemplateDeployment(),
   110  			"azurerm_traffic_manager_endpoint":  resourceArmTrafficManagerEndpoint(),
   111  			"azurerm_traffic_manager_profile":   resourceArmTrafficManagerProfile(),
   112  			"azurerm_virtual_machine_extension": resourceArmVirtualMachineExtensions(),
   113  			"azurerm_virtual_machine":           resourceArmVirtualMachine(),
   114  			"azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(),
   115  			"azurerm_virtual_network":           resourceArmVirtualNetwork(),
   116  			"azurerm_virtual_network_peering":   resourceArmVirtualNetworkPeering(),
   117  
   118  			// These resources use the Riviera SDK
   119  			"azurerm_dns_a_record":      resourceArmDnsARecord(),
   120  			"azurerm_dns_aaaa_record":   resourceArmDnsAAAARecord(),
   121  			"azurerm_dns_cname_record":  resourceArmDnsCNameRecord(),
   122  			"azurerm_dns_mx_record":     resourceArmDnsMxRecord(),
   123  			"azurerm_dns_ns_record":     resourceArmDnsNsRecord(),
   124  			"azurerm_dns_srv_record":    resourceArmDnsSrvRecord(),
   125  			"azurerm_dns_txt_record":    resourceArmDnsTxtRecord(),
   126  			"azurerm_dns_zone":          resourceArmDnsZone(),
   127  			"azurerm_resource_group":    resourceArmResourceGroup(),
   128  			"azurerm_search_service":    resourceArmSearchService(),
   129  			"azurerm_sql_database":      resourceArmSqlDatabase(),
   130  			"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
   131  			"azurerm_sql_server":        resourceArmSqlServer(),
   132  		},
   133  	}
   134  
   135  	p.ConfigureFunc = providerConfigure(p)
   136  
   137  	return p
   138  }
   139  
   140  // Config is the configuration structure used to instantiate a
   141  // new Azure management client.
   142  type Config struct {
   143  	ManagementURL string
   144  
   145  	SubscriptionID           string
   146  	ClientID                 string
   147  	ClientSecret             string
   148  	TenantID                 string
   149  	Environment              string
   150  	SkipProviderRegistration bool
   151  
   152  	validateCredentialsOnce sync.Once
   153  }
   154  
   155  func (c *Config) validate() error {
   156  	var err *multierror.Error
   157  
   158  	if c.SubscriptionID == "" {
   159  		err = multierror.Append(err, fmt.Errorf("Subscription ID must be configured for the AzureRM provider"))
   160  	}
   161  	if c.ClientID == "" {
   162  		err = multierror.Append(err, fmt.Errorf("Client ID must be configured for the AzureRM provider"))
   163  	}
   164  	if c.ClientSecret == "" {
   165  		err = multierror.Append(err, fmt.Errorf("Client Secret must be configured for the AzureRM provider"))
   166  	}
   167  	if c.TenantID == "" {
   168  		err = multierror.Append(err, fmt.Errorf("Tenant ID must be configured for the AzureRM provider"))
   169  	}
   170  	if c.Environment == "" {
   171  		err = multierror.Append(err, fmt.Errorf("Environment must be configured for the AzureRM provider"))
   172  	}
   173  
   174  	return err.ErrorOrNil()
   175  }
   176  
   177  func providerConfigure(p *schema.Provider) schema.ConfigureFunc {
   178  	return func(d *schema.ResourceData) (interface{}, error) {
   179  		config := &Config{
   180  			SubscriptionID:           d.Get("subscription_id").(string),
   181  			ClientID:                 d.Get("client_id").(string),
   182  			ClientSecret:             d.Get("client_secret").(string),
   183  			TenantID:                 d.Get("tenant_id").(string),
   184  			Environment:              d.Get("environment").(string),
   185  			SkipProviderRegistration: d.Get("skip_provider_registration").(bool),
   186  		}
   187  
   188  		if err := config.validate(); err != nil {
   189  			return nil, err
   190  		}
   191  
   192  		client, err := config.getArmClient()
   193  		if err != nil {
   194  			return nil, err
   195  		}
   196  
   197  		client.StopContext = p.StopContext()
   198  
   199  		// replaces the context between tests
   200  		p.MetaReset = func() error {
   201  			client.StopContext = p.StopContext()
   202  			return nil
   203  		}
   204  
   205  		// List all the available providers and their registration state to avoid unnecessary
   206  		// requests. This also lets us check if the provider credentials are correct.
   207  		providerList, err := client.providers.List(nil, "")
   208  		if err != nil {
   209  			return nil, fmt.Errorf("Unable to list provider registration status, it is possible that this is due to invalid "+
   210  				"credentials or the service principal does not have permission to use the Resource Manager API, Azure "+
   211  				"error: %s", err)
   212  		}
   213  
   214  		if !config.SkipProviderRegistration {
   215  			err = registerAzureResourceProvidersWithSubscription(*providerList.Value, client.providers)
   216  			if err != nil {
   217  				return nil, err
   218  			}
   219  		}
   220  
   221  		return client, nil
   222  	}
   223  }
   224  
   225  func registerProviderWithSubscription(providerName string, client resources.ProvidersClient) error {
   226  	_, err := client.Register(providerName)
   227  	if err != nil {
   228  		return fmt.Errorf("Cannot register provider %s with Azure Resource Manager: %s.", providerName, err)
   229  	}
   230  
   231  	return nil
   232  }
   233  
   234  var providerRegistrationOnce sync.Once
   235  
   236  // registerAzureResourceProvidersWithSubscription uses the providers client to register
   237  // all Azure resource providers which the Terraform provider may require (regardless of
   238  // whether they are actually used by the configuration or not). It was confirmed by Microsoft
   239  // that this is the approach their own internal tools also take.
   240  func registerAzureResourceProvidersWithSubscription(providerList []resources.Provider, client resources.ProvidersClient) error {
   241  	var err error
   242  	providerRegistrationOnce.Do(func() {
   243  		providers := map[string]struct{}{
   244  			"Microsoft.Compute":           struct{}{},
   245  			"Microsoft.Cache":             struct{}{},
   246  			"Microsoft.ContainerRegistry": struct{}{},
   247  			"Microsoft.ContainerService":  struct{}{},
   248  			"Microsoft.Network":           struct{}{},
   249  			"Microsoft.Cdn":               struct{}{},
   250  			"Microsoft.Storage":           struct{}{},
   251  			"Microsoft.Sql":               struct{}{},
   252  			"Microsoft.Search":            struct{}{},
   253  			"Microsoft.Resources":         struct{}{},
   254  			"Microsoft.ServiceBus":        struct{}{},
   255  			"Microsoft.KeyVault":          struct{}{},
   256  			"Microsoft.EventHub":          struct{}{},
   257  		}
   258  
   259  		// filter out any providers already registered
   260  		for _, p := range providerList {
   261  			if _, ok := providers[*p.Namespace]; !ok {
   262  				continue
   263  			}
   264  
   265  			if strings.ToLower(*p.RegistrationState) == "registered" {
   266  				log.Printf("[DEBUG] Skipping provider registration for namespace %s\n", *p.Namespace)
   267  				delete(providers, *p.Namespace)
   268  			}
   269  		}
   270  
   271  		var wg sync.WaitGroup
   272  		wg.Add(len(providers))
   273  		for providerName := range providers {
   274  			go func(p string) {
   275  				defer wg.Done()
   276  				log.Printf("[DEBUG] Registering provider with namespace %s\n", p)
   277  				if innerErr := registerProviderWithSubscription(p, client); err != nil {
   278  					err = innerErr
   279  				}
   280  			}(providerName)
   281  		}
   282  		wg.Wait()
   283  	})
   284  
   285  	return err
   286  }
   287  
   288  // armMutexKV is the instance of MutexKV for ARM resources
   289  var armMutexKV = mutexkv.NewMutexKV()
   290  
   291  func azureStateRefreshFunc(resourceURI string, client *ArmClient, command riviera.APICall) resource.StateRefreshFunc {
   292  	return func() (interface{}, string, error) {
   293  		req := client.rivieraClient.NewRequestForURI(resourceURI)
   294  		req.Command = command
   295  
   296  		res, err := req.Execute()
   297  		if err != nil {
   298  			return nil, "", fmt.Errorf("Error executing %T command in azureStateRefreshFunc", req.Command)
   299  		}
   300  
   301  		var value reflect.Value
   302  		if reflect.ValueOf(res.Parsed).Kind() == reflect.Ptr {
   303  			value = reflect.ValueOf(res.Parsed).Elem()
   304  		} else {
   305  			value = reflect.ValueOf(res.Parsed)
   306  		}
   307  
   308  		for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
   309  			tag := value.Type().Field(i).Tag // returns the tag string
   310  			tagValue := tag.Get("mapstructure")
   311  			if tagValue == "provisioningState" {
   312  				return res.Parsed, value.Field(i).Elem().String(), nil
   313  			}
   314  		}
   315  
   316  		panic(fmt.Errorf("azureStateRefreshFunc called on structure %T with no mapstructure:provisioningState tag. This is a bug", res.Parsed))
   317  	}
   318  }
   319  
   320  // Resource group names can be capitalised, but we store them in lowercase.
   321  // Use a custom diff function to avoid creation of new resources.
   322  func resourceAzurermResourceGroupNameDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
   323  	return strings.ToLower(old) == strings.ToLower(new)
   324  }
   325  
   326  // ignoreCaseDiffSuppressFunc is a DiffSuppressFunc from helper/schema that is
   327  // used to ignore any case-changes in a return value.
   328  func ignoreCaseDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
   329  	return strings.ToLower(old) == strings.ToLower(new)
   330  }
   331  
   332  // ignoreCaseStateFunc is a StateFunc from helper/schema that converts the
   333  // supplied value to lower before saving to state for consistency.
   334  func ignoreCaseStateFunc(val interface{}) string {
   335  	return strings.ToLower(val.(string))
   336  }
   337  
   338  func userDataStateFunc(v interface{}) string {
   339  	switch s := v.(type) {
   340  	case string:
   341  		s = base64Encode(s)
   342  		hash := sha1.Sum([]byte(s))
   343  		return hex.EncodeToString(hash[:])
   344  	default:
   345  		return ""
   346  	}
   347  }
   348  
   349  // base64Encode encodes data if the input isn't already encoded using
   350  // base64.StdEncoding.EncodeToString. If the input is already base64 encoded,
   351  // return the original input unchanged.
   352  func base64Encode(data string) string {
   353  	// Check whether the data is already Base64 encoded; don't double-encode
   354  	if isBase64Encoded(data) {
   355  		return data
   356  	}
   357  	// data has not been encoded encode and return
   358  	return base64.StdEncoding.EncodeToString([]byte(data))
   359  }
   360  
   361  func isBase64Encoded(data string) bool {
   362  	_, err := base64.StdEncoding.DecodeString(data)
   363  	return err == nil
   364  }