Your DevOps study space

Real explanations. Videos with tests. Fresh exams every time. Keep the streak alive and watch the XP stack up.

Terraform in practice: variables, modules and environments · DevOps Docs · StackwisePlanDevOps Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseCodePython Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseBuildDocker Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseTestDevOps Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseReleaseGit Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseDeployKubernetes Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseOperateLinux Terraform in practice: variables, modules and environments · DevOps Docs · StackwiseMonitorDevOps

Pick a topic

Eight tracks, each with docs, a cheat sheet, videos and tests.

How it works

One loop, repeated until it sticks.

Jump back in

Picked up from where you left off.

Free forever

Your DevOps journey starts with one click.

Sign in with Google or GitHub to open every chapter, video, test and challenge. Your progress is saved wherever you learn.

Terraform in practice: variables, modules and environments

Chapter 5 built one bucket from one file. Real infrastructure has a dev and a production copy that should differ only in size and names, pieces that repeat, resources that already exist, and a team that changes it through pull requests. This chapter covers the Terraform features that make that manageable.

Variables, outputs and locals

Variables are a configuration's inputs, outputs are what it reports back, and locals are named values you compute inside it:

# variables.tf
variable "env" {
  type        = string
  description = "dev, staging or prod"
  validation {
    condition     = contains(["dev", "staging", "prod"], var.env)
    error_message = "env must be dev, staging or prod."
  }
}
variable "instance_type" {
  type    = string
  default = "t3.micro"
}
variable "db_password" {
  type      = string
  sensitive = true                  # hidden in plan output
}

# main.tf
locals {
  name = "shop-${var.env}"
  tags = { project = "shop", env = var.env, managed_by = "terraform" }
}
resource "aws_s3_bucket" "assets" {
  bucket = "${local.name}-assets"
  tags   = local.tags
}

# outputs.tf
output "assets_bucket" {
  value = aws_s3_bucket.assets.bucket
}

Values come from, in rising priority: the default, a terraform.tfvars or *.auto.tfvars file (loaded automatically), -var-file=prod.tfvars, and -var "env=prod" on the command line. Environment variables named TF_VAR_db_password also work, which is how CI passes secrets without writing them to a file.

Many of the same thing: count and for_each

# count: N copies, numbered 0, 1, 2...
resource "aws_instance" "web" {
  count         = 3
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type
  tags          = { Name = "web-${count.index}" }
}

# for_each: one per key, named by the key
resource "aws_s3_bucket" "store" {
  for_each = toset(["logs", "backups", "uploads"])
  bucket   = "${local.name}-${each.key}"
}

Prefer for_each for anything with a name. With count, removing the middle item renumbers everything after it, and Terraform destroys and recreates resources that didn't need to change. With for_each, each resource is tracked by its key (aws_s3_bucket.store["logs"]), so removing one touches only that one.

count: remove "backups"[0] logskept[1] uploadswas backups: replaced![2] uploadsdestroyedfor_each: remove "backups"["logs"]kept["backups"]destroyed, as asked["uploads"]kept
count tracks resources by position, for_each by name. Removing one name only ever touches that one resource.

Data sources: read what already exists

A data block looks something up instead of creating it: the newest Ubuntu image, the current account ID, a VPC another team manages.

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]                 # Canonical, the publisher of Ubuntu
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
  }
}
data "aws_caller_identity" "current" {}

output "account_id" { value = data.aws_caller_identity.current.account_id }

Modules: write it once, use it everywhere

A module is just a folder of .tf files with variables and outputs. Every configuration is already a module (the root module); you can call others from it:

modules/
  web_service/
    variables.tf      # name, instance_type, instance_count, vpc_id...
    main.tf           # the security group, instances, load balancer target group
    outputs.tf        # the load balancer DNS name
envs/
  dev/main.tf
  prod/main.tf

# envs/prod/main.tf
module "api" {
  source         = "../../modules/web_service"
  name           = "shop-api-prod"
  instance_type  = "t3.medium"
  instance_count = 3
}
output "api_url" { value = module.api.url }

Run terraform init again after adding or changing a module's source. Public modules from the Terraform Registry work the same way with source = "terraform-aws-modules/vpc/aws" and a version constraint; read one before you use it, since you're taking on all of its choices.

Environments: one folder each

modules/web_servicevariables, main, outputsnetworkVPC, subnetsdatabaseRDS, backupsenvs/devmain.tf1 x t3.microown stateown backendusesenvs/prodmain.tf3 x t3.mediumown stateown backend
One copy of the logic, one folder per environment. Dev and prod differ only in the values they pass in, and can never touch each other's state.

The simplest layout that stays safe is a folder per environment, each with its own backend (its own state file) and a small main.tf that calls the shared modules. Dev and prod can't touch each other's state, plans are easy to read, and prod can pin an older module version while dev tries a new one.

Terraform also has workspaces (terraform workspace new dev), several state files for one folder of code, with terraform.workspace holding the current name. They're handy for short-lived copies, but it's easy to run apply in the wrong one, so most teams use separate folders for real environments.

Importing and moving without destroying

Resources made by hand can be brought under Terraform with an import block (Terraform 1.5 and later). Terraform can even write the resource block for you:

import {
  to = aws_s3_bucket.legacy
  id = "shop-old-uploads"            # the bucket's real name
}

$ terraform plan -generate-config-out=generated.tf   # writes a starting resource block
$ terraform apply                                    # now it's in state; tidy generated.tf by hand

Renaming a resource in code normally means "destroy the old one, create a new one". A moved block tells Terraform it's the same thing under a new address:

moved {
  from = aws_s3_bucket.assets
  to   = aws_s3_bucket.store["assets"]
}

Guard rails with lifecycle

resource "aws_db_instance" "main" {
  # ...
  lifecycle {
    prevent_destroy       = true                # any plan that would delete it fails
    ignore_changes        = [tags["last_backup"]]   # changed by something else, don't fight it
  }
}

Terraform in a team: plan in the PR, apply on merge

  1. Every pull request runs terraform fmt -check, terraform validate, a linter such as tflint, a config scan (trivy config, see DevOps chapter 11) and terraform plan, and posts the plan as a comment.
  2. The reviewer reads the plan, not just the code: "3 to add, 0 to change, 0 to destroy" is the line that matters.
  3. After merge, CI runs terraform apply on that same plan, using OIDC credentials (no stored keys) and the shared, locked remote state from chapter 5.

Nobody runs apply from a laptop against prod. That one rule prevents most Terraform disasters.

Common mistakes

  • Hard-coding names and sizes so dev and prod need separate copies of the code. Make them variables and keep one module.
  • Using count for named things, then watching Terraform rebuild half of them after one deletion. Use for_each.
  • Secrets in .tfvars files committed to Git. Pass them as TF_VAR_ environment variables from the CI secret store, or read them from a secrets manager with a data source. Remember the state file still contains them, so keep state encrypted and private.
  • Renaming without a moved block, and a "simple refactor" plan wants to destroy a database. Always read the plan.
  • Huge root modules where one plan takes ten minutes and touches everything. Split by lifetime and owner: network, data, apps.

Questions

Pick an answer. Get it wrong and you can try again right away, no waiting. 10 questions per topic - pick a filter below, then use Recreate questions for a fresh set on that topic.

Fresh questions every time

Exam

A mixed test across the whole site, shuffled so you never know which topic comes next. When you submit, every mistake comes with the reason and a jump to the exact moment in the video that explains it.

30 questions 6 topics 20 minute limit Up to 70 XP
1–4 answer · ←→ move
History

Essay

0 / 200-250 words
Sample answer
History
0:00 / 0:00
Not started

on YouTube
Subscribe

Topic progress

Activity

Achievements

Settings

Your profile and your account.

Profile details

* Required. Saved in this browser until you sign in.

Letters, numbers, dots, dashes and underscores.
0 / 160

Account

Checking…

App

Install Stackwise on your phone or computer. It opens in its own window from your home screen, and the Docs and cheat sheets you've opened keep working without internet.

Only admins can see this

Dashboard

Sign-ups, activity, messages and reviews in one place.

Prove it

Certificates

Pass a topic's test and get a certificate with its own public page you can share or add to LinkedIn. Each test is 10 questions drawn at random and graded on the server; you need 8 right, you have 15 minutes, and you get one try per topic a day.

From first command to production

Linux for DevOps

A path through Linux the way DevOps engineers use it: ten stages, every command explained with its flags, examples, real output and mistakes, the combinations engineers chain together, and incidents worked through step by step. Practise everything in a safe lab folder.

Before the interview

Interview prep

Questions that come up in real DevOps interviews, with the kind of answer that lands. Say yours out loud first, then compare. Each one links to the chapter that goes deeper.

    Private to you

    My notes

    Everything you wrote down while watching and reading, in one place. Saved to your account, never shown to anyone.