1

我正在通过构建模板来学习 terraform,以在 hetzner 云中创建我的基础架构。为此,我使用了 hcloud 提供程序。

我创建了一个映射变量hosts来创建 >1 个具有不同配置的服务器。

variable "hosts" {
    type = map(object({
        name                    = string
        serverType              = string
        serverImage             = string
        serverLocation          = string
        serverKeepDisk          = bool
        serverBackup            = bool 
        ip                      = string
      }))
    }

这工作正常。但我还需要配置卷。我只需要 2 台服务器的附加卷,并且 terraform 必须检查可变卷是否为真。如果为 true,则应创建具有给定详细信息的新卷并将其附加到服务器。为此,我编辑了我的变量hosts

variable "hosts" {
    type = map(object({
        name                    = string
        serverType              = string
        serverImage             = string
        serverLocation          = string
        serverKeepDisk          = bool
        serverBackup            = bool 
        ip                      = string

        volume                  = bool
        volumeName              = string
        volumeSize              = number
        volumeFormat            = string
        volumeAutomount         = bool
        volumeDeleteProtection  = bool
      }))
    }

在 main.tf 中,volume 块看起来像这样,但它不起作用,因为 for_each 和 count 不能一起使用。我怎样才能得到我正在寻找的东西?那可能吗?

resource "hcloud_volume" "default" {
  for_each          = var.hosts
  count             = each.value.volume ? 1 : 0
  name              = each.value.volumeName
  size              = each.value.volumeSize
  server_id         = hcloud_server.default[each.key].id
  automount         = each.value.volumeAutomount
  format            = each.value.volumeFormat
  delete_protection = each.value.volumeDeleteProtection
}
4

1 回答 1

1

前一个迭代元参数count不会为您提供您需要的功能,因为您需要在地图volume的每次var.hosts迭代中访问 bool 类型。为此,您可以在元参数的for表达式中添加条件。for_each

for_each = { for host, values in var.hosts: host => values if values.volume }

这将为for_each元参数的值构建一个映射。它将包含对象键所在var.hosts的每个键值对。volumetrue

看起来这很适合转换和类型并存在于许多其他语言中的方法collectmap函数,但这些在 Terraform 中尚不存在。因此,我们使用表达式 lambda 等价物。listmapfor

于 2022-01-14T22:41:03.017 回答