sok*_*ata 6 terraform terraform-template-file hcloud
我正在通过构建一个模板来在 Hetzner 云中创建我的基础设施来学习 terraform。为此,我使用 hcloud 提供商。
我创建一个映射变量主机来创建> 1个具有不同配置的服务器。
variable "hosts" {
type = map(object({
name = string
serverType = string
serverImage = string
serverLocation = string
serverKeepDisk = bool
serverBackup = bool
ip = string
}))
}
Run Code Online (Sandbox Code Playgroud)
这工作正常。但我还需要配置卷。我只需要 2 个服务器额外的卷,并且 terraform 必须检查变量卷是否为真。如果为 true,则应创建具有给定详细信息的新卷并将其附加到服务器。为此,我编辑我的变量主机:
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
}))
}
Run Code Online (Sandbox Code Playgroud)
在 main.tf 中,卷块看起来像这样,但它不起作用,因为 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
}
Run Code Online (Sandbox Code Playgroud)
前一个迭代元参数count不会为您提供此处所需的功能,因为您需要在映射中的volume每次迭代中访问 bool 类型。var.hosts为此,您可以在元参数for内的表达式中添加条件。for_each
for_each = { for host, values in var.hosts: host => values if values.volume }
Run Code Online (Sandbox Code Playgroud)
for_each这将为元参数的值构建一个映射。它将包含对象键var.hosts为 的每个键值对。volumetrue
这似乎非常适合在许多其他语言中进行转换和类型化的collectormap方法或函数,但这些在 Terraform 中尚不存在。因此,我们使用lambda 等价表达式。listmapfor
| 归档时间: |
|
| 查看次数: |
17853 次 |
| 最近记录: |