by Andrew Pearce (Web Operations Profession)
I use Terraform to provision AWS infrastructure for an application. The app has 3 environments - development, preproduction and production - that have the same configuration.
Terraform workspaces are used to isolate the resources and to map certain values, such as what AWS account to provision to.
Variable definitions using tfvars
Variable definitions let you set values for lots of variables at once. They can read in automatically when you run a
terraform apply or
terraform plan instead of individually providing them with
You can provide values in Terraform’s syntax with
terraform.tfvars files, or in JSON format with
terraform.tfvars.json files are how I provide values specific to each environment.
I’ve been doing this for a while, but I recently found a new way to organise, define and access these values thanks to some improvements in the underlying Terraform language.
My old way of organising variables
I used to define maps for each variable. Each map held values for dev, preprod and prod:
tfvars.json had a lot of repeating dev, preprod, prod stanzas:
I would then access my values for each environment using a lookup function, matching the name of the environment:
This does have the advantage of being able to supply a default when the lookup fails to return a match.
My new way of organising variables
Now I am using objects to define many values:
Variables can now be organised by environment:
Values can now be accessed from the object using the environment name, which here is available in
I still have a need for variable maps, and the two can live alongside each other in the
Why I prefer this
For my purposes, this is much neater and easier to read. All the parameters for each environment are grouped together. Adding another environment would be as easy as copying the block and updating as necessary instead of adding a new line to each variable map.
I can’t speak to the performance improvements for terraform, but it has made my work faster.
You can read a full implementation of this on GitHub.