循环对象映射

Dar*_*Var 4 terraform

如何for_each为以下内容进行循环?

我想创建一个tfe_variable node_count& vm_size。我需要这两个 tfe_variableswksp1wksp2

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)

Ben*_*ley 5

你真的很接近!以下是需要考虑的几件事:

选项 1:多种tfe_variable资源

  1. tfe_variable为每个要创建的变量创建一个资源
  2. 确保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:变量对象列表

  1. 定义每个变量的键、值和工作区 ID 的列表
  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 中的循环概念上遇到困难,这篇博文可能会对您有所帮助。