地形资源块中不同块内的条件流

时间:2019-02-04 12:07:32

标签: google-cloud-platform terraform

我正在尝试创建一个Terraform脚本,该脚本需要用户输入并相应地执行。我基本上想问用户是否要在Google云平台中使用静态IP,如果可以,则相应地将资源“ google_compute_instance”缝合起来,否则,就放手吧。

分享我编写的代码:

variable "create_eip" {
  description = "Enter 1 for true, 0 for false"
}

resource "google_compute_address" "external" {
  count = "${var.create_eip}"
  name = "external-ip",
  address_type = "EXTERNAL",
}

resource "google_compute_instance" "compute-engine" {
  name = "random",
  machine_type = "f1-micro",
  boot_disk {
    initialize_params {
      size = "10",
      type = "pd-ssd",
      image = "${data.google_compute_image.image.self_link}"
    }
   }
  network_interface {
    subnetwork = "default",
        access_config {
              nat_ip = "${google_compute_address.external.address}"
   }
 }
}

我在这里遇到的错误是,当用户输入0作为输入时,代码控件仍然转到“ nat_ip =“ $ {google_compute_address.external.address}”“

因为出现此错误,所以:

  
      
  • google_compute_instance.compute-engine:找不到变量的资源“ google_compute_address.external”   “ google_compute_address.external.address”。
  •   

我也通过替换

尝试过这种方式
nat_ip = "${var.create_eip == "1" ? "${google_compute_address.external.address}" : ""}"

(如果create_ip = 1,则执行“ google_compute_address.external.address”,否则不执行任何操作。)

但是它没有按预期工作。

1 个答案:

答案 0 :(得分:0)

这是Terraform的问题...

除了计数之外,您真的不能做if。

您可以尝试类似的操作,因为暂时无法在资源中放置条件:

variable "create_eip" {
  description = "Enter 1 for true, 0 for false"
}

resource "google_compute_address" "external" {
  count = "${var.create_eip}"
  name = "external-ip",
  address_type = "EXTERNAL",
}

resource "google_compute_instance" "compute-engine-ip" {
  count = "${var.create_eip == 1 ? 1 : 0}"
  name = "random",
  machine_type = "f1-micro",
  boot_disk {
    initialize_params {
      size = "10",
      type = "pd-ssd",
      image = "${data.google_compute_image.image.self_link}"
    }
   }
  network_interface {
    subnetwork = "default",
        access_config {
              nat_ip = "${google_compute_address.external.address}"
   }
 }
}

resource "google_compute_instance" "compute-engine" {
  count = "${var.create_eip == 1 ? 0 : 1}"
  name = "random",
  machine_type = "f1-micro",
  boot_disk {
    initialize_params {
      size = "10",
      type = "pd-ssd",
      image = "${data.google_compute_image.image.self_link}"
    }
   }
  network_interface {
    subnetwork = "default",
        access_config {
   }
 }
}

如果变量值是一个,则此代码将使用创建的ip创建一个计算实例,在另一种情况下,它将创建一个ip,如果要在compute_address资源上保留相同的ip,也可以添加生命周期:

lifecycle = {
  ignore_changes = ["node_pool"]
}