forked from hashicorp/terraform-provider-vault
/
resource_aws_auth_backend_role.go
457 lines (418 loc) · 14.3 KB
/
resource_aws_auth_backend_role.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
package vault
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/vault/api"
)
var (
awsAuthBackendRoleBackendFromPathRegex = regexp.MustCompile("^auth/(.+)/role/.+$")
awsAuthBackendRoleNameFromPathRegex = regexp.MustCompile("^auth/.+/role/(.+)$")
)
func awsAuthBackendRoleResource() *schema.Resource {
return &schema.Resource{
Create: awsAuthBackendRoleCreate,
Read: awsAuthBackendRoleRead,
Update: awsAuthBackendRoleUpdate,
Delete: awsAuthBackendRoleDelete,
Exists: awsAuthBackendRoleExists,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"role": {
Type: schema.TypeString,
Required: true,
Description: "Name of the role.",
ForceNew: true,
},
"auth_type": {
Type: schema.TypeString,
Optional: true,
Default: "iam",
Description: "The auth type permitted for this role.",
ForceNew: true,
},
"bound_ami_id": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances using this AMI ID will be permitted to log in.",
},
"bound_account_id": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances with this account ID in their identity document will be permitted to log in.",
},
"bound_region": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances in this region will be permitted to log in.",
},
"bound_vpc_id": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances associated with this VPC ID will be permitted to log in.",
},
"bound_subnet_id": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances associated with this subnet ID will be permitted to log in.",
},
"bound_iam_role_arn": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances that match this IAM role ARN will be permitted to log in.",
},
"bound_iam_instance_profile_arn": {
Type: schema.TypeString,
Optional: true,
Description: "Only EC2 instances associated with an IAM instance profile ARN that matches this value will be permitted to log in.",
},
"role_tag": {
Type: schema.TypeString,
Optional: true,
Description: "The key of the tag on EC2 instance to use for role tags.",
},
"bound_iam_principal_arn": {
Type: schema.TypeString,
Optional: true,
Description: "The IAM principal that must be authenticated using the iam auth method.",
},
"inferred_entity_type": {
Type: schema.TypeString,
Optional: true,
Description: "The type of inferencing Vault should do.",
},
"inferred_aws_region": {
Type: schema.TypeString,
Optional: true,
Description: "The region to search for the inferred entities in.",
},
"resolve_aws_unique_ids": {
Type: schema.TypeBool,
Optional: true,
Description: "Whether or not Vault should resolve the bound_iam_principal_arn to an AWS Unique ID. When true, deleting a principal and recreating it with the same name won't automatically grant the new principal the same roles in Vault that the old principal had.",
Computed: true,
},
"ttl": {
Type: schema.TypeInt,
Optional: true,
Description: "The TTL period of tokens issued using this role, provided as the number of seconds.",
},
"max_ttl": {
Type: schema.TypeInt,
Optional: true,
Description: "The maximum allowed lifetime of tokens issued using this role, provided as the number of seconds.",
},
"period": {
Type: schema.TypeInt,
Optional: true,
Description: "If set, indicates that the token generated using this role should never expire. The token should be renewed within the duration specified by this value. At each renewal, the token's TTL will be set to the value of this field. The maximum allowed lifetime of token issued using this role. Specified as a number of seconds.",
},
"policies": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Description: "Policies to be set on tokens issued using this role.",
},
"allow_instance_migration": {
Type: schema.TypeBool,
Optional: true,
Description: "When true, allows migration of the underlying instance where the client resides. Use with caution.",
Computed: true,
},
"disallow_reauthentication": {
Type: schema.TypeBool,
Optional: true,
Description: "When true, only allows a single token to be granted per instance ID.",
},
"backend": {
Type: schema.TypeString,
Optional: true,
Description: "Unique name of the auth backend to configure.",
ForceNew: true,
Default: "aws",
// standardise on no beginning or trailing slashes
StateFunc: func(v interface{}) string {
return strings.Trim(v.(string), "/")
},
},
},
}
}
func awsAuthBackendRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
backend := d.Get("backend").(string)
role := d.Get("role").(string)
path := awsAuthBackendRolePath(backend, role)
log.Printf("[DEBUG] Writing AWS auth backend role %q", path)
iPolicies := d.Get("policies").([]interface{})
policies := make([]string, 0, len(iPolicies))
for _, iPolicy := range iPolicies {
policies = append(policies, iPolicy.(string))
}
authType := d.Get("auth_type").(string)
inferred := d.Get("inferred_entity_type").(string)
data := map[string]interface{}{
"auth_type": authType,
}
if v, ok := d.GetOk("ttl"); ok {
data["ttl"] = v.(int)
}
if v, ok := d.GetOk("max_ttl"); ok {
data["max_ttl"] = v.(int)
}
if v, ok := d.GetOk("period"); ok {
data["period"] = v.(int)
}
if len(policies) > 0 {
data["policies"] = policies
}
if authType == "ec2" || (inferred == "ec2_instance" && authType == "iam") {
if v, ok := d.GetOk("bound_ami_id"); ok {
data["bound_ami_id"] = v.(string)
}
if v, ok := d.GetOk("bound_account_id"); ok {
data["bound_account_id"] = v.(string)
}
if v, ok := d.GetOk("bound_region"); ok {
data["bound_region"] = v.(string)
}
if v, ok := d.GetOk("bound_vpc_id"); ok {
data["bound_vpc_id"] = v.(string)
}
if v, ok := d.GetOk("bound_subnet_id"); ok {
data["bound_subnet_id"] = v.(string)
}
if v, ok := d.GetOk("bound_iam_role_arn"); ok {
data["bound_iam_role_arn"] = v.(string)
}
if v, ok := d.GetOk("bound_iam_instance_profile_arn"); ok {
data["bound_iam_instance_profile_arn"] = v.(string)
}
}
if authType == "ec2" {
if v, ok := d.GetOk("role_tag"); ok {
data["role_tag"] = v.(string)
}
if v, ok := d.GetOk("allow_instance_migration"); ok {
data["allow_instance_migration"] = v.(bool)
}
if v, ok := d.GetOk("disallow_reauthentication"); ok {
data["disallow_reauthentication"] = v.(bool)
}
}
if authType == "iam" {
if inferred != "" {
data["inferred_entity_type"] = inferred
}
if v, ok := d.GetOk("bound_iam_principal_arn"); ok {
data["bound_iam_principal_arn"] = v.(string)
}
if v, ok := d.GetOk("inferred_aws_region"); ok {
data["inferred_aws_region"] = v.(string)
}
if v, ok := d.GetOk("resolve_aws_unique_ids"); ok {
data["resolve_aws_unique_ids"] = v.(bool)
}
}
_, err := client.Logical().Write(path, data)
d.SetId(path)
if err != nil {
d.SetId("")
return fmt.Errorf("error writing AWS auth backend role %q: %s", path, err)
}
log.Printf("[DEBUG] Wrote AWS auth backend role %q", path)
return awsAuthBackendRoleRead(d, meta)
}
func awsAuthBackendRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
path := d.Id()
backend, err := awsAuthBackendRoleBackendFromPath(path)
if err != nil {
return fmt.Errorf("invalid path %q for AWS auth backend role: %s", path, err)
}
role, err := awsAuthBackendRoleNameFromPath(path)
if err != nil {
return fmt.Errorf("invalid path %q for AWS auth backend role: %s", path, err)
}
log.Printf("[DEBUG] Reading AWS auth backend role %q", path)
resp, err := client.Logical().Read(path)
if err != nil {
return fmt.Errorf("error reading AWS auth backend role %q: %s", path, err)
}
log.Printf("[DEBUG] Read AWS auth backend role %q", path)
if resp == nil {
log.Printf("[WARN] AWS auth backend role %q not found, removing from state", path)
d.SetId("")
return nil
}
iPolicies := resp.Data["policies"].([]interface{})
policies := make([]string, 0, len(iPolicies))
for _, iPolicy := range iPolicies {
policies = append(policies, iPolicy.(string))
}
ttl, err := resp.Data["ttl"].(json.Number).Int64()
if err != nil {
return fmt.Errorf("expected ttl %q to be a number, isn't", resp.Data["ttl"])
}
maxTTL, err := resp.Data["max_ttl"].(json.Number).Int64()
if err != nil {
return fmt.Errorf("expected max_ttl %q to be a number, isn't", resp.Data["max_ttl"])
}
period, err := resp.Data["period"].(json.Number).Int64()
if err != nil {
return fmt.Errorf("expected period %q to be a number, isn't", resp.Data["period"])
}
d.Set("backend", backend)
d.Set("role", role)
d.Set("auth_type", resp.Data["auth_type"])
d.Set("bound_ami_id", resp.Data["bound_ami_id"])
d.Set("bound_account_id", resp.Data["bound_account_id"])
d.Set("bound_region", resp.Data["bound_region"])
d.Set("bound_vpc_id", resp.Data["bound_vpc_id"])
d.Set("bound_subnet_id", resp.Data["bound_subnet_id"])
d.Set("bound_iam_role_arn", resp.Data["bound_iam_role_arn"])
d.Set("bound_iam_instance_profile_arn", resp.Data["bound_iam_instance_profile_arn"])
d.Set("role_tag", resp.Data["role_tag"])
d.Set("bound_iam_principal_arn", resp.Data["bound_iam_principal_arn"])
d.Set("inferred_entity_type", resp.Data["inferred_entity_type"])
d.Set("inferred_aws_region", resp.Data["inferred_aws_region"])
d.Set("resolve_aws_unique_ids", resp.Data["resolve_aws_unique_ids"])
d.Set("ttl", ttl)
d.Set("max_ttl", maxTTL)
d.Set("period", period)
d.Set("policies", policies)
d.Set("allow_instance_migration", resp.Data["allow_instance_migration"])
d.Set("disallow_reauthentication", resp.Data["disallow_reauthentication"])
return nil
}
func awsAuthBackendRoleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
path := d.Id()
log.Printf("[DEBUG] Updating AWS auth backend role %q", path)
iPolicies := d.Get("policies").([]interface{})
policies := make([]string, 0, len(iPolicies))
for _, iPolicy := range iPolicies {
policies = append(policies, iPolicy.(string))
}
authType := d.Get("auth_type").(string)
inferred := d.Get("inferred_entity_type").(string)
data := map[string]interface{}{}
if v, ok := d.GetOk("ttl"); ok {
data["ttl"] = v.(int)
}
if v, ok := d.GetOk("max_ttl"); ok {
data["max_ttl"] = v.(int)
}
if v, ok := d.GetOk("period"); ok {
data["period"] = v.(int)
}
if len(policies) > 0 {
data["policies"] = policies
}
if authType == "ec2" || (inferred == "ec2_instance" && authType == "iam") {
if v, ok := d.GetOk("bound_ami_id"); ok {
data["bound_ami_id"] = v.(string)
}
if v, ok := d.GetOk("bound_account_id"); ok {
data["bound_account_id"] = v.(string)
}
if v, ok := d.GetOk("bound_region"); ok {
data["bound_region"] = v.(string)
}
if v, ok := d.GetOk("bound_vpc_id"); ok {
data["bound_vpc_id"] = v.(string)
}
if v, ok := d.GetOk("bound_subnet_id"); ok {
data["bound_subnet_id"] = v.(string)
}
if v, ok := d.GetOk("bound_iam_role_arn"); ok {
data["bound_iam_role_arn"] = v.(string)
}
if v, ok := d.GetOk("bound_iam_instance_profile_arn"); ok {
data["bound_iam_instance_profile_arn"] = v.(string)
}
}
if authType == "ec2" {
if v, ok := d.GetOk("role_tag"); ok {
data["role_tag"] = v.(string)
}
if v, ok := d.GetOk("allow_instance_migration"); ok {
data["allow_instance_migration"] = v.(bool)
}
if v, ok := d.GetOk("disallow_reauthentication"); ok {
data["disallow_reauthentication"] = v.(bool)
}
}
if authType == "iam" {
if inferred != "" {
data["inferred_entity_type"] = inferred
}
if v, ok := d.GetOk("bound_iam_principal_arn"); ok {
data["bound_iam_principal_arn"] = v.(string)
}
if v, ok := d.GetOk("inferred_aws_region"); ok {
data["inferred_aws_region"] = v.(string)
}
if v, ok := d.GetOk("resolve_aws_unique_ids"); ok {
data["resolve_aws_unique_ids"] = v.(bool)
}
}
_, err := client.Logical().Write(path, data)
if err != nil {
return fmt.Errorf("error updating AWS auth backend role %q: %s", path, err)
}
log.Printf("[DEBUG] Updated AWS auth backend role %q", path)
return awsAuthBackendRoleRead(d, meta)
}
func awsAuthBackendRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*api.Client)
path := d.Id()
log.Printf("[DEBUG] Deleting AWS auth backend role %q", path)
_, err := client.Logical().Delete(path)
if err != nil {
return fmt.Errorf("error deleting AWS auth backend role %q", path)
}
log.Printf("[DEBUG] Deleted AWS auth backend role %q", path)
return nil
}
func awsAuthBackendRoleExists(d *schema.ResourceData, meta interface{}) (bool, error) {
client := meta.(*api.Client)
path := d.Id()
log.Printf("[DEBUG] Checking if AWS auth backend role %q exists", path)
resp, err := client.Logical().Read(path)
if err != nil {
return true, fmt.Errorf("error checking if AWS auth backend role %q exists: %s", path, err)
}
log.Printf("[DEBUG] Checked if AWS auth backend role %q exists", path)
return resp != nil, nil
}
func awsAuthBackendRolePath(backend, role string) string {
return "auth/" + strings.Trim(backend, "/") + "/role/" + strings.Trim(role, "/")
}
func awsAuthBackendRoleNameFromPath(path string) (string, error) {
if !awsAuthBackendRoleNameFromPathRegex.MatchString(path) {
return "", fmt.Errorf("no role found")
}
res := awsAuthBackendRoleNameFromPathRegex.FindStringSubmatch(path)
if len(res) != 2 {
return "", fmt.Errorf("unexpected number of matches (%d) for role", len(res))
}
return res[1], nil
}
func awsAuthBackendRoleBackendFromPath(path string) (string, error) {
if !awsAuthBackendRoleBackendFromPathRegex.MatchString(path) {
return "", fmt.Errorf("no backend found")
}
res := awsAuthBackendRoleBackendFromPathRegex.FindStringSubmatch(path)
if len(res) != 2 {
return "", fmt.Errorf("unexpected number of matches (%d) for backend", len(res))
}
return res[1], nil
}