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