计算实例模块的动态网络接口

时间:2019-03-24 15:48:31

标签: google-cloud-platform terraform gcloud

我们有Terraform模块,用于创建compute_instance。
有些实例应该获得公共IP。
在network_interface下定义“ access_config {}”属性时创建的公用IP:

network_interface {
  network = "default"
  access_config {

  }
}

我们尝试动态注入网络接口和来自 调用此模块的“ production / Main.tf”:

module "arbiter" {
  source                = "../modules/compute"
  name                  = "arbiter"
  machine_type          = "custom-1-2048"
  zones                 = ["europe-west2-a"]
  tags                  = ["mongo-db"]
  metadata              = {
    sshKeys             = "${var.ssh_user}:${file("ssh-keys/main.rsa.pub")}"
  }
  network_interface = { -> this line is worng
    network = "default"
  }
}

如何将动态对象注入network_interface属性?
如果没有,Terraform是否可以解决?有哪些替代方案?

1 个答案:

答案 0 :(得分:1)

在您的arbiter模块中,执行以下操作:

variable "external_ip" {
  description = "Controls if VM gets external IP"
  default     = false
}

locals {
  access_config = {
    "0" = []
    "1" = [{}]
  }
}

resource "google_compute_instance" "arbiter" {
  name         = "${var.name}"
  machine_type = "${var.type}"
  zone         = "${var.zones}"
  tags         = "${var.tags}"
  metadata     = "${var.metadata}"

  boot_disk {
    initialize_params {
      image = "some/image"
    }
  }

  network_interface {
    network = "default"

    access_config = "${local.access_config[var.external_ip]}"
  }
}

然后,在使用模块时,您可以指定external_ip变量以指示应该可以从Internet访问VM。

module "arbiter" {
  source       = "../modules/compute"
  name         = "arbiter"

  machine_type = "custom-1-2048"
  zones        = ["europe-west2-a"]
  tags         = ["mongo-db"]

  metadata = {
    sshKeys = "${var.ssh_user}:${file("ssh-keys/main.rsa.pub")}"
  }

  external_ip = true
}

有关Terraform和null值技巧的更多详细信息:Null values in Terraform v0.11.x