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