Storing Values (e.g. Secrets) in Environment Variables with Terraform – Output Raw

Firstly, a disclaimer. Although you can store values, specifically secrets (e.g. passwords) within Environment Variables so that you are not storing them in your Terraform template code there are better ways, for example by use of a formal Secrets Management solution. However, this article will show you how you can use Environment Variables to “safely” inject/interpolate values into your Terraform at runtime without having them stored plain text in your templates or having to enter them manually each time you run a Terraform Apply or Terraform Plan.

Firstly you need to name your environment variables prepended with TF_VAR_ by doing this Terraform will read in any environment variable which is prepended with this string, so in our case we’re going to create two environment variables called: TF_VAR_TUNNEL1_PRESHARED_KEY and TF_VAR_TUNNEL2_PRESHARED_KEY

Below is a cheeky BASH script that you can use to populate the keys, you keep this outside of your repository, somewhere safe on your machine if it is storing sensitive values.

preshared-keys.sh

#!/bin/bash

export TF_VAR_TUNNEL1_PRESHARED_KEY="<key>"
export TF_VAR_TUNNEL2_PRESHARED_KEY="<key>"

Source the values:

source ~/preshared-keys.sh

You’re all set.

Within your Terraform you refer to the values by the end part of the name, i.e. the environment variable: TF_VAR_TUNNEL1_PRESHARED_KEY would become the variable: TUNNEL1_PRESHARED_KEY within Terraform.

variable "TUNNEL1_PRESHARED_KEY" {
  description = "AWS VPN Preshared Key 1"
  type        = string
  sensitive   = true
}

variable "TUNNEL2_PRESHARED_KEY" {
  description = "AWS VPN Preshared Key 2"
  type        = string
  sensitive   = true
}

Now you can use these variables as you normally would throughout your Terraform. For example:

  tunnel1_preshared_key = var.TUNNEL1_PRESHARED_KEY
  tunnel2_preshared_key = var.TUNNEL2_PRESHARED_KEY

Although not something to use in production, but if you needed to prove this was really working as expected, using say a dummy value. You can see the contents by adding this output:

output "tunnel1_key" {
    value = var.TUNNEL1_PRESHARED_KEY
    sensitive = true
}

Then show the value with:

terraform output -raw tunnel1_key

As an example.

https://support.hashicorp.com/hc/en-us/articles/5175257151891-How-to-output-sensitive-data-with-Terraform

Leave a comment