hashicorp / terraform-provider-aws

The AWS Provider enables Terraform to manage AWS resources.
https://registry.terraform.io/providers/hashicorp/aws
Mozilla Public License 2.0
9.86k stars 9.21k forks source link

destroy order - aws_iam_user & aws_iam_policy_attachment #25074

Open brunobritodev opened 2 years ago

brunobritodev commented 2 years ago

Community Note

Terraform CLI and Terraform AWS Provider Version

terraform -v
Terraform v1.1.2
+ provider registry.terraform.io/hashicorp/aws v4.15.1

Affected Resource(s)

Terraform Configuration Files

resource "aws_iam_user" "powerusers" {
  for_each = toset(["user_a", "user_b"])
  name     = each.key
}

resource "aws_iam_policy_attachment" "powerusers" {
  name       = "iam-codebuild-powerusers"
  users      = keys({ for k, v in aws_iam_user.powerusers : k => v })
  policy_arn = "arn:aws:iam::aws:policy/AWSCodeCommitPowerUser"
}

Expected Behavior

  1. Remove policy attachment
  2. Remove user

Actual Behavior

  1. Remove user
  2. Remove policy attachment

It must remove policy attachment first, then remove user. Actually it tries to remove user first.

aws_iam_user.powerusers["user_b"]: Destroying... [id=user_b]
Error: Error deleting IAM User user_b: DeleteConflict: Cannot delete entity, must detach all policies first.
       status code: 409, request id: ....

Steps to Reproduce

  1. terraform apply
  2. Remove user_b from list
  3. terraform apply
justinretzolk commented 2 years ago

Hey @brunohbrito 👋 I looked into this a bit and came across this helpful comment that gave a breakdown on why this happens and how to get around it. Can you take a look over that and let me know if it helps you get past this issue?

brunobritodev commented 1 year ago

@justinretzolk In this case no. Even if we set force_destroy = true on aws_iam_users the same error happens.

The destroy order here is important. So a workaround is first run a terraform apply -target=aws_iam_policy_attachment.powerusers, then terraform apply, so the users are removed.

github-actions[bot] commented 1 week ago

Marking this issue as stale due to inactivity. This helps our maintainers find and focus on the active issues. If this issue receives no comments in the next 30 days it will automatically be closed. Maintainers can also remove the stale label.

If this issue was automatically closed and you feel this issue should be reopened, we encourage creating a new issue linking back to this one for added context. Thank you!