Terraform Workspaces, Direnv, Dotenv, and Mental Sanity

Teracloud
1 min readOct 2, 2021

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. Read this tip form our Teraclouds experts.

Terraform workspaces direnv dotenv and mental sanity

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 that variables will be automatically loaded each time we run terraform workspace select <workspace>.

Teracloud is an AWS Advanced Consulting Partner specialized in Cloud Computing (AWS, Azure, GCP) best practices. We help SaaS of different industries around the world scale their business safely.

Contact our team at info@teracloud.io for an assessment. Let us handle migration, automation, deployment, performance, cost optimization and machine learning to make your business grow.

We make the cloud easy for you!

--

--

Teracloud

Our thoughts on everything Cloud, Expanding knowledge on our expertise and services