Terraform Labs · Lab 7 of 9

Google Cloud: A VM in a Custom VPC with State in GCS

Create a custom VPC network and subnet, firewall rules that allow HTTP and SSH only through Identity-Aware Proxy, a dedicated service account, and a Shielded e2-micro VM running nginx — with Terraform state in a versioned Cloud Storage bucket.

Environment
Google Cloud
Level
Intermediate
Time
About 55 min
Cost
Always Free e2-micro; external IP ≈ $0.005 per hour

You will build

A web server on Google Cloud built with the same production habits as on AWS: custom network, least-privilege identity, no public SSH, and remote state from the first apply.

Before you start

Members can save this page, take notes and track progress. See membership · Sign in

The plan output below comes from planning this configuration with the example project ID my-project-id; yours shows your own project ID. apply, curl and SSH steps describe what to look for, since IP addresses are different for every project.

Cost: e2-micro is in the Always Free tier in us-central1, us-west1 and us-east1; the external IP costs about $0.005 per hour.

What you will build

  • Project: the billing and permission boundary everything lives in.
  • VPC network (custom mode): no automatic subnets; you create subnet 10.10.1.0/24 yourself.
  • Firewall rules apply to the whole network and pick their targets by network tag: allow-http lets tcp/80 reach VMs tagged web, and allow-iap-ssh allows port 22 only from 35.235.240.0/20, the range Identity-Aware Proxy (IAP) connects from.
  • VM e2-micro: a Shielded VM (secure boot, vTPM) running Debian 12 and nginx from a startup script, as its own service account with no roles.
  • GCS bucket: holds Terraform's state, with versioning.
InternetusersYougcloud sshProject my-project-idIAPSSH tunnelVPC network (custom mode)allow-httptcp/80 to tag weballow-iap-ssh22 from 35.235.240.0/20Subnet 10.10.1.0/24VM e2-microShielded, nginxService accountVM identity, no keysTerraformyou or CIGCS bucketversioned statestate
What the Google Cloud lab builds: firewall rules by network tag, IAP-only SSH and remote state in GCS

Project structure

gcp-web/
├── .gitignore
├── versions.tf    # provider, empty gcs backend, default labels
├── backend.hcl    # backend settings for terraform init
├── variables.tf
├── network.tf     # VPC, subnet, firewall rules
├── compute.tf     # service account and VM
└── outputs.tf

Download starter filesDownload finished project

Steps

  1. 1Sign in and enable the APIs

    Application Default Credentials are what Terraform's Google provider uses on your computer.

    Run
    gcloud auth application-default login
    gcloud config set project YOUR_PROJECT_ID
    gcloud services enable compute.googleapis.com iam.googleapis.com
    export TF_VAR_project_id=$(gcloud config get-value project)
    
    Check:

    gcloud services list --enabled includes compute.googleapis.com.

  2. 2Create a state bucket

    Versioning keeps every state revision; uniform access and public access prevention keep it private.

    Run
    gcloud storage buckets create gs://acme-tfstate-$TF_VAR_project_id \
      --location=us-central1 --uniform-bucket-level-access --public-access-prevention
    gcloud storage buckets update gs://acme-tfstate-$TF_VAR_project_id --versioning
    
    Check:

    gcloud storage buckets describe gs://acme-tfstate-$TF_VAR_project_id shows versioning enabled.

  3. 3Provider and a partial backend

    backend "gcs" {} is left empty on purpose: the bucket name comes from backend.hcl at init time, so the same code can point at a different bucket per environment. default_labels labels every resource.

    backend.hcl supplies the bucket and prefix when you run terraform init -backend-config=backend.hcl. The GCS backend stores the state as default.tfstate under that prefix and keeps a default.tflock object while a run is applying. Each environment has its own backend.hcl, so the code stays identical.

    versions.tfbackend "gcs" {}backend.hclbucket, prefixterraform init-backend-config=backend.hclGCS bucketStatedefault.tfstateLockdefault.tflock while applyingThe backend block stays empty in code; each environment passes its own settings at init
    Partial backend configuration: an empty backend block plus a settings file read at init
    versions.tf
    terraform {
      required_version = ">= 1.6"
    
      required_providers {
        google = {
          source  = "hashicorp/google"
          version = "~> 8.0"
        }
      }
    
      # Settings come from backend.hcl: terraform init -backend-config=backend.hcl
      backend "gcs" {}
    }
    
    provider "google" {
      project = var.project_id
      region  = var.region
      zone    = var.zone
    
      default_labels = {
        project     = var.name
        environment = var.environment
        managed_by  = "terraform"
      }
    }
    
  4. 4Backend settings

    Put your bucket name here.

    backend.hcl
    bucket = "acme-tfstate-my-project-id" # the bucket you create in step 2
    prefix = "shop/dev/gcp-web"
    
  5. 5Inputs

    variables.tf
    variable "project_id" {
      description = "Google Cloud project ID"
      type        = string
    }
    
    variable "region" {
      description = "us-central1, us-west1 and us-east1 include an Always Free e2-micro"
      type        = string
      default     = "us-central1"
    }
    
    variable "zone" {
      type    = string
      default = "us-central1-a"
    }
    
    variable "name" {
      description = "Name prefix for every resource"
      type        = string
      default     = "shop"
    }
    
    variable "environment" {
      type    = string
      default = "dev"
    }
    
    variable "allowed_http_cidr" {
      description = "Who may open the web page. Use your own IP with /32 to keep it private."
      type        = string
      default     = "0.0.0.0/0"
    
      validation {
        condition     = can(cidrhost(var.allowed_http_cidr, 0))
        error_message = "allowed_http_cidr must be a valid IPv4 CIDR block."
      }
    }
    
  6. 6Network and firewall

    auto_create_subnetworks = false gives you a custom-mode VPC with only the subnets you define. SSH is allowed only from Google's IAP range, so nobody can reach port 22 from the internet.

    network.tf
    resource "google_compute_network" "main" {
      name                    = "${var.name}-${var.environment}"
      auto_create_subnetworks = false # define subnets yourself
    }
    
    resource "google_compute_subnetwork" "web" {
      name          = "${var.name}-${var.environment}-web"
      network       = google_compute_network.main.id
      region        = var.region
      ip_cidr_range = "10.10.1.0/24"
    }
    
    resource "google_compute_firewall" "http" {
      name          = "${var.name}-${var.environment}-allow-http"
      network       = google_compute_network.main.id
      direction     = "INGRESS"
      source_ranges = [var.allowed_http_cidr]
      target_tags   = ["web"]
    
      allow {
        protocol = "tcp"
        ports    = ["80"]
      }
    }
    
    # SSH only through Identity-Aware Proxy (gcloud compute ssh --tunnel-through-iap), never from the internet
    resource "google_compute_firewall" "iap_ssh" {
      name          = "${var.name}-${var.environment}-allow-iap-ssh"
      network       = google_compute_network.main.id
      direction     = "INGRESS"
      source_ranges = ["35.235.240.0/20"]
      target_tags   = ["web"]
    
      allow {
        protocol = "tcp"
        ports    = ["22"]
      }
    }
    
  7. 7Service account and VM

    The VM runs as its own service account with no roles, instead of the default compute account that has broad project access. Shielded VM options protect the boot chain.

    compute.tf
    # A dedicated identity with no roles, instead of the broad default compute service account
    resource "google_service_account" "web" {
      account_id   = "${var.name}-${var.environment}-web"
      display_name = "Web server (${var.environment})"
    }
    
    resource "google_compute_instance" "web" {
      name         = "${var.name}-${var.environment}-web"
      machine_type = "e2-micro"
      tags         = ["web"]
    
      boot_disk {
        initialize_params {
          image = "debian-cloud/debian-12"
          size  = 10
          type  = "pd-standard"
        }
      }
    
      network_interface {
        subnetwork = google_compute_subnetwork.web.id
        access_config {} # ephemeral public IP
      }
    
      metadata_startup_script = <<-EOT
        #!/bin/bash
        apt-get update
        apt-get install -y nginx
        echo "<h1>${var.name} ${var.environment}</h1><p>Served by $(hostname)</p>" > /var/www/html/index.html
      EOT
    
      metadata = {
        enable-oslogin = "TRUE"
      }
    
      service_account {
        email  = google_service_account.web.email
        scopes = ["cloud-platform"]
      }
    
      shielded_instance_config {
        enable_secure_boot          = true
        enable_vtpm                 = true
        enable_integrity_monitoring = true
      }
    }
    
  8. 8Outputs

    outputs.tf
    output "url" {
      description = "Open this in a browser (allow a minute for nginx to install)"
      value       = "http://${google_compute_instance.web.network_interface[0].access_config[0].nat_ip}"
    }
    
  9. 9Initialise with the backend settings

    Run
    terraform init -backend-config=backend.hcl
    
    Check:

    Terraform installs hashicorp/google v8.x and reports that the gcs backend was configured.

  10. 10Validate

    Run
    terraform fmt -check
    terraform validate
    

    Expected output

    Success! The configuration is valid.
  11. 11Plan

    Run
    terraform plan -out=tfplan
    

    Expected output

      # google_compute_firewall.http will be created
      ...
      # google_compute_firewall.iap_ssh will be created
      ...
      # google_compute_instance.web will be created
      + resource "google_compute_instance" "web" {
          + machine_type            = "e2-micro"
          + name                    = "shop-dev-web"
          ...
          + zone                    = "us-central1-a"
    
          + boot_disk {
              ...
              + initialize_params {
                  + image                  = "debian-cloud/debian-12"
                  ...
                  + size                   = 10
                  + type                   = "pd-standard"
          ...
          + service_account {
              + email  = "[email protected]"
          ...
          + shielded_instance_config {
              + enable_secure_boot          = true
          ...
      # google_compute_network.main will be created
      ...
      # google_compute_subnetwork.web will be created
      ...
      # google_service_account.web will be created
      ...
    Plan: 6 to add, 0 to change, 0 to destroy.
    
    Changes to Outputs:
      + url = (known after apply)
  12. 12Apply and open the page

    Run
    terraform apply tfplan
    curl $(terraform output -raw url)
    
    Check:

    Apply complete! Resources: 6 added. About a minute later curl returns <h1>shop dev</h1> and the VM's name.

  13. 13SSH through IAP

    Run
    gcloud compute ssh shop-dev-web --zone us-central1-a --tunnel-through-iap
    
    Check:

    You get a shell even though port 22 isn't open to the internet. Type exit to leave.

    Hint

    Your user needs the IAP-secured Tunnel User role (roles/iap.tunnelResourceAccessor) on the project.

  14. 14Check the state is remote

    Run
    gcloud storage ls gs://acme-tfstate-$TF_VAR_project_id/shop/dev/gcp-web/
    
    Check:

    The listing shows default.tfstate; there is no terraform.tfstate in your folder.

Clean up

The external IP costs money while it exists, and the VM leaves the free tier if you run a second one.

terraform destroy
gcloud storage rm --recursive gs://acme-tfstate-$TF_VAR_project_id

Check for Destroy complete! Resources: 6 destroyed. Delete the bucket last, after the destroy, because it holds the state Terraform needs to know what to delete.

In production

What changes

In this lab In production
One project for everything One project per environment inside a folder structure, created by a project factory, with an org policy baseline
A VM with an external IP Managed instance groups or Cloud Run behind an external HTTPS load balancer with a Google-managed certificate; VMs without external IPs, outbound through Cloud NAT
Startup script installs nginx A custom image (Packer) or containers, so every instance starts identical
You run Terraform with your own login CI authenticates with Workload Identity Federation (no service account keys) and impersonates a deploy service account
0.0.0.0/0 allowed on port 80 Firewall rules target service accounts rather than tags; Cloud Armor in front of public load balancers

Identity first

On Google Cloud, most security comes from IAM. Give every workload its own service account with only the roles it needs, never create service account keys, and grant humans access through groups.

Production checklist

  • Custom-mode VPC with planned subnet ranges; no default network
  • No SSH from the internet: IAP or OS Login only
  • Each workload has its own service account with minimal roles; no keys
  • Shielded VM enabled; VMs have no external IP behind a load balancer
  • State in a versioned GCS bucket with uniform access, one prefix per environment
  • Labels on every resource for billing reports; budgets and alerts on every project

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake