Skip to content

fix: Replace count with for_each in additional_many policy attachment#738

Open
gungoren wants to merge 3 commits intoterraform-aws-modules:masterfrom
gungoren:fix/iam-policy-attachment-for-each
Open

fix: Replace count with for_each in additional_many policy attachment#738
gungoren wants to merge 3 commits intoterraform-aws-modules:masterfrom
gungoren:fix/iam-policy-attachment-for-each

Conversation

@gungoren
Copy link

Summary

  • Replaces count with for_each in aws_iam_role_policy_attachment.additional_many
  • Uses policy ARN as the stable for_each key instead of list index
  • Prevents unnecessary detach/reattach of all policies when one is removed from the front or middle of the list, which causes Lambda functions to temporarily lose access to external services during the destroy→attach cycle

Problem

When using count with a list of policy ARNs, Terraform tracks attachments by index. Removing any item other than the last causes all subsequent resources to be re-indexed, triggering a full detach of all policies followed by reattachment of the remaining ones. During this window, the Lambda function loses IAM permissions.

Solution

Switch to for_each with toset(var.policies), using the ARN itself as the stable key. This ensures Terraform only destroys the specific attachment being removed, leaving all others untouched.

Test plan

  • Apply with existing policies — verify no changes detected
  • Remove a policy from the front of the list — verify only that attachment is destroyed, others are untouched
  • Verify Lambda functions retain external service access during policy changes

… to prevent detach/reattach on list reorder

Signed-off-by: Mehmet Gungoren <mehgungoren@gmail.com>
@gungoren gungoren changed the title fix: replace count with for_each in additional_many policy attachment fix: Replace count with for_each in additional_many policy attachment Mar 17, 2026
Signed-off-by: Mehmet Gungoren <mehgungoren@gmail.com>
…moval

Signed-off-by: Mehmet Gungoren <mehgungoren@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant