skip to content
Marcin's Image Marcin's Blog

How to use Terraform module to for GCP load balancer

/ 2 min read

How to use Terraform module

My rule of a thumb to create Terraform module is when I need to repeat myself more than 3 times. Here are my notes on how to create a simple Terraform module for two resources which you need to keep defining for each backend google_compute_region_network_endpoint_group and google_compute_backend_service.

Create a module

Module structure in sub-folder: ./modules/backend:

modules/backend/main.tf
data "google_cloud_run_service" "run" {
  name     = var.run_service_name
  location = var.region
}

resource "google_compute_region_network_endpoint_group" "network_endpoint_group" {
  name   = var.run_service_name
  region = var.region
  network_endpoint_type = "SERVERLESS"
  cloud_run {
      service = data.google_cloud_run_service.run.name
  }
}

resource "google_compute_backend_service" "service" {
  name = var.run_service_name
  load_balancing_scheme = "EXTERNAL_MANAGED"
  protocol = "HTTPS"
  port_name = "http"
  backend {
     group = google_compute_region_network_endpoint_group.network_endpoint_group.self_link
  }
}

So it requires two variables region and run_service_name:

modules/backend/variables.tf
variable "run_service_name" {}
variable "region" {}

Finally, it also requires one output which can be used later in google_compute_url_map:

modules/backend/outputs.tf
output "backend_service" {
  value = google_compute_backend_service.service
}

How to use the module.

Old code:

main-before.tf
resource "google_compute_region_network_endpoint_group" "bar" {
  //...
}

resource "google_compute_backend_service" "foo" {
  //...
}

New code:

main-after.tf
module "backend" {
  source = "./modules/backend"
  region = var.region
  run_service_name = var.run_service_name
}

moved {
  from = google_compute_region_network_endpoint_group.bar
  to   = module.backend.google_compute_region_network_endpoint_group.network_endpoint_group
}

moved {
  from = google_compute_backend_service.foo
  to   = module.backend.google_compute_backend_service.service
}

Before you can use module you need to run terraform init. If all is good terraform plan should notice items moved and no changes should be proposed.