Blog

Simplifying Google Cloud IP Management with Terraform

29 Jan, 2023
Xebia Background Header Wave

Managing IP addresses in Google Cloud can be a tedious and error-prone process, especially when relying on static IP addresses. This is where the google_netblock_ip_ranges data source comes in, simplifying the process of managing IPs in Google Cloud.

The challenge of hardcoded IP addresses

Hardcoded static IP addresses are a common issue in Terraform configurations. For instance, many configurations permit inbound health checks from GCP Load Balancers using hardcoded IPs declared as locals or variables. However, this approach is both error-prone and time-consuming as it requires constant monitoring for changes made by Google.

# These are the source IP ranges for health checks (managed by Google Cloud)
source_ranges = ["35.191.0.0/16", "130.211.0.0/22", "209.85.152.0/22", "209.85.204.0/22"]

This approach is error-prone and requires significant time and effort, as you must continually monitor for any changes made by Google.

The solution – automate IP range tracking

The google_netblock_ip_ranges data source generates a list of Google-managed CIDR ranges that correspond to Google Cloud’s infrastructure, automating the process of tracking IP range changes.

Using google_netblock_ip_ranges

When declaring the google_netblock_ip_ranges data source you set the range_type to the type of range you need.

data "google_netblock_ip_ranges" "this" {
  for_each = toset([
    "health-checkers",
    "legacy-health-checkers",
  ])
  range_type = each.key
}

Next, the firewall rule uses the CIDR ranges as its source ranges.

resource "google_compute_firewall" "lb_health_check" {
  name        = "my-firewall-rule"
  description = "Rule that allows inbound Google Load Balancer health checks"
  direction   = "INGRESS"
  network     = "default"
  allow {
    protocol = "tcp"
  }
  source_ranges = distinct(concat(
    data.google_netblock_ip_ranges.this["health-checkers"].cidr_blocks_ipv4,
    data.google_netblock_ip_ranges.this["legacy-health-checkers"].cidr_blocks_ipv4,
  ))
  project     = "my-project-name"
}

With Terraform’s google_netblock_ip_ranges data source, managing IP addresses in Google Cloud is now easier, faster, and less error-prone. Say goodbye to the hassle of hardcoded IP addresses and hello to a simplified Google Cloud IP management process.

Bruno Schaatsbergen
Bruno is an open-source and serverless enthusiast. He tends to enjoy looking for new challenges and building large scale solutions in the cloud. If he's not busy with cloud-native architecture/development, he's high-likely working on a new article or podcast covering similar topics. In his spare time he fusses around on Github or is busy drinking coffee and exploring the field of cosmology.
Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts