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