【问题标题】:Terraform iterate over map and create nested resourcesTerraform 遍历地图并创建嵌套资源
【发布时间】:2021-09-08 22:27:10
【问题描述】:

我正在尝试遍历地图并在 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-services terraform infrastructure-as-code


    【解决方案1】:

    动态块的名称必须与要创建的块的名称匹配,并且在块内名称必须是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 块,就像您手动键入它们一样。

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2016-10-14
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多