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