amazon-web-services - 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.
解决方案
动态块的名称必须与要创建的块的名称匹配,并且在块内名称必须是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
块,就像您手动键入它们一样。
推荐阅读
- python - 计算单元格为列表的熊猫数据框的平均值
- swift - 为什么我不应该用序列对象制作我的自定义结构?
- xml - kotlin中的Websocket连接?
- javascript - Chrome 问题 - 通过单击 URL 打开移动短信应用
- ios - Swift CGVector 不一致
- .net-core - 我可以在 .Net MVC Core Web 应用程序中创建多个项目吗
- javascript - 以匀速圆周运动同时拖动元素
- google-bigquery - BigQuery 加载作业因权限问题而失败
- javascript - Cannot read property CSS undefined
- google-apps-script - 如何根据单元格值查找特定行并将当前日期插入该行的单元格