Introduction
When creating an aws_iam_role resource using the Terraform AWS Provider, an inline_policy with incorrect syntax may be rejected by AWS. When this occurs, the aws_iam_role resource is created in AWS but is not tracked in the Terraform state file, leaving it orphaned.
This happens because AWS does not validate the inline_policy before creating the aws_iam_role resource. The policy validation fails only after the IAM Role has been created.
Problem
During a terraform apply, an invalid inline_policy causes the aws_iam_role resource to be created in AWS but not added to the Terraform state. Subsequent Terraform runs will fail because the role already exists.
│ Error: │ error creating IAM Role (RoleWithInvalidInlinePolicy): │ EntityAlreadyExists: │ Role with name RoleWithInvalidInlinePolicy already exists. │ status code: 409, request id: 25d27ece...
Prerequisites
- Terraform AWS Provider version
3.74.0or earlier. - An
aws_iam_roleresource configured with aninline_policy.
Cause
The Terraform AWS Provider first creates the IAM Role and then attempts to attach the inline IAM Policy. When AWS validates and rejects the policy with a Malformed policy error, the provider operation fails. Because the error occurs after the role was created, the resource is not saved to the state file.
Solutions
After you confirm the policy syntax is valid, use one of the following methods to resolve the state mismatch.
Solution 1: Import the Existing Role
Import the orphaned IAM role into the Terraform state. Then, run terraform apply to attach the corrected IAM policy.
Solution 2: Recreate the Role
Manually delete the orphaned IAM Role from the AWS console. Then, run terraform apply again to have Terraform create the role with the valid inline_policy.
Outcome Validation
To verify that the role and policy were created and are tracked correctly, run terraform apply again. A successful run should report no changes to your infrastructure.
Alternatively, you can run terraform state list and confirm that the aws_iam_role resource is present in the state.