How do I reference the secondary ranges in Terraform code?

1.3k Views Asked by At

I'm trying to reference secondary ranges in another resource:

resource "google_compute_subnetwork" "mysubnetwork" {
  name          = "mysubnetwork"
  ....
  secondary_ip_range {
    range_name    = "mysecondary"
    ip_cidr_range = "10.0.0.0/24"
  }
  ....

resource "google_container_cluster" "my-cluster" {
....
ip_allocation_policy{
    cluster_secondary_range_name = <reference my existing secondary ranges>
    services_secondary_range_name = <reference my existing secondary ranges>
}

Tried this: google_compute_subnetwork.mysubnetwork.secondary_ip_range.range_name["mysecondary"]

but got This value does not have any attributes.

I tried this: google_compute_subnetwork.mysubnetwork.secondary_ip_range.range_name.mysecondary

but got the same error.

1

There are 1 best solutions below

0
On BEST ANSWER

This is convoluted and I havent tested yet but seem like it will work- will I run into issues with this? Want to know if there is a preferable way. For clarity it should be obvious what range is being referenced (so not using an index number)

variable "vpc_secondary_ip_ranges" {
  type = map(object({
    secondary_range = object({
      range_name = string
      ip_cidr_range = string
    })
  }))
  default = {
    gke-pods = {
      secondary_range = {
        range_name = "gke-pods"
        ip_cidr_range = "10.1.0.0/14"
      }
    }
    gke-services = {
      secondary_range = {
        range_name = "gke-services"
        ip_cidr_range = "10.2.2.0/24"
      }
    }
  }
}

// flatten for secondary_ip_range parameter
resource "google_compute_subnetwork" "bombora-default-subnetwork-us-west1" {
  secondary_ip_range = [for r in var.vpc_secondary_ip_ranges : r.secondary_range]
  ...

...
resource "google_container_cluster" "mycluster" {
  // index into map for names of secondaries for ip_allocation_policy
  ip_allocation_policy {
    cluster_secondary_range_name = var.vpc_secondary_ip_ranges.gke-pods.secondary_range.range_name
    services_secondary_range_name = var.vpc_secondary_ip_ranges.gke-services.secondary_range.range_name
  }
....