-
Notifications
You must be signed in to change notification settings - Fork 549
/
Copy pathresource_aws_secret_backend.go
516 lines (460 loc) · 16.8 KB
/
resource_aws_secret_backend.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
511
512
513
514
515
516
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package vault
import (
"context"
"fmt"
"log"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/terraform-provider-vault/internal/consts"
"github.com/hashicorp/terraform-provider-vault/internal/provider"
"github.com/hashicorp/terraform-provider-vault/util"
"github.com/hashicorp/terraform-provider-vault/util/mountutil"
)
var awsSecretFields = []string{
consts.FieldIAMEndpoint,
consts.FieldSTSEndpoint,
consts.FieldUsernameTemplate,
}
func awsSecretBackendResource() *schema.Resource {
return provider.MustAddMountMigrationSchema(&schema.Resource{
CreateContext: awsSecretBackendCreate,
ReadContext: provider.ReadContextWrapper(awsSecretBackendRead),
UpdateContext: awsSecretBackendUpdate,
DeleteContext: awsSecretBackendDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
CustomizeDiff: getMountCustomizeDiffFunc(consts.FieldPath),
Schema: map[string]*schema.Schema{
consts.FieldPath: {
Type: schema.TypeString,
Optional: true,
Default: "aws",
Description: "Path to mount the backend at.",
ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) {
value := v.(string)
if strings.HasSuffix(value, "/") {
errs = append(errs, fmt.Errorf("path cannot end in '/'"))
}
return
},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return old+"/" == new || new+"/" == old
},
},
consts.FieldDescription: {
Type: schema.TypeString,
Optional: true,
Description: "Human-friendly description of the mount for the backend.",
},
consts.FieldDefaultLeaseTTL: {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Default lease duration for secrets in seconds",
},
consts.FieldMaxLeaseTTL: {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Maximum possible lease duration for secrets in seconds",
},
consts.FieldAccessKey: {
Type: schema.TypeString,
Optional: true,
Description: "The AWS Access Key ID to use when generating new credentials.",
Sensitive: true,
},
consts.FieldSecretKey: {
Type: schema.TypeString,
Optional: true,
Description: "The AWS Secret Access Key to use when generating new credentials.",
Sensitive: true,
},
consts.FieldRegion: {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The AWS region to make API calls against. Defaults to us-east-1.",
},
consts.FieldIAMEndpoint: {
Type: schema.TypeString,
Optional: true,
Description: "Specifies a custom HTTP IAM endpoint to use.",
},
consts.FieldSTSEndpoint: {
Type: schema.TypeString,
Optional: true,
Description: "Specifies a custom HTTP STS endpoint to use.",
},
consts.FieldSTSRegion: {
Type: schema.TypeString,
Optional: true,
Description: "Specifies a custom STS region to use.",
},
consts.FieldSTSFallbackEndpoints: {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Description: "Specifies a list of custom STS fallback endpoints to use (in order).",
},
consts.FieldSTSFallbackRegions: {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Description: "Specifies a list of custom STS fallback regions to use (in order).",
},
consts.FieldUsernameTemplate: {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Template describing how dynamic usernames are generated.",
},
consts.FieldLocal: {
Type: schema.TypeBool,
ForceNew: true,
Optional: true,
Default: false,
Description: "Specifies if the secret backend is local only",
},
consts.FieldRoleArn: {
Type: schema.TypeString,
Optional: true,
Description: "Role ARN to assume for plugin identity token federation.",
},
consts.FieldIdentityTokenAudience: {
Type: schema.TypeString,
Optional: true,
Description: "The audience claim value.",
},
consts.FieldIdentityTokenKey: {
Type: schema.TypeString,
Optional: true,
Description: "The key to use for signing identity tokens.",
},
consts.FieldIdentityTokenTTL: {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The TTL of generated identity tokens in seconds.",
},
},
}, false)
}
func getMountCustomizeDiffFunc(field string) schema.CustomizeDiffFunc {
return func(ctx context.Context, diff *schema.ResourceDiff, meta interface{}) error {
if !diff.HasChange(field) {
return nil
}
o, _ := diff.GetChange(field)
if o == "" {
return nil
}
// Mount Migration is only available for versions >= 1.10
remountSupported := provider.IsAPISupported(meta, provider.VaultVersion110)
disable := diff.Get(consts.FieldDisableRemount).(bool)
if remountSupported && !disable {
return nil
}
// Mount migration not available
// Destroy and recreate resource
return diff.ForceNew(field)
}
}
func awsSecretBackendCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
useAPIVer119 := provider.IsAPISupported(meta, provider.VaultVersion119)
useAPIVer116 := provider.IsAPISupported(meta, provider.VaultVersion116) && provider.IsEnterpriseSupported(meta)
client, e := provider.GetClient(d, meta)
if e != nil {
return diag.FromErr(e)
}
path := d.Get(consts.FieldPath).(string)
description := d.Get(consts.FieldDescription).(string)
defaultTTL := d.Get(consts.FieldDefaultLeaseTTL).(int)
maxTTL := d.Get(consts.FieldMaxLeaseTTL).(int)
accessKey := d.Get(consts.FieldAccessKey).(string)
secretKey := d.Get(consts.FieldSecretKey).(string)
region := d.Get(consts.FieldRegion).(string)
local := d.Get(consts.FieldLocal).(bool)
d.Partial(true)
log.Printf("[DEBUG] Mounting AWS backend at %q", path)
mountConfig := api.MountConfigInput{
DefaultLeaseTTL: fmt.Sprintf("%ds", defaultTTL),
MaxLeaseTTL: fmt.Sprintf("%ds", maxTTL),
}
if useAPIVer116 {
identityTokenKey := d.Get(consts.FieldIdentityTokenKey).(string)
if identityTokenKey != "" {
mountConfig.IdentityTokenKey = identityTokenKey
}
}
err := client.Sys().MountWithContext(ctx, path, &api.MountInput{
Type: consts.MountTypeAWS,
Description: description,
Local: local,
Config: mountConfig,
})
if err != nil {
return diag.Errorf("error mounting to %q: %s", path, err)
}
log.Printf("[DEBUG] Mounted AWS backend at %q", path)
d.SetId(path)
log.Printf("[DEBUG] Writing root credentials to %q", path+"/config/root")
data := map[string]interface{}{
consts.FieldAccessKey: accessKey,
consts.FieldSecretKey: secretKey,
}
for _, k := range awsSecretFields {
if v, ok := d.GetOk(k); ok {
data[k] = v.(string)
}
}
if useAPIVer119 {
if v, ok := d.GetOk(consts.FieldSTSFallbackEndpoints); ok {
data[consts.FieldSTSFallbackEndpoints] = util.ToStringArray(v.([]interface{}))
}
if v, ok := d.GetOk(consts.FieldSTSFallbackRegions); ok {
data[consts.FieldSTSFallbackRegions] = util.ToStringArray(v.([]interface{}))
}
if v, ok := d.GetOk(consts.FieldSTSRegion); ok {
data[consts.FieldSTSRegion] = v.(string)
}
}
if useAPIVer116 {
if v, ok := d.GetOk(consts.FieldIdentityTokenAudience); ok && v != "" {
data[consts.FieldIdentityTokenAudience] = v.(string)
}
if v, ok := d.GetOk(consts.FieldRoleArn); ok && v != "" {
data[consts.FieldRoleArn] = v.(string)
}
if v, ok := d.GetOk(consts.FieldIdentityTokenTTL); ok && v != 0 {
data[consts.FieldIdentityTokenTTL] = v.(int)
}
}
if region != "" {
data[consts.FieldRegion] = region
}
_, err = client.Logical().WriteWithContext(ctx, path+"/config/root", data)
if err != nil {
return diag.Errorf("error configuring root credentials for %q: %s", path, err)
}
log.Printf("[DEBUG] Wrote root credentials to %q", path+"/config/root")
if region == "" {
d.Set(consts.FieldRegion, "us-east-1")
}
d.Partial(false)
return awsSecretBackendRead(ctx, d, meta)
}
func awsSecretBackendRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
useAPIVer116 := provider.IsAPISupported(meta, provider.VaultVersion116) && provider.IsEnterpriseSupported(meta)
useAPIVer119 := provider.IsAPISupported(meta, provider.VaultVersion119)
client, e := provider.GetClient(d, meta)
if e != nil {
return diag.FromErr(e)
}
path := d.Id()
log.Printf("[DEBUG] Reading AWS backend mount %q from Vault", path)
mount, err := mountutil.GetMount(ctx, client, path)
if err != nil {
if mountutil.IsMountNotFoundError(err) {
log.Printf("[WARN] Mount %q not found, removing from state.", path)
d.SetId("")
return nil
}
return diag.FromErr(err)
}
log.Printf("[DEBUG] Read AWS backend mount %q from Vault", path)
log.Printf("[DEBUG] Read AWS secret backend config/root %s", path)
resp, err := client.Logical().ReadWithContext(ctx, path+"/config/root")
if err != nil {
// This is here to support backwards compatibility with Vault. Read operations on the config/root
// endpoint were just added and haven't been released yet, and so in currently released versions
// the read operations return a 405 error. We'll gracefully revert back to the old behavior in that
// case to allow for a transition period.
respErr, ok := err.(*api.ResponseError)
if !ok || respErr.StatusCode != 405 {
return diag.Errorf("error reading AWS secret backend config/root: %s", err)
}
log.Printf("[DEBUG] Unable to read config/root due to old version detected; skipping reading access_key and region parameters")
resp = nil
}
if resp != nil {
if v, ok := resp.Data[consts.FieldAccessKey].(string); ok {
d.Set(consts.FieldAccessKey, v)
}
// Terrible backwards compatibility hack. Previously, if no region was specified,
// this provider would just write a region of "us-east-1" into its state. Now that
// we're actually reading the region out from the backend, if it hadn't been set,
// it will return an empty string. This could potentially cause unexpected diffs
// for users of the provider, so to avoid it, we're doing something similar here
// and injecting a fake region of us-east-1 into the state.
if v, ok := resp.Data[consts.FieldRegion].(string); ok && v != "" {
d.Set(consts.FieldRegion, v)
} else {
d.Set(consts.FieldRegion, "us-east-1")
}
for _, k := range awsSecretFields {
if v, ok := resp.Data[k]; ok {
if err := d.Set(k, v); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", k, path, err)
}
}
}
if useAPIVer119 {
if v, ok := resp.Data[consts.FieldSTSFallbackEndpoints]; ok {
if err := d.Set(consts.FieldSTSFallbackEndpoints, v); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", consts.FieldSTSFallbackEndpoints, path, err)
}
}
if v, ok := resp.Data[consts.FieldSTSFallbackRegions]; ok {
if err := d.Set(consts.FieldSTSFallbackRegions, v); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", consts.FieldSTSFallbackRegions, path, err)
}
}
if v, ok := resp.Data[consts.FieldSTSRegion]; ok {
if err := d.Set(consts.FieldSTSRegion, v); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", consts.FieldSTSRegion, path, err)
}
}
}
if useAPIVer116 {
if err := d.Set(consts.FieldIdentityTokenAudience, resp.Data[consts.FieldIdentityTokenAudience]); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", consts.FieldIdentityTokenAudience, path, err)
}
if err := d.Set(consts.FieldRoleArn, resp.Data[consts.FieldRoleArn]); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", consts.FieldRoleArn, path, err)
}
if err := d.Set(consts.FieldIdentityTokenTTL, resp.Data[consts.FieldIdentityTokenTTL]); err != nil {
return diag.Errorf("error reading %s for AWS Secret Backend %q: %q", consts.FieldIdentityTokenTTL, path, err)
}
}
}
if err := d.Set(consts.FieldPath, path); err != nil {
return diag.FromErr(err)
}
if err := d.Set(consts.FieldDescription, mount.Description); err != nil {
return diag.FromErr(err)
}
if err := d.Set(consts.FieldDefaultLeaseTTL, mount.Config.DefaultLeaseTTL); err != nil {
return diag.FromErr(err)
}
if err := d.Set(consts.FieldMaxLeaseTTL, mount.Config.MaxLeaseTTL); err != nil {
return diag.FromErr(err)
}
if err := d.Set(consts.FieldLocal, mount.Local); err != nil {
return diag.FromErr(err)
}
if useAPIVer116 {
if err := d.Set(consts.FieldIdentityTokenKey, mount.Config.IdentityTokenKey); err != nil {
return diag.FromErr(err)
}
}
return nil
}
func awsSecretBackendUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
useAPIVer116 := provider.IsAPISupported(meta, provider.VaultVersion116) && provider.IsEnterpriseSupported(meta)
useAPIVer119 := provider.IsAPISupported(meta, provider.VaultVersion119)
client, e := provider.GetClient(d, meta)
if e != nil {
return diag.FromErr(e)
}
path := d.Id()
d.Partial(true)
path, err := util.Remount(d, client, consts.FieldPath, false)
if err != nil {
return diag.FromErr(err)
}
if d.HasChanges(consts.FieldDefaultLeaseTTL, consts.FieldMaxLeaseTTL, consts.FieldDescription, consts.FieldIdentityTokenKey) {
description := d.Get(consts.FieldDescription).(string)
config := api.MountConfigInput{
Description: &description,
DefaultLeaseTTL: fmt.Sprintf("%ds", d.Get(consts.FieldDefaultLeaseTTL)),
MaxLeaseTTL: fmt.Sprintf("%ds", d.Get(consts.FieldMaxLeaseTTL)),
}
if useAPIVer116 {
identityTokenKey := d.Get(consts.FieldIdentityTokenKey).(string)
if identityTokenKey != "" {
config.IdentityTokenKey = identityTokenKey
}
}
log.Printf("[DEBUG] Updating mount config input for %q", path)
err := client.Sys().TuneMountWithContext(ctx, path, config)
if err != nil {
return diag.Errorf("error updating mount config input for %q: %s", path, err)
}
log.Printf("[DEBUG] Updated mount config input for %q", path)
}
if d.HasChanges(consts.FieldAccessKey,
consts.FieldSecretKey, consts.FieldRegion, consts.FieldIAMEndpoint,
consts.FieldSTSEndpoint, consts.FieldSTSFallbackEndpoints, consts.FieldSTSRegion, consts.FieldSTSFallbackRegions,
consts.FieldIdentityTokenTTL, consts.FieldIdentityTokenAudience, consts.FieldRoleArn,
) {
log.Printf("[DEBUG] Updating root credentials at %q", path+"/config/root")
data := map[string]interface{}{
consts.FieldAccessKey: d.Get(consts.FieldAccessKey).(string),
consts.FieldSecretKey: d.Get(consts.FieldSecretKey).(string),
}
for _, k := range awsSecretFields {
if v, ok := d.GetOk(k); ok {
data[k] = v.(string)
}
}
if useAPIVer119 {
if v, ok := d.GetOk(consts.FieldSTSFallbackEndpoints); ok {
data[consts.FieldSTSFallbackEndpoints] = util.ToStringArray(v.([]interface{}))
}
if v, ok := d.GetOk(consts.FieldSTSFallbackRegions); ok {
data[consts.FieldSTSFallbackRegions] = util.ToStringArray(v.([]interface{}))
}
if v, ok := d.GetOk(consts.FieldSTSRegion); ok {
data[consts.FieldSTSRegion] = v.(string)
}
}
if useAPIVer116 {
identityTokenAudience := d.Get(consts.FieldIdentityTokenAudience).(string)
if identityTokenAudience != "" {
data[consts.FieldIdentityTokenAudience] = identityTokenAudience
}
roleArn := d.Get(consts.FieldRoleArn).(string)
if roleArn != "" {
data[consts.FieldRoleArn] = roleArn
}
identityTokenTTL := d.Get(consts.FieldIdentityTokenTTL).(int)
if identityTokenTTL != 0 {
data[consts.FieldIdentityTokenTTL] = identityTokenTTL
}
}
region := d.Get(consts.FieldRegion).(string)
if region != "" {
data[consts.FieldRegion] = region
}
_, err := client.Logical().WriteWithContext(ctx, path+"/config/root", data)
if err != nil {
return diag.Errorf("error configuring root credentials for %q: %s", path, err)
}
log.Printf("[DEBUG] Updated root credentials at %q", path+"/config/root")
if region == "" {
d.Set(consts.FieldRegion, "us-east-1")
}
}
d.Partial(false)
return awsSecretBackendRead(ctx, d, meta)
}
func awsSecretBackendDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client, e := provider.GetClient(d, meta)
if e != nil {
return diag.FromErr(e)
}
path := d.Id()
log.Printf("[DEBUG] Unmounting AWS backend %q", path)
err := client.Sys().UnmountWithContext(ctx, path)
if err != nil {
return diag.Errorf("error unmounting AWS backend from %q: %s", path, err)
}
log.Printf("[DEBUG] Unmounted AWS backend %q", path)
return nil
}