如何在带有变量的 terraform GCP 上添加或删除 access_config

How to add or remove access_config on terraform GCP with variable

如何使用 GCP 在 Terraform 上添加或删除块代码 access_config { }

我有变量:

external_ip = false

如果外部 IP 值为 false 代码:


resource "google_compute_instance_from_template" "default_name_index" {
  name  = "${length(var.instances[change_with_index].instance_backup_ip) == 1 ? var.instances[change_with_index].instance_backup_name : format("%s-%s", var.instances[change_with_index].instance_backup_name, count.index + 1)}"
  count = length(var.instances[change_with_index].instance_backup_ip)

  source_instance_template = "projects/${var.provider_project}/global/instanceTemplates/${replace(var.instances[change_with_index].instance_name, "-app-image", "")}-${var.release_version}"

  network_interface {
    network    = var.instances[change_with_index].instance_network
    subnetwork = var.instances[change_with_index].instance_subnetwork
    network_ip = var.instances[change_with_index].instance_backup_ip[count.index]
    
  }
}

如果 external_ip 是值 true 代码:


resource "google_compute_instance_from_template" "default_name_index" {
  name  = "${length(var.instances[change_with_index].instance_backup_ip) == 1 ? var.instances[change_with_index].instance_backup_name : format("%s-%s", var.instances[change_with_index].instance_backup_name, count.index + 1)}"
  count = length(var.instances[change_with_index].instance_backup_ip)

  source_instance_template = "projects/${var.provider_project}/global/instanceTemplates/${replace(var.instances[change_with_index].instance_name, "-app-image", "")}-${var.release_version}"

  network_interface {
    network    = var.instances[change_with_index].instance_network
    subnetwork = var.instances[change_with_index].instance_subnetwork
    network_ip = var.instances[change_with_index].instance_backup_ip[count.index]
    
    #access_config will add in here
    access_config
    {
    }

  }
}

谢谢你的帮助。

您可以使用 dynamic blocksfor_each:

resource "google_compute_instance_from_template" "default_name_index" {
  name  = "${length(var.instances[change_with_index].instance_backup_ip) == 1 ? var.instances[change_with_index].instance_backup_name : format("%s-%s", var.instances[change_with_index].instance_backup_name, count.index + 1)}"
  count = length(var.instances[change_with_index].instance_backup_ip)

  source_instance_template = "projects/${var.provider_project}/global/instanceTemplates/${replace(var.instances[change_with_index].instance_name, "-app-image", "")}-${var.release_version}"

  network_interface {
    network    = var.instances[change_with_index].instance_network
    subnetwork = var.instances[change_with_index].instance_subnetwork
    network_ip = var.instances[change_with_index].instance_backup_ip[count.index]
    
    #access_config will add in here
    dynamic "access_config"    
    {
       for_each = external_ip == false ? [] : [1]
       content {
          // the normal content of access_config
       }
    }

  }
}