Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 45 ยท Projects

Project: A Three-Tier App with Terraform

Define a three-tier app in Terraform: a custom VPC, a managed instance group behind a load balancer, a private Cloud SQL database, and a clean teardown.

A three-tier application separates a web tier (what users reach), an application tier (the code that runs your logic) and a data tier (the database). On Google Cloud a classic version uses a custom VPC network, a managed instance group of VMs behind a load balancer, and a Cloud SQL database that only has a private address. In this project you describe all of it as Terraform code, so it can be reviewed, repeated and destroyed with two commands.

The real resources need a billing account and cost money while they exist, so the Terraform is read-only here. The runnable stand-in is a small plan builder: it turns a description of the architecture into an ordered list of resources with dependencies, which is the core idea behind terraform plan.

Three tiers on Google Cloud

Load balancer One public entry point.
VM group Autoscaled app servers.
Cloud SQL Private database only.
VPC The network that joins them.
1 / 2
flowchart TB
  U["Users"] --> LB["HTTP load balancer"]
  LB --> MIG["Managed instance group<br/>(app VMs, private IPs)"]
  MIG --> SQL["Cloud SQL<br/>(private IP)"]
  subgraph VPC["Custom VPC network"]
    MIG
    SQL
  end

Only the load balancer is public; VMs and the database have no public addresses.

Project layout

Keep the files small and named by purpose. Review infrastructure as code for state and workflow basics.

TEXT
three-tier/
  versions.tf     # Terraform and provider versions, backend
  variables.tf    # inputs: project, region, passwords
  network.tf      # VPC, subnet, firewall, private service access
  database.tf     # Cloud SQL
  compute.tf      # template, group, autoscaler, health check
  lb.tf           # load balancer
  outputs.tf      # the IP address and connection name

versions.tf and variables.tf

Store the state in a bucket so teams share it and it survives your laptop. Create the bucket first (gcloud storage buckets create gs://my-tf-state-12345 --uniform-bucket-level-access) and turn on versioning. Backend blocks cannot use variables, so the name is written out.

HCL
terraform {
  required_version = ">= 1.6"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 6.0"
    }
  }
  backend "gcs" {
    bucket = "my-tf-state-12345"
    prefix = "three-tier"
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}
HCL
variable "project_id" {
  type = string
}

variable "region" {
  type    = string
  default = "us-central1"
}

variable "db_password" {
  type      = string
  sensitive = true
}

Do not put the password in a .tf file. Pass it as TF_VAR_db_password from your shell or fetch it from Secret Manager. Note that Terraform state can contain secret values, which is one more reason to protect the state bucket with tight IAM.

network.tf

A custom-mode VPC, one regional subnet, and a firewall rule. The rule allows the load balancer's health-check and proxy ranges (Google documents them as 130.211.0.0/22 and 35.191.0.0/16) to reach the VMs on port 8080, and nothing else from outside. See VPC networks for firewall priorities and tags.

HCL
resource "google_compute_network" "main" {
  name                    = "three-tier-vpc"
  auto_create_subnetworks = false
}

resource "google_compute_subnetwork" "app" {
  name                     = "app-subnet"
  ip_cidr_range            = "10.10.0.0/24"
  region                   = var.region
  network                  = google_compute_network.main.id
  private_ip_google_access = true
}

resource "google_compute_firewall" "allow_lb" {
  name    = "allow-lb-to-app"
  network = google_compute_network.main.name

  allow {
    protocol = "tcp"
    ports    = ["8080"]
  }
  source_ranges = ["130.211.0.0/22", "35.191.0.0/16"]
  target_tags   = ["app"]
}

# Private services access, so Cloud SQL can have a private IP in this VPC
resource "google_compute_global_address" "sql_range" {
  name          = "sql-private-range"
  purpose       = "VPC_PEERING"
  address_type  = "INTERNAL"
  prefix_length = 16
  network       = google_compute_network.main.id
}

resource "google_service_networking_connection" "sql" {
  network                 = google_compute_network.main.id
  service                 = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [google_compute_global_address.sql_range.name]
}

database.tf

HCL
resource "google_sql_database_instance" "main" {
  name             = "three-tier-db"
  database_version = "POSTGRES_16"
  region           = var.region

  settings {
    tier = "db-custom-1-3840"
    ip_configuration {
      ipv4_enabled    = false
      private_network = google_compute_network.main.id
    }
    backup_configuration {
      enabled = true
    }
  }

  deletion_protection = false   # true in production; false lets teardown work
  depends_on          = [google_service_networking_connection.sql]
}

resource "google_sql_user" "app" {
  name     = "app"
  instance = google_sql_database_instance.main.name
  password = var.db_password
}

ipv4_enabled = false is what keeps the database off the public internet. depends_on matters: the private connection must exist first. Check Cloud SQL for high availability, replicas and edition choices.

compute.tf

An instance template describes one VM; the managed instance group keeps several running, replaces unhealthy ones and autoscales on CPU. The VMs have no external IP, and a startup script launches your app (here a placeholder). See instance groups.

HCL
resource "google_compute_instance_template" "app" {
  name_prefix  = "app-"
  machine_type = "e2-small"
  tags         = ["app"]

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

  network_interface {
    subnetwork = google_compute_subnetwork.app.id
    # no access_config block: no external IP
  }

  metadata_startup_script = file("startup.sh")

  lifecycle {
    create_before_destroy = true
  }
}

resource "google_compute_health_check" "app" {
  name = "app-health"
  http_health_check {
    port         = 8080
    request_path = "/healthz"
  }
}

resource "google_compute_region_instance_group_manager" "app" {
  name               = "app-mig"
  region             = var.region
  base_instance_name = "app"
  version {
    instance_template = google_compute_instance_template.app.id
  }
  named_port {
    name = "http"
    port = 8080
  }
  auto_healing_policies {
    health_check      = google_compute_health_check.app.id
    initial_delay_sec = 120
  }
}

resource "google_compute_region_autoscaler" "app" {
  name   = "app-autoscaler"
  region = var.region
  target = google_compute_region_instance_group_manager.app.id
  autoscaling_policy {
    min_replicas    = 2
    max_replicas    = 6
    cooldown_period = 90
    cpu_utilization { target = 0.6 }
  }
}

VMs without external IPs cannot reach the internet to install packages unless you add Cloud NAT, so bake dependencies into the image or add google_compute_router_nat for outbound access. This is the most common surprise in this design.

lb.tf and outputs.tf

HCL
resource "google_compute_backend_service" "app" {
  name                  = "app-backend"
  protocol              = "HTTP"
  port_name             = "http"
  load_balancing_scheme = "EXTERNAL_MANAGED"
  health_checks         = [google_compute_health_check.app.id]
  backend {
    group = google_compute_region_instance_group_manager.app.instance_group
  }
}

resource "google_compute_url_map" "app" {
  name            = "app-map"
  default_service = google_compute_backend_service.app.id
}

resource "google_compute_target_http_proxy" "app" {
  name    = "app-proxy"
  url_map = google_compute_url_map.app.id
}

resource "google_compute_global_forwarding_rule" "app" {
  name                  = "app-rule"
  load_balancing_scheme = "EXTERNAL_MANAGED"
  port_range            = "80"
  target                = google_compute_target_http_proxy.app.id
}

output "load_balancer_ip" {
  value = google_compute_global_forwarding_rule.app.ip_address
}
output "database_connection_name" {
  value = google_sql_database_instance.main.connection_name
}

This uses plain HTTP to stay short. For a real site add a managed certificate and an HTTPS proxy as in the static-site project. The newer load balancer scheme in Terraform also requires a proxy-only subnet in the region; if plan or apply reports that, add one and re-run. Keep this in mind: provider arguments and requirements change between versions, so confirm the current resource documentation before relying on any snippet.

Run it

Terminal
export TF_VAR_project_id=my-project-id
export TF_VAR_db_password="a-long-random-value"

gcloud auth application-default login
gcloud services enable compute.googleapis.com sqladmin.googleapis.com servicenetworking.googleapis.com

terraform init
terraform fmt
terraform validate
terraform plan -out=tfplan
terraform apply tfplan

Always read the plan: it lists each resource as create (+), change (~) or destroy (-). Creating the database can take 10 to 20 minutes.

Teardown

Terminal
terraform destroy

Destroy deletes in reverse dependency order. If it fails on the private connection, delete the database first and retry. Confirm nothing is left with gcloud compute instances list, gcloud sql instances list and gcloud compute forwarding-rules list, as in common mistakes. The state bucket is separate; delete it last.

Stand-in: a plan builder

Terraform reads the references between resources (like google_compute_network.main.id) to build a dependency graph, creates things in an order where dependencies come first, and destroys in the reverse order. This stand-in does the same for a short list of resources: it sorts them and prints a plan. It is a model of the idea, not Terraform.

JS Stand-in: order resources by dependency

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first plan lists the network first and the database last, because each resource appears only after everything it needs. Teardown is the exact reverse. Terraform also detects cycles, which is why two resources cannot each reference the other.

A second stand-in: a cost sketch

Before applying, estimate what the architecture could cost per month. This stand-in multiplies invented hourly rates by hours; the rates are made up to show the method, so replace them with numbers from Google's pricing calculator.

JS Stand-in: rough monthly cost of the design

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Everything keeps billing while it exists, even idle, which is why the teardown step is part of the project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What keeps the Cloud SQL instance off the public internet in this design?

    Disabling the public IPv4 address and attaching the instance to the VPC through private services access makes it reachable only privately.
  2. 2. Why store Terraform state in a Cloud Storage bucket?

    A remote backend gives shared, durable state that protects against conflicting applies.
  3. 3. In what order does terraform destroy remove resources?

    A resource cannot be deleted while others depend on it, so Terraform removes dependents before what they use.
  4. 4. The VMs have no external IP and cannot install packages. What can you add?

    Cloud NAT provides outbound internet access to VMs without external IPs, or you can bake software into the image.
  5. 5. Why should you read terraform plan before apply?

    The plan is your last chance to catch an unintended change, especially a destroy.

Summary

  • A three-tier design uses a load balancer, a managed instance group in a custom VPC, and a private Cloud SQL database.
  • Split Terraform into small files, keep state in a versioned bucket, and keep secrets out of .tf files.
  • Run fmt, validate, plan and apply, and read every plan.
  • Resources keep billing while they exist; terraform destroy (or deleting the project) is the cleanup.

Next: Practice Exercises with Solutions