The resource aws_iam_policy_attachment has the following warning
WARNING: The
aws_iam_policy_attachment
resource creates exclusive attachments of IAM policies. Across the entire AWS account, all of the users/roles/groups to which a single policy is attached must be declared by a singleaws_iam_policy_attachment
resource. This means that even any users/roles/groups that have the attached policy via any other mechanism (including other Terraform resources) will have that attached policy revoked by this resource. Consideraws_iam_role_policy_attachment
,aws_iam_user_policy_attachment
, oraws_iam_group_policy_attachment
instead. These resources do not enforce exclusive attachment of an IAM policy.
We changed some of our code from
resource "aws_iam_policy_attachment" "logs" {
name = "${var.function_name}-logs"
roles = [aws_iam_role.lambda.name]
policy_arn = aws_iam_policy.logs[0].arn
}
to
resource "aws_iam_role_policy_attachment" "logs" {
name = "${var.function_name}-logs"
role = aws_iam_role.lambda.name
policy_arn = aws_iam_policy.logs[0].arn
}
The change above is simple but now terraform wants to remove the aws_iam_policy_attachment
resource and add the aws_iam_role_policy_attachment
. Previously, when we applied the terraform for a module using a shared managed IAM resource, it detached the policy from 30 different IAM roles, forcing us to reattach them by finding and reapplying our terraform modules.
What is a safe strategy to use the less dangerous resource aws_iam_role_policy_attachment
?
Our current strategy
Recreate managed IAM policy as an inline policy and add to role
Remove the managed policy manually using AWS console
Possibly easier with this CLI command. It just seems in the console.
aws iam detach-role-policy \ --role-name my-role-name \ --policy-arn arn:aws:iam:1234567890:role/logs
Remove the bad resource from the state
- May not be necessary since it was removed in the previous step
terraform state rm aws_iam_policy_attachment.logs
Target apply the new attachment
target apply -target aws_iam_role_policy_attachment.logs
Sanity check
terraform plan
Remove the inline policy from the first step
aws_iam_role_policy_attachment
resource so that is an option if you don't want to have a brief blip on IAM permissions while you refactor this or there's another reason you want to avoid a potential intermittent failure before a retry fixes things. I'd personally just run the apply and if it fails double tap it as this is a one off migration when refactoring. – ydaetskcoRaws_iam_role_policy_attachment
isn't the issue. The issue is the removal of theaws_iam_policy_attachment
which causes detachment in other roles outside of the terraform module being applied. – SomeGuyOnAComputer