forked from hashicorp/terraform-provider-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_iam_role.go
550 lines (472 loc) · 15.6 KB
/
resource_aws_iam_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
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package aws
import (
"fmt"
"log"
"net/url"
"regexp"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
func resourceAwsIamRole() *schema.Resource {
return &schema.Resource{
Create: resourceAwsIamRoleCreate,
Read: resourceAwsIamRoleRead,
Update: resourceAwsIamRoleUpdate,
Delete: resourceAwsIamRoleDelete,
Importer: &schema.ResourceImporter{
State: resourceAwsIamRoleImport,
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"unique_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
// https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8329-L8334
value := v.(string)
if len(value) > 64 {
errors = append(errors, fmt.Errorf(
"%q cannot be longer than 64 characters", k))
}
if !regexp.MustCompile(`^[\w+=,.@-]*$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q must match [\\w+=,.@-]", k))
}
return
},
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"name"},
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
// https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8329-L8334
value := v.(string)
if len(value) > 32 {
errors = append(errors, fmt.Errorf(
"%q cannot be longer than 32 characters, name is limited to 64", k))
}
if !regexp.MustCompile(`^[\w+=,.@-]*$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q must match [\\w+=,.@-]", k))
}
return
},
},
"path": {
Type: schema.TypeString,
Optional: true,
Default: "/",
ForceNew: true,
},
"permissions_boundary": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 2048),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateIamRoleDescription,
},
"assume_role_policy": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs,
ValidateFunc: validation.ValidateJsonString,
},
"force_detach_policies": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"max_session_duration": {
Type: schema.TypeInt,
Optional: true,
Default: 3600,
ValidateFunc: validation.IntBetween(3600, 43200),
},
"tags": tagsSchema(),
},
}
}
func resourceAwsIamRoleImport(
d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
d.Set("force_detach_policies", false)
return []*schema.ResourceData{d}, nil
}
func resourceAwsIamRoleCreate(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
name = resource.PrefixedUniqueId(v.(string))
} else {
name = resource.UniqueId()
}
request := &iam.CreateRoleInput{
Path: aws.String(d.Get("path").(string)),
RoleName: aws.String(name),
AssumeRolePolicyDocument: aws.String(d.Get("assume_role_policy").(string)),
}
if v, ok := d.GetOk("description"); ok {
request.Description = aws.String(v.(string))
}
if v, ok := d.GetOk("max_session_duration"); ok {
request.MaxSessionDuration = aws.Int64(int64(v.(int)))
}
if v, ok := d.GetOk("permissions_boundary"); ok {
request.PermissionsBoundary = aws.String(v.(string))
}
if v, ok := d.GetOk("tags"); ok {
request.Tags = tagsFromMapIAM(v.(map[string]interface{}))
}
var createResp *iam.CreateRoleOutput
err := resource.Retry(30*time.Second, func() *resource.RetryError {
var err error
createResp, err = iamconn.CreateRole(request)
// IAM users (referenced in Principal field of assume policy)
// can take ~30 seconds to propagate in AWS
if isAWSErr(err, "MalformedPolicyDocument", "Invalid principal in policy") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
})
if isResourceTimeoutError(err) {
createResp, err = iamconn.CreateRole(request)
}
if err != nil {
return fmt.Errorf("Error creating IAM Role %s: %s", name, err)
}
d.SetId(*createResp.Role.RoleName)
stateConf := &resource.StateChangeConf{
Pending: []string{iam.ErrCodeNoSuchEntityException},
Target: []string{d.Id()},
Refresh: resourceAwsIamRoleStateRefreshFunc(meta, d.Id(), *createResp.Role.Arn),
Timeout: d.Timeout(schema.TimeoutCreate),
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for IAM role (%s) to create: %s", d.Id(), err)
}
return resourceAwsIamRoleRead(d, meta)
}
func resourceAwsIamRoleRead(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn
request := &iam.GetRoleInput{
RoleName: aws.String(d.Id()),
}
getResp, err := iamconn.GetRole(request)
if err != nil {
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
log.Printf("[WARN] IAM Role %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Error reading IAM Role %s: %s", d.Id(), err)
}
if getResp == nil || getResp.Role == nil {
log.Printf("[WARN] IAM Role %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
role := getResp.Role
d.Set("arn", role.Arn)
if err := d.Set("create_date", role.CreateDate.Format(time.RFC3339)); err != nil {
return err
}
d.Set("description", role.Description)
d.Set("max_session_duration", role.MaxSessionDuration)
d.Set("name", role.RoleName)
d.Set("path", role.Path)
if role.PermissionsBoundary != nil {
d.Set("permissions_boundary", role.PermissionsBoundary.PermissionsBoundaryArn)
}
d.Set("unique_id", role.RoleId)
if err := d.Set("tags", tagsToMapIAM(role.Tags)); err != nil {
return fmt.Errorf("error setting tags: %s", err)
}
assumRolePolicy, err := url.QueryUnescape(*role.AssumeRolePolicyDocument)
if err != nil {
return err
}
if err := d.Set("assume_role_policy", assumRolePolicy); err != nil {
return err
}
return nil
}
func resourceAwsIamRoleUpdate(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn
if d.HasChange("assume_role_policy") {
assumeRolePolicyInput := &iam.UpdateAssumeRolePolicyInput{
RoleName: aws.String(d.Id()),
PolicyDocument: aws.String(d.Get("assume_role_policy").(string)),
}
_, err := iamconn.UpdateAssumeRolePolicy(assumeRolePolicyInput)
if err != nil {
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
d.SetId("")
return nil
}
return fmt.Errorf("Error Updating IAM Role (%s) Assume Role Policy: %s", d.Id(), err)
}
}
if d.HasChange("description") {
roleDescriptionInput := &iam.UpdateRoleDescriptionInput{
RoleName: aws.String(d.Id()),
Description: aws.String(d.Get("description").(string)),
}
_, err := iamconn.UpdateRoleDescription(roleDescriptionInput)
if err != nil {
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
d.SetId("")
return nil
}
return fmt.Errorf("Error Updating IAM Role (%s) Assume Role Policy: %s", d.Id(), err)
}
}
if d.HasChange("max_session_duration") {
roleMaxDurationInput := &iam.UpdateRoleInput{
RoleName: aws.String(d.Id()),
MaxSessionDuration: aws.Int64(int64(d.Get("max_session_duration").(int))),
}
_, err := iamconn.UpdateRole(roleMaxDurationInput)
if err != nil {
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
d.SetId("")
return nil
}
return fmt.Errorf("Error Updating IAM Role (%s) Max Session Duration: %s", d.Id(), err)
}
}
if d.HasChange("permissions_boundary") {
permissionsBoundary := d.Get("permissions_boundary").(string)
if permissionsBoundary != "" {
input := &iam.PutRolePermissionsBoundaryInput{
PermissionsBoundary: aws.String(permissionsBoundary),
RoleName: aws.String(d.Id()),
}
_, err := iamconn.PutRolePermissionsBoundary(input)
if err != nil {
return fmt.Errorf("error updating IAM Role permissions boundary: %s", err)
}
} else {
input := &iam.DeleteRolePermissionsBoundaryInput{
RoleName: aws.String(d.Id()),
}
_, err := iamconn.DeleteRolePermissionsBoundary(input)
if err != nil {
return fmt.Errorf("error deleting IAM Role permissions boundary: %s", err)
}
}
}
if d.HasChange("tags") {
// Reset all tags to empty set
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
c, r := diffTagsIAM(tagsFromMapIAM(o), tagsFromMapIAM(n))
if len(r) > 0 {
_, err := iamconn.UntagRole(&iam.UntagRoleInput{
RoleName: aws.String(d.Id()),
TagKeys: tagKeysIam(r),
})
if err != nil {
return fmt.Errorf("error deleting IAM role tags: %s", err)
}
}
if len(c) > 0 {
input := &iam.TagRoleInput{
RoleName: aws.String(d.Id()),
Tags: c,
}
_, err := iamconn.TagRole(input)
if err != nil {
return fmt.Errorf("error update IAM role tags: %s", err)
}
}
}
return resourceAwsIamRoleRead(d, meta)
}
func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn
// Roles cannot be destroyed when attached to an existing Instance Profile
if err := deleteAwsIamRoleInstanceProfiles(iamconn, d.Id()); err != nil {
return fmt.Errorf("error deleting IAM Role (%s) instance profiles: %s", d.Id(), err)
}
if d.Get("force_detach_policies").(bool) {
// For managed policies
if err := deleteAwsIamRolePolicyAttachments(iamconn, d.Id()); err != nil {
return fmt.Errorf("error deleting IAM Role (%s) policy attachments: %s", d.Id(), err)
}
// For inline policies
if err := deleteAwsIamRolePolicies(iamconn, d.Id()); err != nil {
return fmt.Errorf("error deleting IAM Role (%s) policies: %s", d.Id(), err)
}
}
deleteRoleInput := &iam.DeleteRoleInput{
RoleName: aws.String(d.Id()),
}
// IAM is eventually consistent and deletion of attached policies may take time
err := resource.Retry(30*time.Second, func() *resource.RetryError {
_, err := iamconn.DeleteRole(deleteRoleInput)
if err != nil {
if isAWSErr(err, iam.ErrCodeDeleteConflictException, "") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(fmt.Errorf("Error deleting IAM Role %s: %s", d.Id(), err))
}
return nil
})
if isResourceTimeoutError(err) {
_, err = iamconn.DeleteRole(deleteRoleInput)
}
if err != nil {
return fmt.Errorf("Error deleting IAM role: %s", err)
}
stateConf := &resource.StateChangeConf{
Pending: []string{d.Id()},
Target: []string{iam.ErrCodeNoSuchEntityException},
Refresh: resourceAwsIamRoleStateRefreshFunc(meta, d.Id(), d.Get("arn").(string)),
Timeout: d.Timeout(schema.TimeoutCreate),
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for IAM role (%s) to create: %s", d.Id(), err)
}
return nil
}
func deleteAwsIamRoleInstanceProfiles(conn *iam.IAM, rolename string) error {
resp, err := conn.ListInstanceProfilesForRole(&iam.ListInstanceProfilesForRoleInput{
RoleName: aws.String(rolename),
})
if err != nil {
return fmt.Errorf("Error listing Profiles for IAM Role (%s) when trying to delete: %s", rolename, err)
}
// Loop and remove this Role from any Profiles
for _, i := range resp.InstanceProfiles {
input := &iam.RemoveRoleFromInstanceProfileInput{
InstanceProfileName: i.InstanceProfileName,
RoleName: aws.String(rolename),
}
_, err := conn.RemoveRoleFromInstanceProfile(input)
if err != nil {
return fmt.Errorf("Error deleting IAM Role %s: %s", rolename, err)
}
}
return nil
}
func deleteAwsIamRolePolicyAttachments(conn *iam.IAM, rolename string) error {
managedPolicies := make([]*string, 0)
input := &iam.ListAttachedRolePoliciesInput{
RoleName: aws.String(rolename),
}
err := conn.ListAttachedRolePoliciesPages(input, func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool {
for _, v := range page.AttachedPolicies {
managedPolicies = append(managedPolicies, v.PolicyArn)
}
return !lastPage
})
if err != nil {
return fmt.Errorf("Error listing Policies for IAM Role (%s) when trying to delete: %s", rolename, err)
}
for _, parn := range managedPolicies {
input := &iam.DetachRolePolicyInput{
PolicyArn: parn,
RoleName: aws.String(rolename),
}
_, err = conn.DetachRolePolicy(input)
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
continue
}
if err != nil {
return fmt.Errorf("Error deleting IAM Role %s: %s", rolename, err)
}
}
return nil
}
func deleteAwsIamRolePolicies(conn *iam.IAM, rolename string) error {
inlinePolicies := make([]*string, 0)
input := &iam.ListRolePoliciesInput{
RoleName: aws.String(rolename),
}
err := conn.ListRolePoliciesPages(input, func(page *iam.ListRolePoliciesOutput, lastPage bool) bool {
inlinePolicies = append(inlinePolicies, page.PolicyNames...)
return !lastPage
})
if err != nil {
return fmt.Errorf("Error listing inline Policies for IAM Role (%s) when trying to delete: %s", rolename, err)
}
for _, pname := range inlinePolicies {
input := &iam.DeleteRolePolicyInput{
PolicyName: pname,
RoleName: aws.String(rolename),
}
_, err := conn.DeleteRolePolicy(input)
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
continue
}
if err != nil {
return fmt.Errorf("Error deleting inline policy of IAM Role %s: %s", rolename, err)
}
}
return nil
}
func resourceAwsIamRoleStateRefreshFunc(meta interface{}, id, arn string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
log.Printf("[YAK] role state refresh id:%s", id)
iamconn := meta.(*AWSClient).iamconn
input := &iam.GetRoleInput{
RoleName: aws.String(id),
}
output, err := iamconn.GetRole(input)
if err != nil {
log.Printf("[YAK] role state refresh err", err)
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
return *output, iam.ErrCodeNoSuchEntityException, nil
}
return nil, "", err
}
stsconn := meta.(*AWSClient).stsconn
stsInput := &sts.AssumeRoleInput{
DurationSeconds: aws.Int64(900),
ExternalId: aws.String("fa739c5c-f516-5ba1-9d86-96b2ea62d761"),
RoleArn: aws.String(arn),
RoleSessionName: aws.String("Bob"),
}
stsOutput, err := stsconn.AssumeRole(stsInput)
if err != nil {
log.Printf("[YAK] role (%s) state refresh assume role err:%s", arn, err)
if isAWSErr(err, "AccessDenied", "Access denied") {
log.Printf("[YAK] INSIDE role state refresh assume role err:%s", err)
// This error is only returned before role is created.
// If current user has no access to the role, when
// creation is complete, the error will be more specific:
// "AccessDenied: User <user_arn> is not authorized to
// perform: sts:AssumeRole on resource: <role_arn>"
return *stsOutput, iam.ErrCodeNoSuchEntityException, nil
}
}
log.Printf("[YAK] role state refresh no err, return %s", aws.StringValue(output.Role.RoleName))
return *output, aws.StringValue(output.Role.RoleName), nil
}
}