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