Introduction
This article describes two methods for reading environment variables in Terraform runs, making their values available for use within your configuration.
Prerequisites
- An environment variable is set in the shell where you run Terraform.
Procedure
Terraform offers two primary ways to access environment variables: using a specific variable name prefix or using the external data source for more complex cases.
Method 1: Using the TF_VAR_ prefix
Terraform can directly read environment variables that are prefixed with TF_VAR_. To use this method, declare a Terraform variable and then set a corresponding environment variable in your shell.
-
Declare a variable in your Terraform configuration (e.g., in
variables.tf).variable "foo" { type = string default = "default-value" } -
Set an environment variable in your shell using the format
TF_VAR_<variable_name>.$ export TF_VAR_foo="bar"
When you run Terraform, it automatically assigns the value bar to the foo variable, overriding its default value.
Method 2: Using the external data source
For environment variables that do not follow the TF_VAR_ naming convention, you can use the external data source to run a script that returns the variable values as a JSON object.
-
Define the
externaldata source in your configuration. This data source executes a script at plan time.# Run a script to get the environment variables of interest. data "external" "env" { program = ["${path.module}/env.sh"] # For Windows (or PowerShell Core on macOS and Linux), # you can run a PowerShell script instead. # program = ["powershell", "-File", "${path.module}/env.ps1"] } # Output the entire map of environment variables returned by the script. output "env_map" { value = data.external.env.result } # Access a specific variable from the map. # This example outputs "bar" if the script returns it. output "foo_value" { value = data.external.env.result["foo"] } -
Create the script that the data source will execute. This script must output a valid JSON object containing string keys and values.
For Linux and macOS, create
env.sh.#!/bin/sh # env.sh # This script outputs a JSON map of environment variables. # The output must be valid JSON, with strings for both keys and values. cat <<EOF { "foo": "$foo", "another_env_var": "$another_env_var" } EOF -
Make the script executable.
$ chmod u+x env.sh
-
For Windows or PowerShell Core users, create an
env.ps1script as an alternative.# env.ps1 # This script outputs a JSON map of environment variables. $env_vars = @{ foo = $Env:foo another_env_var = $Env:another_env_var } ConvertTo-Json -InputObject $env_vars -Compress - Run
terraform planorterraform applyto see the outputs populated with the environment variable values.
Additional Information
- For more details, refer to the external data source documentation.