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