当 for_each 为空时,忽略动态资源

when for_each empty, ignore dynamic resource

我的 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"
    }
  }
}

当 var.policy_statements 为空列表或什么都没有时 运行 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" {

var.policy_statements 为空时,该政策似乎仍在 aws_iam_policy.task_role 资源中引用。

这会导致创建 aws_iam_policy.task_role 时带有空的 Statement(这会导致您看到的格式错误的策略错误)。

我建议在策略本身上设置一个 count 标志,这样它甚至不会在语句为空时尝试创建它,例如

resource "aws_iam_policy" "task_role" {
  count = length(var.policy_statements) == 0 ? 0 : 1

  // Your other args here...
}

这可能会对其他资源(例如消耗 aws_iam_policy.task_role 的资源)产生级联效应。您需要通过提供不会中断的默认值或在其中添加 count 来处理这些影响。