【问题标题】:How can i set a count in for_each in terraform如何在 terraform 中的 for_each 中设置计数
【发布时间】:2023-03-15 03:43:01
【问题描述】:

我正在通过构建模板来学习 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
}

【问题讨论】:

    标签: terraform terraform-template-file hcloud


    【解决方案1】:

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

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

    这将为for_each 元参数的值构造一个映射。它将包含var.hosts 的每个键值对,其中volume 对象键为true

    看起来这很适合 collectmap 方法或函数,它转换 listmap 类型并存在于许多其他语言中,但这些在 Terraform 中尚不存在.因此,我们使用 for 表达式 lambda 等效项。

    【讨论】:

    • 谢谢你,马特。这是有效的。
    猜你喜欢
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2021-10-18
    • 2022-07-21
    • 2020-08-31
    • 2021-07-09
    • 2021-04-09
    相关资源
    最近更新 更多