'Looking for iteration logic for GCP Subnetwork creation using Terraform
Trying to create GCP subnetwork for 2 regions using terraform module. use case will be we may create either of the region subnet one time or both regions subnets along with secondary ranges (not all the time and can be more than one secondary range within same subnet). Like,
- one region (from 2 regions) subnet at a time without secondary range.
- both regions subnet at a time without secondary range.
- one region (from 2 regions) subnet at a time with one or more secondary range.
- both regions subnet at a time with one or more secondary ranges.
below code hasrestriction to use count and for_each on same resource. planning to add another resource block for central region as well in same main.tf
**main.tf file**
resource "google_compute_subnetwork" "subnet_east4" {
count = "${var.npe_subnet_east4_enable ? 1 : 0}"
name = "${var.npe_subnet_name_east4}"
ip_cidr_range = "${var.npe_cidr_range_east4}"
network = "${var.npe_vpc_name_east4}"
region = "${var.npe_region_east4}"
private_ip_google_access = "true"
for_each = var.npe_secondary_subnets_east4
secondary_ip_range {
range_name = each.value["npe_east4_subnet_pod_range_name"]
ip_cidr_range = each.value["npe_east4_subnet_pod_ip_cidr_range"]
}
secondary_ip_range {
range_name = each.value["npe_east4_subnet_service_range_name"]
ip_cidr_range = each.value["npe_east4_subnet_service_ip_cidr_range"]
}
**variable.tf file**
variable "npe_secondary_subnets_east4" {
type = map(object({
npe_east4_subnet_pod_range_name = string
npe_east4_subnet_pod_ip_cidr_range = string
npe_east4_subnet_service_range_name = string
npe_east4_subnet_service_ip_cidr_range = string
}))
description = "Secondary subnets"
}
Please suggest some alternate logic here
Solution 1:[1]
count is not necessary, you can use a conditional expression in your for_each:
for_each = var.npe_subnet_east4_enable ? var.npe_secondary_subnets_east4 : {}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maxime |
