首页 > 解决方案 > Terraform 遍历地图并创建嵌套资源

问题描述

我正在尝试遍历地图并在aws_codebuild_project. 这是我第一次在 Terraform 中使用循环。我的主要困惑是我不知道资源是否必须“支持”循环,或者是否可以在资源内的几乎所有地方进行迭代?

variable "custom_environment_variables" {
  type    = map(any)
  default = {}
}

resource "aws_codebuild_project" "my_project" {
  # other props...

  environment {
    type = "LINUX_CONTAINER"
    # more props

    # some hardcoded environment_variable
    environment_variable {
      name  = "APP_STAGE"
      value = var.app_stage
    }
    # some dynamic environment_variable
    dynamic "custom_environment_variable" {
      for_each = var.custom_environment_variables
      environment_variable {
        name  = custom_environment_variable.key
        value = custom_environment_variable.value
      }
    }
  }
}

此代码导致此错误:

│ Error: Unsupported block type
│ 
│   on ../modules/static_web_pipeline/main.tf line 155, in resource "aws_codebuild_project" "my_project":
│  155:     dynamic "custom_environment_variable" {
│ 
│ Blocks of type "custom_environment_variable" are not expected here.

标签: amazon-web-servicesterraforminfrastructure-as-code

解决方案


动态块的名称必须与要创建的块的名称匹配,并且在块内名称必须是content

dynamic "environment_variable" {
  for_each = var.custom_environment_variables
  content {
    name  = environment_variable.key
    value = environment_variable.value
  }
}

回答“我的主要困惑来源是我不知道资源是否必须“支持”循环,或者是否可以在资源内的几乎所有地方进行迭代?

不,资源不需要“支持”循环,但您仍然不能在任何地方迭代所有内容。您只能迭代块,并且由于资源支持块environment_variable,您可以使用动态块来创建多个environment_variable块。将迭代视为核心 terraform 功能,资源本身永远不会看到或知道迭代,资源只会看到多个 environment_variable块,就像您手动键入它们一样。


推荐阅读