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