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

Dynamic network interface for Compute Instance module

我们有创建 compute_instance.
的 Terraform 模块 某些实例应该获得 public IP。
Public 在 network_interface 下定义 "access_config {}" 属性 时创建的 IP:

network_interface {
  network = "default"
  access_config {

  }
}

我们尝试动态注入网络接口和 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,有哪些替代方案?

在您的 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