Terraform for Developers: State, Modules, Environments and CI

Terraform for developers explained: providers, remote state and locking, modules, environments, secrets in state, plan/apply in CI and drift, with real HCL.

By Victor Sanchez

Terraform for developers usually starts the same way: the "infra person" is on vacation, a pipeline needs a new environment variable or a queue, and the change lives in a repository full of .tf files nobody on the app team understands. We maintain Terraform that manages GitHub Actions workflows for an enterprise application, and we provision our own projects with it. This is the mental model we wish every application developer had on day one.

What are providers and resources in Terraform?

A provider is a plugin that talks to an API (AWS, Azure, DigitalOcean, GitHub). A resource is one object that provider manages. You declare the desired end state; Terraform computes the diff and calls the API.

terraform {
  required_version = ">= 1.11"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = var.region
}

resource "aws_sqs_queue" "orders" {
  name                       = "orders-${var.env}"
  visibility_timeout_seconds = 60
}

Think of it as a declarative DbContext for infrastructure: you describe the model, and Terraform generates the "migration" (the plan).

Why does Terraform state matter so much?

State is Terraform's memory: a JSON file mapping aws_sqs_queue.orders to the real queue in your account. Lose it and Terraform thinks nothing exists. Let two people write it at once and you corrupt it. That is why state never lives on a laptop.

Remote backend with locking

terraform {
  backend "s3" {
    bucket       = "example-tfstate"
    key          = "app/prod/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true # native S3 locking; DynamoDB locking is deprecated
  }
}

On Azure the equivalent is the azurerm backend on a storage account, which locks with blob leases. Turn on bucket versioning so you can recover a bad state write.

How should you structure Terraform modules?

A module is just a folder with inputs (variable) and outputs (output). Write one when the same group of resources appears twice, not before.

module "worker_queue" {
  source = "./modules/queue"

  name              = "orders"
  env               = var.env
  max_receive_count = 5 # dead-letter after five failures
}

output "orders_queue_url" {
  value = module.worker_queue.url
}

Pin external modules to a version (version = "x.y.z" or a git tag). An unpinned module is an unreviewed dependency.

Workspaces or folders for environments?

Terraform workspaces give one configuration several state files. They are fine for identical, short-lived copies (a preview environment per branch). For dev/staging/prod we prefer one folder per environment calling shared modules, because prod usually differs (sizes, replicas, alerts) and separate folders make that explicit in code review.

infra/
  modules/
    queue/
    api/
  envs/
    dev/      # main.tf, backend.tf, terraform.tfvars
    staging/
    prod/

Are secrets safe in Terraform state?

Not by default. Marking a variable sensitive = true hides it in plan output but still writes it to state in plain text. Three rules we follow:

  • Treat the state backend as a secret store: encryption at rest, tight IAM, no public access.
  • Prefer letting the platform own the secret (managed identity, a secrets manager) and pass only references.
  • Where the provider supports it, use write-only arguments (Terraform 1.11+), which are sent to the API but never stored in state.
resource "aws_db_instance" "main" {
  # ...
  password_wo         = var.db_password # write-only: not persisted in state
  password_wo_version = 1               # bump to rotate
}

If a secret already sits in your repository, read how to find, remove and rotate hardcoded secrets before wiring it into Terraform.

How do you run plan and apply in CI?

The pattern: plan on pull request, apply on merge, with short-lived cloud credentials through OIDC instead of stored keys.

name: terraform
on:
  pull_request:
    paths: ["infra/**"]
  push:
    branches: [main]
    paths: ["infra/**"]

permissions:
  id-token: write   # OIDC token for the cloud provider
  contents: read

jobs:
  terraform:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: infra/envs/prod
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::<ACCOUNT_ID>:role/<CI_ROLE>
          aws-region: us-east-1
      - run: terraform init -input=false
      - run: terraform fmt -check && terraform validate
      - run: terraform plan -input=false -out=tfplan
      - if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform apply -input=false tfplan

For production, put the apply job behind a GitHub environment with required reviewers. We show the full pipeline for a real app in deploying .NET and React on DigitalOcean.

How do you detect drift?

Drift is when reality no longer matches your code, usually because someone "fixed it quickly" in the console. Run a scheduled plan and fail loudly when it finds changes:

# Exit code 0 = no changes, 1 = error, 2 = drift detected
terraform plan -detailed-exitcode -input=false -lock=false
if [ $? -eq 2 ]; then
  echo "Drift detected in prod" >&2
  exit 1
fi

Then decide per case: import the manual change into code, or let the next apply revert it.

Common Terraform pitfalls for developers

  • Renaming a resource. Terraform sees delete plus create. Use a moved block to keep the real object.
  • Floating provider versions. Commit .terraform.lock.hcl and pin providers.
  • Applying from laptops. One apply path (CI) means one audit trail.
  • Giant root modules. Thousands of resources in one state make every plan slow and risky. Split by lifecycle.
  • Ignoring the plan. Read every "destroy" line before you approve.

Terraform checklist for app teams

  • Remote backend with encryption, versioning and locking.
  • required_version, provider versions and the lock file committed.
  • One folder per long-lived environment; modules only for real repetition.
  • No secrets in .tfvars committed to git.
  • Plan on PR, apply on merge, OIDC credentials, reviewers for prod.
  • Scheduled drift detection.

Key takeaways

  • Terraform is a desired-state engine: providers talk to APIs, state remembers what exists.
  • Protect state like a database of secrets, because it can be one.
  • Environments as folders are easier to review than workspaces for prod.
  • CI owns apply; humans own the review of the plan. Comparing tools first? See Terraform vs OpenTofu vs Pulumi vs Bicep.

Sources

Need help with Terraform?

Santhor designs cloud architecture, infrastructure as code and CI/CD for new products built from scratch, and we migrate or stabilize existing deployments that suffer from performance, cost or reliability problems. We are based in Costa Rica and work nearshore with teams in the U.S. and Latin America. Tell us about your project

More articles ยท Contact Santhor