Search code examples
terraformterraform-provider-aws

when for_each empty, ignore dynamic resource


I have the following in my main.tf:

data "aws_iam_policy_document" "task_role_policy" {
  dynamic "statement" {
    for_each = var.policy_statements
    content {
      actions   = statement.value.actions
      resources = statement.value.resources
      effect    = "Allow"
    }
  }
}

When var.policy_statements is empty list or nothing I get the following error when running terraform apply:

Error: Error creating IAM policy dev-chatbot-engine-policy: MalformedPolicyDocument: Syntax errors in policy.
    status code: 400, request id: a181b065-b659-4261-87d5-9aae8c4454aa

  on .terraform/modules/service/main.tf line 68, in resource "aws_iam_policy" "task_role":
  68: resource "aws_iam_policy" "task_role" {

Solution

  • It looks like this policy is still being reference in the aws_iam_policy.task_role resource when var.policy_statements is empty.

    This would cause aws_iam_policy.task_role to be created with an empty Statement (which causes that malformed-policy error you are seeing).

    I would recommend setting a count flag on the policy itself so that it doesn't even attempt to create it when the statements are empty, e.g.

    resource "aws_iam_policy" "task_role" {
      count = length(var.policy_statements) == 0 ? 0 : 1
    
      // Your other args here...
    }
    

    This may have cascading effects to other resources (such as those that consume aws_iam_policy.task_role). You'll need to handle those effects by providing defaults that don't break or adding a count there as well.