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