Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resource/aws_iam_role: Use ListAttachedRolePoliciesPages #2857

Merged
merged 1 commit into from
Jan 18, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions aws/resource_aws_iam_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()),
Expand Down