top of page

Terraform workspaces, direnv, dotenv, and mental sanity

  • Writer: Carlos Barroso
    Carlos Barroso
  • Jun 15, 2021
  • 1 min read

Updated: Sep 8


""

Once you have all your environments working with Direnv, Advanced Direnv for Devops, if you are working with Terraform namespaces, there is another improvement you can make to automate further.


We use another directive from direnv called watch_file, which reloads the environment each time a particular file is changed. We can point this directive to the .terraform/workspace file, which holds the currently selected workspace in Terraform. The following code in the .envrc file implements this behavior:


watch_file .terraform/environment

if test -e .terraform/environment; then

 dotenv .env.$(cat .terraform/environment)

fi

This technique allows us to have different variables (defining accounts, regions, usernames, more) per environment, and those variables will be automatically loaded each time we run terraform workspace select <workspace>.


For teams looking to further streamline Terraform automation and maintain consistency across projects, exploring reusable GitHub workflows for streamlined Terraform automation can significantly reduce errors and improve efficiency.


""




Carlos Barroso

Head of AI






bottom of page