如何for_each
为以下内容进行循环?
我想创建一个tfe_variable
node_count
& vm_size
。我需要这两个 tfe_variableswksp1
和wksp2
variable "custom_variables" {
type = map(object({
node_count = number
vm_size = string
}))
default = {
wksp1 = {
node_count = 2
vm_size = "Standard_D2_v3"
},
wksp2 = {
node_count = 5
vm_size = "Standard_D2_v5"
}
}
}
resource "tfe_variable" "custom" {
for_each = {
# for each workspace & variable in var.custom_variables create a tfe_variable
}
key = each.value.name
value = each.value.value
category = "terraform"
workspace_id = each.value.workspace_id
}
Run Code Online (Sandbox Code Playgroud)
你真的很接近!以下是需要考虑的几件事:
选项 1:多种tfe_variable
资源
tfe_variable
为每个要创建的变量创建一个资源custom_variables
映射中的键是工作区 ID。variable "custom_variables" {
type = map(object({
node_count = number
vm_size = string
}))
default = {
wksp1_id = {
node_count = 2
vm_size = "Standard_D2_v3"
},
wksp2_id = {
node_count = 5
vm_size = "Standard_D2_v5"
}
}
}
resource "tfe_variable" "node_count" {
for_each = var.custom_variables
key = "node_count"
value = each.value.node_count
category = "terraform"
workspace_id = each.key
}
resource "tfe_variable" "vm_size" {
for_each = var.custom_variables
key = "vm_size"
value = each.value.vm_size
category = "terraform"
workspace_id = each.key
}
Run Code Online (Sandbox Code Playgroud)
此选项的缺点是您需要为每个变量提供额外的资源。
选项 2:变量对象列表
count
迭代列表variable "custom_variables" {
type = list(object({
key = string
value = string
workspace_id = string
}))
default = [
{
key = "node_count"
value = "2"
workspace_id = "wksp1_id"
},
{
key = "node_count"
value = "5"
workspace_id = "wksp2_id"
},
{
key = "vm_size"
value = "Standard_D2_v3"
workspace_id = "wksp1_id"
},
{
key = "vm_size"
value = "Standard_D2_v5"
workspace_id = "wksp2_id"
}
]
}
resource "tfe_variable" "custom" {
count = length(var.custom_variables)
key = var.custom_variables[count.index].key
value = var.custom_variables[count.index].value
workspace_id = var.custom_variables[count.index].workspace_id
category = "terraform"
}
Run Code Online (Sandbox Code Playgroud)
这种方法也有一些缺点:
如果您在 Terraform 中的循环概念上遇到困难,这篇博文可能会对您有所帮助。
归档时间: |
|
查看次数: |
6397 次 |
最近记录: |