If you work with Terraform you might know the struggle setting the right environment variables. Especially if you work with different Terraform configurations on a daily basis.

I found 2 tools (or a tool and a script) to make this much easier. The first is direnv which automagically sources env variables stored in a .envrc file if you change in a managed directory.

$ mkdir direnv-test
$ echo "export mykey=wasd" >> .envrc
$ cd .. && cd direnv-test

# direnv will show this error
direnv: error /home/andre/tmp/direnv-test/.envrc is blocked.
Run `direnv allow` to approve its content

$ direnv allow

$ cd .. && cd direnv-test
direnv: loading ~/tmp/direnv-test/.envrc
direnv: export +mykey

$ echo $mykey

And that’s it! Simply install direnv, create a .envrc, run direnv allow and all the needed env variables will be set when you change in the directory.

I mentioned 2 tools at the beginning and the second tool is a little script I use to get API tokens out of my password store. My password store is powered by gopass therefore it is pretty easy to script around it.

The setup is based on this blog post of Shibumi. Thanks for the idea!

Store this script in the same directory as your Terraform code.


cloud_api_key=$(gopass show --password tokens/cloud-project-token)

echo "{ \"cloud_api_key\": \"${cloud_api_key}\" }"

It will be called by the Terraform module external.

data "external" "cloud_api_key" {
  program = ["${path.module}/fetch-key.sh"]

provider "mycloud" {
  token = data.external.cloud_api_key.result.cloud_api_key

Terraform will use this script to get the needed token and that’s it.

This is so much better than going back in your shell history or use reverse search (and sometimes apply the wrong config to the wrong infrastructure).