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