Environments with directories and tfvars
One root module per environment with its own backend, the same modules, and tfvars for the differences, plus the exact order Terraform picks values in.
Repository layouts for TerraformWorkspaces and what they are not
Environments with directories and tfvars
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A directory per environment gives each its own backend key, credentials and reviewable diff while calling the same modules.
- Terraform loads terraform.tfvars and *.auto.tfvars on its own; any other file such as prod.tfvars needs -var-file.
- Precedence runs default, TF_VAR_ env, terraform.tfvars, terraform.tfvars.json, *.auto.tfvars, then -var and -var-file in order given.
- A backend block cannot use variables, so a single directory with per-environment tfvars needs -backend-config at init time, and the two flags must match.
Making three environments that are alike but apart
Dev, staging and prod should run the same code at different sizes with different permissions. Two things pull in opposite directions. You want them alike, so a change proven in dev means something for prod. You want them apart, so a mistake in dev cannot reach prod and a developer who can change dev cannot change prod. Everything in this lesson is a way to get both.
The last lesson showed why workspaces give you alike without apart. The common fix is a directory per environment.
The shape
Each environment gets its own root module, with its own backend and its own values, and all of them call the same modules:
infra/
modules/web-service/
envs/
dev/app/
backend.tf # key = "dev/app/terraform.tfstate"
main.tf # module "web" { source = "../../../modules/web-service" ... }
terraform.tfvars
prod/app/
backend.tf # key = "prod/app/terraform.tfstate"
main.tf
terraform.tfvars
Each directory is a separate state, so each can have its own IAM role for CI. The diff between dev and prod is a normal file diff: diff -r envs/dev envs/prod shows exactly what is different, and a pull request that changes envs/prod is visible as such to reviewers and to CODEOWNERS rules. The cost is repetition, since main.tf is nearly the same in each, and that is what Terragrunt was built to reduce.
Ned in the Cloud’s video, the embed here, compares three ways to promote code: branches, folders and separate repositories. I default to folders because the whole difference between environments sits in one commit on one branch. That reasoning is mine, not a claim about what the video concludes.
Putting the differences in tfvars
A good environment directory has almost no code in it. The module call is the same everywhere, and the differences are values:
# envs/prod/app/terraform.tfvars
instance_type = "m7g.large"
min_size = 3
multi_az = true
# envs/dev/app/terraform.tfvars
instance_type = "t4g.small"
min_size = 1
multi_az = false
Terraform loads terraform.tfvars and any *.auto.tfvars automatically. Any other name, such as prod.tfvars, is loaded only if you pass it with -var-file. The documented precedence, lowest to highest, is the variable’s default, TF_VAR_ environment variables, terraform.tfvars, terraform.tfvars.json, *.auto.tfvars in lexical order, and then -var and -var-file in the order given.
I did not want to take the order on faith, so I wrote a small Python resolver that applies exactly that list to real files, and ran it. It is a stand-in for Terraform’s behaviour, written from the docs. The directory has a terraform.tfvars, a zz.auto.tfvars and a prod.tfvars:
$ python3 -I resolve.py .
instance_type = t3.small (from terraform.tfvars)
min_size = 3 (from zz.auto.tfvars)
region = eu-west-1 (from default)
$ TF_VAR_region=us-east-1 python3 -I resolve.py . -var-file prod.tfvars -var min_size=9
instance_type = m7g.large (from -var-file prod.tfvars)
min_size = 9 (from -var)
region = eu-central-1 (from -var-file prod.tfvars)
Look at the second run. The environment variable lost to the file passed with -var-file, and min_size came from -var, the last thing on the command line. The practical rule: *.auto.tfvars files silently beat terraform.tfvars, and a stray one left in a directory is a classic “why is it using that value” bug. Keep one source of values per directory and print it in CI.
One directory, many tfvars
There is a second layout that looks similar: a single root module with dev.tfvars and prod.tfvars beside it, selected with -var-file. It saves the repetition, but the backend is a problem. The docs say a backend block cannot refer to input variables, locals or data sources. To vary the state location you leave out arguments and pass them at init time with partial configuration:
terraform init -backend-config=prod.s3.tfbackend
terraform apply -var-file=prod.tfvars
Now two separate flags in two separate commands must agree. Run init for dev, then apply with prod.tfvars, and you have applied prod values to dev’s state. This is written from the backend documentation and I did not run it. If you use it, wrap both flags in one script or Makefile target and make CI the only thing that calls it, so the pairing cannot be typed wrong.
Naming and guard rails
Give every environment directory the same file names and the same module call shape, so a reviewer who has seen envs/dev/app can read envs/prod/app without learning anything new. Put the environment name in resource names and tags, so the console shows which copy you are looking at. And make CI, not a laptop, the only identity that can apply to prod, which is the benefit the separate backend and credentials were for.
Promotion
With directories the promotion path is a normal change: edit the module (or bump its version pin), apply dev, see it work, then apply staging and prod from the same commit or a later one. What you gain over a branch per environment is that the history of what prod looks like is the history of envs/prod. What you give up is automation for free: a tool such as CI with saved plans has to know which directories changed. Most pipelines use a path filter for exactly that.
About the video
The embed is Ned in the Cloud’s “Managing Multiple Environments with Terraform”, 20 minutes 39 seconds, October 2023. Its description says it compares using git branches, a folder structure and separate repositories, with Terraform, GitHub Actions and Azure as examples. I took that from the description and not from watching all of it, and judged it English from the title, description and channel and its English auto-caption track. It leans on Azure, but the layout argument does not depend on the cloud. The devops lesson on modules, environments and remote state also lists this video under deeper. Techielass’s 8-minute video in deeper is a short intro to tfvars files for several environments.
Where this fits
A directory per environment still leaves you with repeated backend.tf and provider.tf blocks. Terragrunt generates them.
Check yourself
A prod.tfvars file sits in the directory but nothing uses it. Why?
Only terraform.tfvars and *.auto.tfvars files load automatically. prod.tfvars must be passed with -var-file.
terraform.tfvars sets min_size = 2 and zz.auto.tfvars sets min_size = 3. Which wins?
3. *.auto.tfvars files rank above terraform.tfvars. -var or -var-file would beat both.
Why can you not write bucket = var.bucket in a backend block?
A backend block cannot refer to named values such as variables, locals or data sources. Use partial configuration with -backend-config.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.