Managing Load Balancing with Terraform

Learn how to set up and manage Google Cloud Load Balancing using Terraform

In this guide, we’ll explore how to manage Google Cloud Load Balancing using Terraform.

Video Tutorial

Learn more about managing Google Cloud Load Balancing with Terraform in this comprehensive video tutorial:

Prerequisites

  • Google Cloud SDK installed and configured
  • Terraform installed (version 1.0.0 or later)
  • A GCP project with billing enabled

Project Structure

.
├── main.tf                   # Main Terraform configuration file
├── variables.tf              # Variable definitions
├── outputs.tf               # Output definitions
├── terraform.tfvars         # Variable values
└── modules/
    └── loadbalancer/
        ├── main.tf          # Load Balancer specific configurations
        ├── variables.tf      # Module variables
        ├── forwarding.tf    # Forwarding rule configurations
        └── outputs.tf       # Module outputs

Provider Configuration

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 4.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}

Variables

variable "project_id" {
  description = "The ID of the GCP project"
  type        = string
}

variable "region" {
  description = "The region to deploy resources to"
  type        = string
  default     = "us-central1"
}

variable "lb_name" {
  description = "Name of the load balancer"
  type        = string
}

HTTP(S) Load Balancer Configuration

# Reserved IP address
resource "google_compute_global_address" "default" {
  name = "${var.lb_name}-address"
}

# HTTP health check
resource "google_compute_health_check" "default" {
  name               = "${var.lb_name}-health-check"
  check_interval_sec = 5
  timeout_sec        = 5

  http_health_check {
    port = 80
  }
}

# Backend service
resource "google_compute_backend_service" "default" {
  name                  = "${var.lb_name}-backend"
  protocol              = "HTTP"
  port_name             = "http"
  load_balancing_scheme = "EXTERNAL"
  timeout_sec           = 30
  health_checks        = [google_compute_health_check.default.id]

  backend {
    group = google_compute_instance_group_manager.default.instance_group
  }
}

# URL map
resource "google_compute_url_map" "default" {
  name            = "${var.lb_name}-url-map"
  default_service = google_compute_backend_service.default.id
}

# HTTP proxy
resource "google_compute_target_http_proxy" "default" {
  name    = "${var.lb_name}-http-proxy"
  url_map = google_compute_url_map.default.id
}

# Forwarding rule
resource "google_compute_global_forwarding_rule" "default" {
  name                  = "${var.lb_name}-forwarding-rule"
  ip_protocol           = "TCP"
  load_balancing_scheme = "EXTERNAL"
  port_range            = "80"
  target                = google_compute_target_http_proxy.default.id
  ip_address            = google_compute_global_address.default.address
}

Instance Template and Group

resource "google_compute_instance_template" "default" {
  name        = "${var.lb_name}-template"
  description = "Template for web server instances"

  tags = ["http-server"]

  machine_type = "e2-medium"

  disk {
    source_image = "debian-cloud/debian-11"
    auto_delete  = true
    boot         = true
  }

  network_interface {
    network = "default"
    access_config {
      // Ephemeral IP
    }
  }

  metadata_startup_script = <<-EOF
    #!/bin/bash
    apt-get update
    apt-get install -y nginx
    service nginx start
    EOF
}

resource "google_compute_instance_group_manager" "default" {
  name = "${var.lb_name}-igm"
  zone = "${var.region}-a"

  version {
    instance_template = google_compute_instance_template.default.id
    name             = "primary"
  }

  named_port {
    name = "http"
    port = 80
  }

  base_instance_name = "${var.lb_name}-vm"
  target_size        = 2
}

resource "google_compute_autoscaler" "default" {
  name   = "${var.lb_name}-autoscaler"
  zone   = "${var.region}-a"
  target = google_compute_instance_group_manager.default.id

  autoscaling_policy {
    max_replicas    = 5
    min_replicas    = 2
    cooldown_period = 60

    cpu_utilization {
      target = 0.7
    }
  }
}

SSL Configuration (Optional)

resource "google_compute_ssl_certificate" "default" {
  name        = "${var.lb_name}-cert"
  private_key = file("path/to/private.key")
  certificate = file("path/to/certificate.crt")
}

resource "google_compute_target_https_proxy" "default" {
  name             = "${var.lb_name}-https-proxy"
  url_map          = google_compute_url_map.default.id
  ssl_certificates = [google_compute_ssl_certificate.default.id]
}

Outputs

output "load_balancer_ip" {
  value       = google_compute_global_address.default.address
  description = "The IP address of the load balancer"
}

output "backend_service_name" {
  value       = google_compute_backend_service.default.name
  description = "The name of the backend service"
}

output "url_map_name" {
  value       = google_compute_url_map.default.name
  description = "The name of the URL map"
}

Best Practices

  1. Load Balancing:

    • Choose appropriate scheme
    • Configure health checks
    • Implement SSL/TLS
    • Use proper backends
  2. Security:

    • Use SSL certificates
    • Configure firewall rules
    • Monitor access logs
    • Regular security audits
  3. Performance:

    • Configure autoscaling
    • Monitor metrics
    • Optimize backend
    • Use CDN when needed
  4. Cost Optimization:

    • Monitor traffic
    • Right-size instances
    • Use preemptible VMs
    • Regular review

Common Operations

Creating Resources

terraform init
terraform plan
terraform apply

Testing Load Balancer

curl http://<load-balancer-ip>

Best Practices and Tips

  1. Load Balancer Management:

    • Monitor health checks
    • Configure logging
    • Set up alerts
    • Regular maintenance
  2. Security:

    • Keep certificates updated
    • Review access patterns
    • Monitor threats
    • Regular updates
  3. Operations:

    • Monitor performance
    • Track metrics
    • Implement logging
    • Regular backups

Conclusion

You’ve learned how to set up and manage Google Cloud Load Balancing using Terraform. This setup provides:

  • High availability
  • Scalable infrastructure
  • Secure load balancing
  • Best practices implementation