🧰 just iac it

closing opentofu's var-file gap with a justfile

tl;dr

Neither OpenTofu nor Terraform ties -var-file to the active workspace. A justfile fixes that without reaching for Terragrunt in teams where it is not yet utilised.

the problem

One main.tf, one workspace per environment, one .tfvars per environment.

  • It's minorly inconvenient to type -var-file=dev.tfvars manually on every command that accepts it
  • Nothing stops you pairing the wrong .tfvars with the wrong workspace, it just applies those values against whatever's currently selected.

This is documented in opentofu/opentofu#1053 and opentofu/opentofu#2509, and is actively discussed.

the solution

Derive -var-file from tofu workspace show instead of typing it. Here's a justfile that does that:

init app:
    tofu init -var="app_name="

workspace name:
    tofu workspace select -var-file=".tfvars"  || tofu workspace new -var-file=".tfvars" 

plan *args:
    tofu plan -var-file="$(tofu workspace show).tfvars" 

apply *args:
    tofu apply -var-file="$(tofu workspace show).tfvars" 

just workspace stg switches (or creates) environments, while just plan/just apply loads the matching file. This means only one thing to select, not two things to keep in sync.

The backend setup this assumes is one bucket per app, with workspaces doing the environment split. Because of this, ensure your state file IAM is appropriate to your infrastructure team! 🔒