循环使用 for 或 For_each |地形 0.12

Looping using for or For_each | Terraform 0.12

我需要在网络内的 GCP 中创建多个子网。我计划使用 Terraform 0.12 语法,如下所示:

project_name = [ 
    "order-dev",
    "ship-dev"
]

variable "project_name" {
  type        = list(string)
  description = "Name of the project"
}

resource "google_compute_subnetwork" "subnetwork" {

  name          = "${var.project_name}-subnetwork"
  ip_cidr_range = var.subnet_ip_cidr_range
  region        = var.region
  network       = google_compute_network.network.self_link
}

在这种情况下是否可以使用 forfor_each 表达式,我知道使用元素并做这个。但如果可能,想尝试不同的方法吗?

尝试使用 count 元参数

用你的样本,像这样

project_name = [ 
    "order-dev",
    "ship-dev"
]

variable "project_name" {
  type        = list(string)
  description = "Name of the project"
}

resource "google_compute_subnetwork" "subnetwork" {
  count         = length(var.project_name)
  name          = "${var.project_name[count.index]}-subnetwork"
  ip_cidr_range = var.subnet_ip_cidr_range
  region        = var.region
  network       = google_compute_network.network.self_link
}

另一种选择是 for_each 键值对,但您只能访问一个值,我认为您不能像示例那样使用列表变量。

resource "google_compute_subnetwork" "subnetwork" {
  for_each = {
    order = "order-dev"
    ship = "ship-dev"
  }
  name          = "${key.value}-subnetwork"
  ip_cidr_range = var.subnet_ip_cidr_range
  region        = var.region
  network       = google_compute_network.network.self_link
}

资源:

https://www.terraform.io/docs/configuration/resources.html#count-multiple-resource-instances-by-count https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9 https://www.terraform.io/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings

variable "project_name" {
  type = set(string)
}

resource "google_compute_subnetwork" "subnetwork" {
  for_each = var.project_name

  name          = "${each.key}-subnetwork"
  ip_cidr_range = var.subnet_ip_cidr_range
  region        = var.region
  network       = google_compute_network.network.self_link
}