Infrastructure as code (IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools. The IT infrastructure managed by this process comprises both physical equipment, such as bare-metal servers, as well as virtual machines, and associated configuration resources. IaC offers benefits including faster time to production and market; improved consistency; efficient and more innovative development; and lower costs.
In this short technical article, we will discuss how to secure Terraform environment variable secrets at rest.
Terraform is an open-source infrastructure as code software tool created by HashiCorp. Users define and provide data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language (HCL), or optionally JSON.
Terraform is a great tool for automating your infrastructure. We have been using it recently to capture some OpenStack infrastructure as code (IaC). I am reading through the 2nd edition of Terraform: Up & Running by Yevgeniy Brikman. I just finished reading chapter 3 which is about managing your Terraform state. One of the sidebars was about secrets.
One of the best practices with IaC is to make sure your secrets never wind up in your source repositories. Terraform has the ability to accept environment variables as parameters which would certainly make life easier if we put them in our shell startup script. But how can we set up environment variables as Terraform parameters without storing our passwords in plain text in say .zshrc or in our shell history? A solution proposed in chapter 3 is to use a tool like http://passwordstore.org to secure your secrets at rest.
For this solution, you will need a GPG key, the password manager from http://passwordstore.org. You will modify your .zshrc to invoke new environment variables and modify your .tf files to use those variables.
If you need a gpg key run this command and follow the prompts:
Choose RSA + RSA, use key size 4096, set the key expiry and enter your details.
You will get some output that looks like this:
Next step install pass: the standard unix password manager. Note that you’ll need the key id (866F4C51D21B52CA)from the previous step.
Add the Terraform environment variables you want to your .zshrc:
And then modify your var.tf to leverage those new environment variables including the secrets:
Your main.tf will look something like this:
We hope you found this technical article useful.