3

我正在尝试创建一个创建计算实例的 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 
4

1 回答 1

3

因为您的磁盘资源已经附加了条件,您可以使用该资源的结果作为您的迭代器,从而避免再次指定条件:

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"
  }
}

但是,在您的特定情况下,我更喜欢前者,因为它更直接地描述了意图(“附加每个磁盘”)。

于 2019-06-06T16:30:43.703 回答