Introduction
This article describes a method for reading environment variables using Terraform that makes their values available for use in the Terraform configuration.
Expected Outcome
An
external
data source will contain the environment variable values of interest, and those values can be used in the Terraform configuration.
Prerequisites
- Set an environment variable that is accessible by Terraform.
- MacOS and Linux shell:
export foo=bar
- Powershell:
$Env:foo = "bar"
- In Terraform Cloud or Enterprise, create an environment variable, not a terraform variable, with the name
foo
and valuebar
.
Use Case
Terraform can directly access environment variables that are named using the pattern
TF_VAR_
, for example TF_VAR_foo=bar
will provide the value bar
to the variable declared using variable "foo" {}
.Accessing environment variable values that are not defined in this manner can be accomplished using the
external
data source.Procedure
- Create a configuration, or add to an existing configuration, an
external
data source that will execute a script.
# Run the script to get the environment variables of interest.
# This is a data source, so it will run at plan time.
data "external" "env" {
program = ["${path.module}/env.sh"]
# For Windows (or Powershell core on MacOS and Linux),
# run a Powershell script instead
#program = ["${path.module}/env.ps1"]
}
# Show the results of running the data source. This is a map of environment
# variable names to their values.
output "env" {
value = data.external.env.result
}
# This outputs "bar"
output "foo" {
value = data.external.env.result["foo"]
}
- Create the
env.sh
script that will output a JSON object that is a map of strings containing the environment variable names and their values. Make the script executable with, e.g.,chmod u+x env.sh
.
#!/bin/sh
# env.sh
# Change the contents of this output to get the environment variables
# of interest. The output must be valid JSON, with strings for both
# keys and values.
cat <<EOF
{
"foo": "$foo",
"another_env_var": "$another_env_var"
}
EOF
- For Windows or Powershell core on other platforms, the above script would be similar to the following.
ConvertTo-Json @{
foo = $Env:foo
}
- Run
terraform plan
orterraform apply
to see the outputs contain the environment variable values.