-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
provider.go
510 lines (423 loc) · 17.8 KB
/
provider.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package provider
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
"github.com/hashicorp/go-azure-sdk/sdk/auth"
"github.com/hashicorp/go-azure-sdk/sdk/environments"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/resourceproviders"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)
func AzureProvider() *schema.Provider {
return azureProvider(false)
}
func TestAzureProvider() *schema.Provider {
return azureProvider(true)
}
func ValidatePartnerID(i interface{}, k string) ([]string, []error) {
// ValidatePartnerID checks if partner_id is any of the following:
// * a valid UUID - will add "pid-" prefix to the ID if it is not already present
// * a valid UUID prefixed with "pid-"
// * a valid UUID prefixed with "pid-" and suffixed with "-partnercenter"
v, ok := i.(string)
if !ok {
return nil, []error{fmt.Errorf("expected type of %q to be string", k)}
}
if v == "" {
return nil, nil
}
// Check for pid=<guid>-partnercenter format
if strings.HasPrefix(v, "pid-") && strings.HasSuffix(v, "-partnercenter") {
g := strings.TrimPrefix(v, "pid-")
g = strings.TrimSuffix(g, "-partnercenter")
if _, err := validation.IsUUID(g, ""); err != nil {
return nil, []error{fmt.Errorf("expected %q to contain a valid UUID", v)}
}
logEntry("[DEBUG] %q partner_id matches pid-<GUID>-partnercenter...", v)
return nil, nil
}
// Check for pid=<guid> (without the -partnercenter suffix)
if strings.HasPrefix(v, "pid-") && !strings.HasSuffix(v, "-partnercenter") {
g := strings.TrimPrefix(v, "pid-")
if _, err := validation.IsUUID(g, ""); err != nil {
return nil, []error{fmt.Errorf("expected %q to be a valid UUID", k)}
}
logEntry("[DEBUG] %q partner_id matches pid-<GUID>...", v)
return nil, nil
}
// Check for straight UUID
if _, err := validation.IsUUID(v, ""); err != nil {
return nil, []error{fmt.Errorf("expected %q to be a valid UUID", k)}
} else {
logEntry("[DEBUG] %q partner_id is an un-prefixed UUID...", v)
return nil, nil
}
}
func azureProvider(supportLegacyTestSuite bool) *schema.Provider {
dataSources := make(map[string]*schema.Resource)
resources := make(map[string]*schema.Resource)
// first handle the typed services
for _, service := range SupportedTypedServices() {
logEntry("[DEBUG] Registering Data Sources for %q..", service.Name())
for _, ds := range service.DataSources() {
key := ds.ResourceType()
if existing := dataSources[key]; existing != nil {
panic(fmt.Sprintf("An existing Data Source exists for %q", key))
}
wrapper := sdk.NewDataSourceWrapper(ds)
dataSource, err := wrapper.DataSource()
if err != nil {
panic(fmt.Errorf("creating Wrapper for Data Source %q: %+v", key, err))
}
dataSources[key] = dataSource
}
logEntry("[DEBUG] Registering Resources for %q..", service.Name())
for _, r := range service.Resources() {
key := r.ResourceType()
if existing := resources[key]; existing != nil {
panic(fmt.Sprintf("An existing Resource exists for %q", key))
}
wrapper := sdk.NewResourceWrapper(r)
resource, err := wrapper.Resource()
if err != nil {
panic(fmt.Errorf("creating Wrapper for Resource %q: %+v", key, err))
}
resources[key] = resource
}
}
// then handle the untyped services
for _, service := range SupportedUntypedServices() {
logEntry("[DEBUG] Registering Data Sources for %q..", service.Name())
for k, v := range service.SupportedDataSources() {
if existing := dataSources[k]; existing != nil {
panic(fmt.Sprintf("An existing Data Source exists for %q", k))
}
dataSources[k] = v
}
logEntry("[DEBUG] Registering Resources for %q..", service.Name())
for k, v := range service.SupportedResources() {
if existing := resources[k]; existing != nil {
panic(fmt.Sprintf("An existing Resource exists for %q", k))
}
resources[k] = v
}
}
p := &schema.Provider{
Schema: map[string]*schema.Schema{
"subscription_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
Description: "The Subscription ID which should be used.",
},
"client_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
Description: "The Client ID which should be used.",
},
"client_id_file_path": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID_FILE_PATH", ""),
Description: "The path to a file containing the Client ID which should be used.",
},
"tenant_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
Description: "The Tenant ID which should be used.",
},
"auxiliary_tenant_ids": {
Type: schema.TypeList,
Optional: true,
MaxItems: 3,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"environment": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_ENVIRONMENT", "public"),
Description: "The Cloud Environment which should be used. Possible values are public, usgovernment, and china. Defaults to public. Not used and should not be specified when `metadata_host` is specified.",
},
"metadata_host": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_METADATA_HOSTNAME", ""),
Description: "The Hostname which should be used for the Azure Metadata Service.",
},
// Client Certificate specific fields
"client_certificate": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_CERTIFICATE", ""),
Description: "Base64 encoded PKCS#12 certificate bundle to use when authenticating as a Service Principal using a Client Certificate",
},
"client_certificate_path": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_CERTIFICATE_PATH", ""),
Description: "The path to the Client Certificate associated with the Service Principal for use when authenticating as a Service Principal using a Client Certificate.",
},
"client_certificate_password": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_CERTIFICATE_PASSWORD", ""),
Description: "The password associated with the Client Certificate. For use when authenticating as a Service Principal using a Client Certificate",
},
// Client Secret specific fields
"client_secret": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
Description: "The Client Secret which should be used. For use When authenticating as a Service Principal using a Client Secret.",
},
"client_secret_file_path": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET_FILE_PATH", ""),
Description: "The path to a file containing the Client Secret which should be used. For use When authenticating as a Service Principal using a Client Secret.",
},
// OIDC specifc fields
"oidc_request_token": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{"ARM_OIDC_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"}, ""),
Description: "The bearer token for the request to the OIDC provider. For use when authenticating as a Service Principal using OpenID Connect.",
},
"oidc_request_url": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{"ARM_OIDC_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_URL"}, ""),
Description: "The URL for the OIDC provider from which to request an ID token. For use when authenticating as a Service Principal using OpenID Connect.",
},
"oidc_token": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_OIDC_TOKEN", ""),
Description: "The OIDC ID token for use when authenticating as a Service Principal using OpenID Connect.",
},
"oidc_token_file_path": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_OIDC_TOKEN_FILE_PATH", ""),
Description: "The path to a file containing an OIDC ID token for use when authenticating as a Service Principal using OpenID Connect.",
},
"use_oidc": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_USE_OIDC", false),
Description: "Allow OpenID Connect to be used for authentication",
},
// Managed Service Identity specific fields
"use_msi": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_USE_MSI", false),
Description: "Allow Managed Service Identity to be used for Authentication.",
},
"msi_endpoint": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_MSI_ENDPOINT", ""),
Description: "The path to a custom endpoint for Managed Service Identity - in most circumstances this should be detected automatically. ",
},
// Azure CLI specific fields
"use_cli": {
Type: schema.TypeBool,
Optional: true,
Default: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_USE_CLI", true),
Description: "Allow Azure CLI to be used for Authentication.",
},
// Azure AKS Workload Identity fields
"use_aks_workload_identity": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_USE_AKS_WORKLOAD_IDENTITY", false),
Description: "Allow Azure AKS Workload Identity to be used for Authentication.",
},
// Managed Tracking GUID for User-agent
"partner_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.Any(ValidatePartnerID, validation.StringIsEmpty),
DefaultFunc: schema.EnvDefaultFunc("ARM_PARTNER_ID", ""),
Description: "A GUID/UUID that is registered with Microsoft to facilitate partner resource usage attribution.",
},
"disable_correlation_request_id": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_DISABLE_CORRELATION_REQUEST_ID", false),
Description: "This will disable the x-ms-correlation-request-id header.",
},
"disable_terraform_partner_id": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_DISABLE_TERRAFORM_PARTNER_ID", false),
Description: "This will disable the Terraform Partner ID which is used if a custom `partner_id` isn't specified.",
},
"features": schemaFeatures(supportLegacyTestSuite),
// Advanced feature flags
"skip_provider_registration": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_SKIP_PROVIDER_REGISTRATION", false),
Description: "Should the AzureRM Provider skip registering all of the Resource Providers that it supports, if they're not already registered?",
},
"storage_use_azuread": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_STORAGE_USE_AZUREAD", false),
Description: "Should the AzureRM Provider use AzureAD to access the Storage Data Plane API's?",
},
},
DataSourcesMap: dataSources,
ResourcesMap: resources,
}
p.ConfigureContextFunc = providerConfigure(p)
return p
}
func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc {
return func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {
var auxTenants []string
if v, ok := d.Get("auxiliary_tenant_ids").([]interface{}); ok && len(v) > 0 {
auxTenants = *utils.ExpandStringSlice(v)
} else if v := os.Getenv("ARM_AUXILIARY_TENANT_IDS"); v != "" {
auxTenants = strings.Split(v, ";")
}
if len(auxTenants) > 3 {
return nil, diag.Errorf("the provider only supports up to 3 auxiliary tenant IDs")
}
var clientCertificateData []byte
if encodedCert := d.Get("client_certificate").(string); encodedCert != "" {
var err error
clientCertificateData, err = decodeCertificate(encodedCert)
if err != nil {
return nil, diag.FromErr(err)
}
}
oidcToken, err := getOidcToken(d)
if err != nil {
return nil, diag.FromErr(err)
}
clientSecret, err := getClientSecret(d)
if err != nil {
return nil, diag.FromErr(err)
}
clientId, err := getClientId(d)
if err != nil {
return nil, diag.FromErr(err)
}
tenantId, err := getTenantId(d)
if err != nil {
return nil, diag.FromErr(err)
}
var (
env *environments.Environment
envName = d.Get("environment").(string)
metadataHost = d.Get("metadata_host").(string)
)
if metadataHost != "" {
logEntry("[DEBUG] Configuring cloud environment from Metadata Service at %q", metadataHost)
if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost)); err != nil {
return nil, diag.FromErr(err)
}
} else {
logEntry("[DEBUG] Configuring built-in cloud environment by name: %q", envName)
if env, err = environments.FromName(envName); err != nil {
return nil, diag.FromErr(err)
}
}
var (
enableAzureCli = d.Get("use_cli").(bool)
enableManagedIdentity = d.Get("use_msi").(bool)
enableOidc = d.Get("use_oidc").(bool) || d.Get("use_aks_workload_identity").(bool)
)
authConfig := &auth.Credentials{
Environment: *env,
ClientID: *clientId,
TenantID: *tenantId,
AuxiliaryTenantIDs: auxTenants,
ClientCertificateData: clientCertificateData,
ClientCertificatePath: d.Get("client_certificate_path").(string),
ClientCertificatePassword: d.Get("client_certificate_password").(string),
ClientSecret: *clientSecret,
OIDCAssertionToken: *oidcToken,
GitHubOIDCTokenRequestURL: d.Get("oidc_request_url").(string),
GitHubOIDCTokenRequestToken: d.Get("oidc_request_token").(string),
CustomManagedIdentityEndpoint: d.Get("msi_endpoint").(string),
EnableAuthenticatingUsingClientCertificate: true,
EnableAuthenticatingUsingClientSecret: true,
EnableAuthenticatingUsingAzureCLI: enableAzureCli,
EnableAuthenticatingUsingManagedIdentity: enableManagedIdentity,
EnableAuthenticationUsingOIDC: enableOidc,
EnableAuthenticationUsingGitHubOIDC: enableOidc,
}
return buildClient(ctx, p, d, authConfig)
}
}
func buildClient(ctx context.Context, p *schema.Provider, d *schema.ResourceData, authConfig *auth.Credentials) (*clients.Client, diag.Diagnostics) {
skipProviderRegistration := d.Get("skip_provider_registration").(bool)
clientBuilder := clients.ClientBuilder{
AuthConfig: authConfig,
DisableCorrelationRequestID: d.Get("disable_correlation_request_id").(bool),
DisableTerraformPartnerID: d.Get("disable_terraform_partner_id").(bool),
Features: expandFeatures(d.Get("features").([]interface{})),
MetadataHost: d.Get("metadata_host").(string),
PartnerID: d.Get("partner_id").(string),
SkipProviderRegistration: skipProviderRegistration,
StorageUseAzureAD: d.Get("storage_use_azuread").(bool),
SubscriptionID: d.Get("subscription_id").(string),
TerraformVersion: p.TerraformVersion,
// this field is intentionally not exposed in the provider block, since it's only used for
// platform level tracing
CustomCorrelationRequestID: os.Getenv("ARM_CORRELATION_REQUEST_ID"),
}
//lint:ignore SA1019 SDKv2 migration - staticcheck's own linter directives are currently being ignored under golanci-lint
stopCtx, ok := schema.StopContext(ctx) //nolint:staticcheck
if !ok {
stopCtx = ctx
}
client, err := clients.Build(stopCtx, clientBuilder)
if err != nil {
return nil, diag.FromErr(err)
}
client.StopContext = stopCtx
if !skipProviderRegistration {
subscriptionId := commonids.NewSubscriptionID(client.Account.SubscriptionId)
requiredResourceProviders := resourceproviders.Required()
ctx2, cancel := context.WithTimeout(ctx, 30*time.Minute)
defer cancel()
if err := resourceproviders.EnsureRegistered(ctx2, client.Resource.ResourceProvidersClient, subscriptionId, requiredResourceProviders); err != nil {
return nil, diag.Errorf(resourceProviderRegistrationErrorFmt, err)
}
}
return client, nil
}
const resourceProviderRegistrationErrorFmt = `Error ensuring Resource Providers are registered.
Terraform automatically attempts to register the Resource Providers it supports to
ensure it's able to provision resources.
If you don't have permission to register Resource Providers you may wish to use the
"skip_provider_registration" flag in the Provider block to disable this functionality.
Please note that if you opt out of Resource Provider Registration and Terraform tries
to provision a resource from a Resource Provider which is unregistered, then the errors
may appear misleading - for example:
> API version 2019-XX-XX was not found for Microsoft.Foo
Could indicate either that the Resource Provider "Microsoft.Foo" requires registration,
but this could also indicate that this Azure Region doesn't support this API version.
More information on the "skip_provider_registration" flag can be found here:
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs#skip_provider_registration
Original Error: %s`