我正在尝试创建一个可创建计算实例的terraform模块。当且仅当模块调用期间将变量attached_disk_enabled
设置为true
时,我才希望资源具有连接的磁盘。我有这个:
resource "google_compute_disk" "my-disk" {
name = "data"
type = "pd-ssd"
size = 20
count = var.attached_disks_enabled ? 1 : 0
}
resource "google_compute_instance" "computer" {
name = "computer"
boot_disk {
...
}
// How do I make this disappear if attached_disk_enabled == false?
attached_disk {
source = "${google_compute_disk.my-disk.self_link}"
device_name = "computer-disk"
mode = "READ_WRITE"
}
}
已在vars.tf
中为模块声明了变量。模块调用是这样的:
module "main" {
source = "../modules/computer"
attached_disk_enabled = false
...
}
我了解动态块,以及如何使用for
循环遍历列表并设置多个块,但是我不确定如何使用此方法从资源中排除一个块:
dynamic "attached-disk" {
for_each in var.disk_list
content {
source = "${google_compute_disk.my-disk.*.self_link}"
device_name = "computer-disk-${count.index}"
mode = "READ_WRITE"
}
}
我要用if
代替for_each
。有没有办法做到这一点?
$ terraform version
Terraform v0.12.0
答案 0 :(得分:0)
由于磁盘资源已经附加了条件,因此您可以将该资源的结果用作迭代器,从而避免再次指定条件:
dynamic "attached_disk" {
for_each = google_compute_disk.my-disk
content {
source = attached_disk.value.self_link
device_name = "computer-disk-${attached_disk.key}"
mode = "READ_WRITE"
}
}
要回答一个普遍的问题:如果您需要条件块,则答案是编写一个条件表达式,该条件表达式返回单项列表或空列表:
dynamic "attached_disk" {
for_each = var.attached_disk_enabled ? [google_compute_disk.my-disk[0].self_link] : []
content {
source = attached_disk.value
device_name = "computer-disk-${attached_disk.key}"
mode = "READ_WRITE"
}
}
但是,在您的特定情况下,我希望使用前者,因为前者更直接地描述了意图(“附加每个磁盘”)。