Skip to content

boozt-platform/terraform-google-traffic-director

GitHub Tag (latest SemVer) license Terraform Google Provider

Terraform Google Traffic Director

Terraform module for creating Google Cloud Traffic Director backend services with TCP proxy load balancing. This module is designed for service mesh architectures using Envoy sidecars with Managed Instance Groups (MIGs).

Table of Contents

Features

  • Traffic Director Integration - Creates INTERNAL_SELF_MANAGED backend services for use with Envoy proxies
  • Flexible Load Balancing - Supports ROUND_ROBIN, RING_HASH (sticky sessions), LEAST_REQUEST, and more
  • Circuit Breakers - Configurable connection limits to prevent cascade failures
  • Outlier Detection - Automatic ejection of unhealthy backends
  • Health Check Integration - Uses external health checks for backend monitoring

Architecture

flowchart TB
    subgraph Client
        E[Envoy Sidecar]
    end

    subgraph Traffic Director
        FR[Global Forwarding Rule<br/><i>INTERNAL_SELF_MANAGED</i>]
        TP[Target TCP Proxy]

        subgraph BS[Backend Service]
            CB[Circuit Breaker]
            OD[Outlier Detection]
            SA[Session Affinity]
        end
    end

    subgraph Backends
        IG1[Instance Group<br/><i>Backend 1</i>]
        IG2[Instance Group<br/><i>Backend 2</i>]
    end

    E --> FR
    FR --> TP
    TP --> BS
    BS --> IG1
    BS --> IG2
Loading

Prerequisites

The following Google Cloud APIs must be enabled on your project:

  • trafficdirector.googleapis.com - Traffic Director API
  • compute.googleapis.com - Compute Engine API

You can enable them using gcloud:

gcloud services enable trafficdirector.googleapis.com compute.googleapis.com

Or using Terraform:

resource "google_project_service" "trafficdirector" {
  service            = "trafficdirector.googleapis.com"
  disable_on_destroy = false
}

resource "google_project_service" "compute" {
  service            = "compute.googleapis.com"
  disable_on_destroy = false
}

Client IAM Permissions

Clients (e.g., VMs running Envoy sidecars) require the roles/trafficdirector.client role to fetch cluster configurations from Traffic Director. Without this role, Envoy cannot retrieve the list of available backend services.

resource "google_project_iam_member" "traffic_director_client" {
  project = "my-project"
  role    = "roles/trafficdirector.client"
  member  = "serviceAccount:my-vm-service-account@my-project.iam.gserviceaccount.com"
}

Usage

Basic Example (Round-Robin)

module "redis_read" {
  source = "github.com/boozt-platform/terraform-google-traffic-director?ref=v1.1.0"

  project_id = "my-project"
  network    = "default"
  name       = "redis-read"

  port_name  = "redis"
  port_range = "6379"

  health_check_id = google_compute_health_check.redis.id
  instance_groups = [
    google_compute_region_instance_group_manager.redis.instance_group
  ]

  locality_lb_policy = "ROUND_ROBIN"
  timeout_sec        = 2
}

Sticky Sessions (Write Operations)

module "redis_write" {
  source = "github.com/boozt-platform/terraform-google-traffic-director?ref=v1.1.0"

  project_id = "my-project"
  network    = "default"
  name       = "redis-write"

  port_name  = "redis"
  port_range = "16379"

  health_check_id = google_compute_health_check.redis.id
  instance_groups = [
    google_compute_region_instance_group_manager.redis.instance_group
  ]

  # Sticky session configuration
  session_affinity   = "CLIENT_IP"
  locality_lb_policy = "RING_HASH"

  timeout_sec                     = 5
  connection_draining_timeout_sec = 10
  max_connections_per_instance    = 1000

  circuit_breakers = {
    max_connections = 1024
  }

  outlier_detection = {
    consecutive_errors = 5
    interval = {
      seconds = 10
    }
    base_ejection_time = {
      seconds = 30
    }
  }
}

Requirements

Name Version
terraform >= 1.3.0
google >= 4.50.0, < 8.0.0

Providers

Name Version
google >= 4.50.0, < 8.0.0

Inputs

Name Description Type Default Required
health_check_id The ID (self_link) of an externally created health check resource. string n/a yes
instance_groups A list of instance group URLs (self_links) to be used as backends. list(string) n/a yes
name The base name for resources. Suffixes will be added (e.g., '-bs' for backend service, '-proxy' for TCP proxy). string n/a yes
network The VPC network name or self_link to which resources will be attached. string n/a yes
port_name The named port on the instance group (must match a named_port defined on the MIG). string n/a yes
port_range The port range for the forwarding rule (e.g., '6379' or '8080-8090'). string n/a yes
project_id The ID of the GCP project in which to provision resources. string n/a yes
balancing_mode The balancing mode for backends. Use 'CONNECTION' for TCP traffic. string "CONNECTION" no
circuit_breakers Circuit breaker configuration for the backend service.
object({
max_connections = optional(number)
max_pending_requests = optional(number)
max_requests = optional(number)
max_retries = optional(number)
})
null no
connection_draining_timeout_sec Time in seconds to wait for connections to drain when removing a backend. number 0 no
create_forwarding_rule Whether to create the forwarding rule and TCP proxy. Set to false to only create the backend service, allowing the user to manage their own forwarding rule externally. The backend_service output provides the necessary attributes for this purpose. bool true no
ip_address The IP address for the forwarding rule. Use '0.0.0.0' for the default mesh-wide listener, or a reserved internal IP address to avoid port conflicts when multiple backend services share the same port. Only used when create_forwarding_rule is true. string "0.0.0.0" no
labels Labels to apply to the forwarding rule resource. map(string) {} no
locality_lb_policy The load balancing policy. Use 'ROUND_ROBIN' for even distribution or 'RING_HASH' for consistent hashing (sticky sessions). string "ROUND_ROBIN" no
log_config_enable Whether to enable logging for the backend service. bool false no
log_config_sample_rate The sampling rate for logging (0.0 to 1.0). Only applies when log_config_enable is true. number 1 no
max_connections Maximum number of simultaneous connections for the entire backend service. number null no
max_connections_per_instance Maximum number of simultaneous connections per backend instance. number null no
outlier_detection Outlier detection configuration for automatic ejection of unhealthy backends.
object({
consecutive_errors = optional(number)
max_ejection_percent = optional(number)
interval = optional(object({
seconds = number
nanos = optional(number)
}))
base_ejection_time = optional(object({
seconds = number
nanos = optional(number)
}))
})
null no
session_affinity The session affinity for the backend service. Use 'CLIENT_IP' with 'RING_HASH' for sticky sessions. string "NONE" no
timeout_sec Backend service timeout in seconds. How long to wait for a backend to respond. number 30 no

Outputs

Name Description
backend_service The created backend service resource attributes.
forwarding_rule The created forwarding rule resource attributes. Null when create_forwarding_rule is false.
tcp_proxy The created TCP proxy resource attributes. Null when create_forwarding_rule is false.

Examples

  • Complete Example - Full setup with MIG, health checks, and read/write services

Testing

This module includes Terraform native tests:

# Run all tests
task test

# Run with verbose output
task test:verbose

# Run specific test file
task test:filter -- validation

Development

This project uses Task for automation. Available tasks:

task --list          # Show all available tasks
task fmt             # Format Terraform files
task validate        # Validate configuration
task lint            # Run tflint
task sec             # Run tfsec security scan
task docs            # Generate documentation
task ci              # Run all CI checks
task clean           # Clean up generated files

Local Development Setup

  1. Install mise for tool version management
  2. Run mise install to install required tools
  3. Run task hooks:install to set up git hooks

About Boozt

Boozt is a leading and fast-growing Nordic technology company selling fashion and lifestyle online mainly through its multi-brand webstore Boozt.com and Booztlet.com.

The company is focused on using cutting-edge, in-house developed technology to curate the best possible customer experience.

With offices in Sweden, Denmark, Lithuania and Poland, we pride ourselves in having a diverse team, consisting of 1100+ employees and 38 nationalities.

See our Medium blog page for technology-focused articles. Would you like to make your mark by working with us at Boozt? Take a look at our latest hiring opportunities.

Reporting Issues

Please provide a clear and concise description of the problem or the feature you're missing along with any relevant context or screenshots.

Check existing issues before reporting to avoid duplicates.

Please follow the Issue Reporting Guidelines before opening a new issue.

Contributing

Contributions are highly valued and very welcome! For the process of reviewing changes, we use Pull Requests. For a detailed information please follow the Contribution Guidelines

License

license

This project is licensed under the MIT. Please see LICENSE for full details.

About

Terraform module for Google Cloud Traffic Director backend services with TCP proxy load balancing. Supports round-robin, sticky sessions (RING_HASH), circuit breakers, and outlier detection for Envoy-based service mesh architectures

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors