From 09a59a8b15aed3f4b27e56c8c932a01da34f809b Mon Sep 17 00:00:00 2001 From: Atsushi Ishibashi Date: Thu, 4 Jan 2018 16:36:17 +0900 Subject: [PATCH] Use ListAttachedRolePoliciesPages --- aws/resource_aws_iam_role.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/aws/resource_aws_iam_role.go b/aws/resource_aws_iam_role.go index 439868062d9..43526174c0f 100644 --- a/aws/resource_aws_iam_role.go +++ b/aws/resource_aws_iam_role.go @@ -267,17 +267,23 @@ func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error { } if d.Get("force_detach_policies").(bool) { - policiesResp, err := iamconn.ListAttachedRolePolicies(&iam.ListAttachedRolePoliciesInput{ + // For managed policies + managedPolicies := make([]*string, 0) + err = iamconn.ListAttachedRolePoliciesPages(&iam.ListAttachedRolePoliciesInput{ RoleName: aws.String(d.Id()), + }, func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool { + for _, v := range page.AttachedPolicies { + managedPolicies = append(managedPolicies, v.PolicyArn) + } + return len(page.AttachedPolicies) > 0 }) if err != nil { return fmt.Errorf("Error listing Policies for IAM Role (%s) when trying to delete: %s", d.Id(), err) } - // Loop and remove the Policies from the Role - if len(policiesResp.AttachedPolicies) > 0 { - for _, i := range policiesResp.AttachedPolicies { - _, err := iamconn.DetachRolePolicy(&iam.DetachRolePolicyInput{ - PolicyArn: i.PolicyArn, + if len(managedPolicies) > 0 { + for _, parn := range managedPolicies { + _, err = iamconn.DetachRolePolicy(&iam.DetachRolePolicyInput{ + PolicyArn: parn, RoleName: aws.String(d.Id()), }) if err != nil { @@ -287,20 +293,20 @@ func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error { } // For inline policies - rolePolicyNames := make([]*string, 0) + inlinePolicies := make([]*string, 0) err = iamconn.ListRolePoliciesPages(&iam.ListRolePoliciesInput{ RoleName: aws.String(d.Id()), }, func(page *iam.ListRolePoliciesOutput, lastPage bool) bool { for _, v := range page.PolicyNames { - rolePolicyNames = append(rolePolicyNames, v) + inlinePolicies = append(inlinePolicies, v) } return len(page.PolicyNames) > 0 }) if err != nil { return fmt.Errorf("Error listing inline Policies for IAM Role (%s) when trying to delete: %s", d.Id(), err) } - if len(rolePolicyNames) > 0 { - for _, pname := range rolePolicyNames { + if len(inlinePolicies) > 0 { + for _, pname := range inlinePolicies { _, err := iamconn.DeleteRolePolicy(&iam.DeleteRolePolicyInput{ PolicyName: pname, RoleName: aws.String(d.Id()),