When creating a 'aws_iam_role' (using the AWS Provider for Terraform) and the 'inline_policy' contains incorrect syntax that causes it to be rejected by AWS, the 'aws_iam_role' is orphaned and will not be tracked by the Terraform state.
AWS does not validate the 'inline_policy' before creating the 'aws_iam_role' resource, and only after the IAM Role is created will the policy validation fail.
During a Terraform Apply an invalid 'inline_policy' will cause the 'aws_iam_role' to not be added to the Terraform state.
- Terraform AWS Provider <= '3.74.0'
- 'aws_iam_role' resource using a 'inline_policy'
- This issue is caused by the Terraform AWS Provider creating the IAM Role before it has attempted to create the inline IAM Policy defined in the 'aws_iam_role' resource. After the role is created, it requests the creation of the IAM Policy, the policy is then validated by AWS and returns a 'Malformed policy' error. The IAM Role is not saved to the state due to this error.
The next run of Terraform will fail due to the 'aws_iam_role' already existing.
│ Error: error creating IAM Role (RoleWithInvalidInlinePolicy): EntityAlreadyExists: Role with name RoleWithInvalidInlinePolicy already exists.
│ status code: 409, request id: 25d27ece...
Once the policy has been confirmed to be valid, you can work around this issue with one of the following methods;
Import the existing role and run 'terraform apply' to apply the now valid IAM Policy.
Remove the IAM Role from AWS and have Terraform create it during the next apply run with a valid 'inline_policy'.
The easiest way to verify that the role and policy have created as expected is to run 'terraform apply' without making any changes to the Terraform code and verify that the run completes without error.
Alternatively you can run 'terraform state list' and validate that the IAM Role exists with the policy as expected.