Problem
An aws_iam_policy_document
data source with no statement
blocks produces a document that can't be read by aws_iam_policy
.
Cause
First an apply occurs with a valid statement and is saved to the state file.
data "aws_iam_policy_document" "maybe_empty" {
statement {
actions = [ "ssm:SendCommand" ]
resources = [ "*" ]
}
}
resource "aws_iam_policy" "example" {
name = "example"
policy = data.aws_iam_policy_document.maybe_empty.json
}
Changes are then made to the Terraform configuration and statements are removed.
data "aws_iam_policy_document" "maybe_empty" {
# statement {
# actions = [ "ssm:SendCommand" ]
# resources = [ "*" ]
# }
}
resource "aws_iam_policy" "example" {
name = "example"
policy = data.aws_iam_policy_document.maybe_empty.json
}
With an empty statement, the state file terraform state show data.aws_iam_policy_document.maybe_empty
will have the policy for both resources set to:
{
"Version": "2012-10-17",
"Statement": null
}
On the next plan, when trying to update and compare a policy already applied to a new one that has no statement or path configured, that policy will be read, but will fail with Error: while setting policy (), encountered: Error parsing 1 policy: Unknown error parsing statement
.
Solution:
The IAM policy needs to be removed from the state file and re-imported, and the policy document needs at least one statement.
- Connect to the
remote
backend - Run
terraform init
to initialize the working directory and allow Terraform to copy theremote
state locally. - Locate the resource and run
terraform state rm aws_iam_policy.$policy_name
to remove the resource from the Terraform state file. - Locate the resource
aws_iam_policy_document
and runterraform state rm data.aws_iam_policy_document.$policy_name
to remove the resource from the Terraform state file. - Ensure that the policy document has a statement in it.
- Run
terraform import
to import both resources back into the state file. - Run
terraform plan
andterraform apply
.