Area 07 · Deployment · Concept 08 of 20

Infrastructure as Code

Define servers, databases and networks in code (Terraform, Pulumi) instead of clicking.

01–10 · The basePhase 5 · Weeks 18–20≈ 2 hours

The idea

Clicking through cloud consoles creates infrastructure nobody can reproduce or review. Infrastructure as code (IaC) declares resources (a Cloud Run service, a Postgres instance, a bucket, IAM roles) in files that live in Git, get reviewed in pull requests and are applied by a tool.

Terraform uses its own HCL language and a plan/apply workflow: plan shows exactly what will change, apply makes it so. Pulumi does the same with Python or TypeScript. State files track what exists and must be stored safely (a remote backend with locking).

With IaC you can recreate staging from scratch, review infrastructure changes and roll them back.

Why it matters

It makes infrastructure reviewable, repeatable and recoverable, and it is expected in any serious team.

Words to know

  • PlanThe preview of changes IaC will make.
  • StateThe tool’s record of real resources it manages.

Try it without code

Read a plan

  1. Install Terraform.
  2. Write a config that creates one storage bucket.
  3. Run terraform plan and read what it would do before applying.

Use it in code

A Cloud Run service with Terraform.

hcl
provider "google" {
  project = var.project
  region  = "europe-west1"
}

resource "google_cloud_run_v2_service" "rag_api" {
  name     = "rag-api"
  location = "europe-west1"
  template {
    containers {
      image = "europe-west1-docker.pkg.dev/${var.project}/apps/rag-api:${var.image_tag}"
      env {
        name = "ANTHROPIC_API_KEY"
        value_source {
          secret_key_ref {
            secret  = "anthropic-api-key"
            version = "latest"
          }
        }
      }
      resources {
        limits = { cpu = "1", memory = "1Gi" }
      }
    }
    scaling {
      min_instance_count = 0
      max_instance_count = 5
    }
  }
}
$ terraform init && terraform plan -var project=my-proj -var image_tag=abc123
PRACTICE · TICK IT AFTER THIS

Describe your deployment target in Terraform or Pulumi and recreate it in a fresh project from code.

Common mistakes

  • State files committed to Git.
  • Mixing console clicks with IaC on the same resources.

Go deeper