Issue creating firewall rules via terraform (google provider)

502 views Asked by At

I am trying to create firewall rule via terraform (using google provider). However struggling to pull external_ipv6_prefix from subnetwork. This is my code

data "google_compute_network" "vpc" {
  name    = "my-vpc"
  project = "my-project"
}

data "google_compute_subnetwork" "subnetwork" {
  for_each  = toset(data.google_compute_network.vpc.subnetworks_self_links)
  self_link = each.value
}
resource "google_compute_firewall" "composer-firewall-rule" {
  name        = "allow-egress-from-composer-control-plane"
  description = "Allow Egress traffic from k8 nodes to Control Plane"
  network     = data.google_compute_network.vpc
  project     = var.DEPLOY_PROJECT
  priority    = 980
  allow { protocol = "all" }
  direction     = "EGRESS"
  disabled      = false
  source_ranges = [data.google_compute_subnetwork.subnetwork.self_link.external_ipv6_prefix]
}

and I am getting following error

Error: Missing resource instance key │ │ on modules\firewall_rules\main.tf line 23, in resource "google_compute_firewall" "composer-firewall-r │ 23: source_ranges = [data.google_compute_subnetwork.subnetwork.self_link.external_ipv6_prefix] │ │ Because data.google_compute_subnetwork.subnetwork has "for_each" set, its attributes must be accessed o │ │ For example, to correlate with indices of a referring resource, use: │ data.google_compute_subnetwork.subnetwork[each.key]

Any idea how to loop through subnet & fetch all secondary ip's & then passing them to source_range in firewall rule ?

1

There are 1 answers

0
Dinesh On

This code worked for me. Thanks a lot Chris Doyle for pointing in right direction

data "google_compute_network" "vpc" {
  name    ="my-vpc"
  project = "my-project"
}

data "google_compute_subnetwork" "subnetwork" {
  for_each  = toset(data.google_compute_network.vpc.subnetworks_self_links)
  self_link = each.value
}

resource "google_compute_firewall" "composer-firewall-rule" {
  name        = "allow-egress-from-composer-control-plane"
  description = "Allow Egress traffic from k8 nodes to Control Plane"
  network     = data.google_compute_network.vpc.id
  project     = var.DEPLOY_PROJECT
  priority    = 980
  allow { protocol = "all" }
  direction          = "EGRESS"
  disabled           = false
  destination_ranges = flatten([for subnet in data.google_compute_subnetwork.subnetwork : [for ip_range in subnet.secondary_ip_range : ip_range.ip_cidr_range]]))
}