[Virtual Event] IaCConf 2026: Real stories on how infra teams are keeping pace

Register Now ➡️

Terraform

How to Set & Use Terraform Environment Variables

An Introduction to Terraform Environment Variables

Terraform environment variables give you a flexible way to pass configuration, credentials, and behavioral settings to Terraform without hardcoding values in your .tf files. This article covers what they are, when to use them, and how to set each one with practical examples.

We will cover:

  1. How to set the Terraform environment variables?
  2. How to read and use environment variables in Terraform runs?
  3. Different types of Terraform environment variables
  4. Custom environment variables in Terraform modules
  5. Example: Using provider-specific Terraform environment variables

What is a Terraform environment variable?

A Terraform environment variable is a key-value pair set within the environment where Terraform is running. Terraform refers to a number of environment variables to customize various aspects of its behavior. They can be used, for example, to specify the location of the Terraform configuration files, set provider credentials, or define backend configurations. These variables provide configuration information to Terraform without having to hardcode it into the configuration files.

How to set the Terraform environment variables?

Environment variables can be set on the command line, within scripts, or by using the operating system’s environment variable settings.

For reference, using the GUI in a Windows OS, they can be set under System Properties → Advanced → Environment Variables → New system variable.

new system variable - terraform environment variables
new system variable TF LOG - terraform environment variables

On the command line in a Windows system, you can use the SET command as an equivalent to the export on Linux based system, and view the current value using %<variable name>%:

set TF_LOG=trace
%TF_LOG%

In Spacelift, environment variables can be defined directly on stacks and modules, as well as on contexts attached to those. Read more about using environment variables in our documentation.

How to read and use environment variables in Terraform runs?

To read and use environment variables in Terraform runs, you simply need to define a Terraform variable, and then add a value for it in the environment:

variable "name" {
   type = string
}

For example, if your variable is called name, as above, you will need to save its value in an environment variable called TF_VAR_name. Terraform checks the environment when you are running the code, and to ensure that you can name your variable however you want, it checks for names that are prefixed with TF_VAR.

Different types of Terraform environment variables

Terraform supports several types of environment variables for configuring and managing various aspects of your infrastructure. Here are the main types of environment variables used in Terraform.

Variable Description
TF_VAR_<name> Sets a value for a matching Terraform input variable at runtime, e.g. TF_VAR_region=us-east-1
TF_LOG Controls log verbosity; accepted values are TRACE, DEBUG, INFO, WARN, ERROR, JSON, or OFF
TF_LOG_PATH Writes log output to a specified file path instead of stderr; requires TF_LOG to be set
TF_INPUT Disables interactive prompts for unset variables when set to 0 or FALSE; useful in automation
TF_CLI_ARGS Appends additional arguments to all Terraform CLI subcommands
TF_CLI_ARGS_<command> Appends additional arguments to a specific CLI subcommand only, e.g. TF_CLI_ARGS_plan
TF_DATA_DIR Overrides the default .terraform directory where Terraform stores working data and plugins
TF_WORKSPACE Sets the active Terraform workspace, equivalent to running terraform workspace select
TF_IN_AUTOMATION Suppresses next-step command suggestions in Terraform output when running in CI/CD pipelines
TF_CLI_CONFIG_FILE Specifies the path to a custom Terraform CLI configuration file (.terraformrc or terraform.rc)
TF_IGNORE Set to trace to print debug messages showing which files are excluded by .terraformignore
TF_REGISTRY_DISCOVERY_RETRY Sets the maximum number of retries for failed registry discovery requests
TF_REGISTRY_CLIENT_TIMEOUT Overrides the default 10-second timeout for requests to the remote registry
TF_STATE_PERSIST_INTERVAL Overrides the default 20-second interval for persisting state to a remote backend (value in seconds)
TF_PLUGIN_CACHE_DIR Specifies a directory for caching downloaded provider plugins across runs and projects

The following examples in this article use the export command, which is native to Linux and MacOS (but is not available on Windows OS).

1) TF_VAR_name

As well as defining variables using a .tfvars files and directly on the command line, this environment variable can be used to set values for variables in your Terraform configuration.

Note that defining variables this way is a fallback if variable values are not found elsewhere.

The variable name you want to set the value for should be in the format _name, e.g., for a variable named region, you would specify TF_VAR_region as the variable name. This can be useful when running Terraform in automation, or when running a sequence of Terraform commands in succession with the same variables.

export TF_VAR_region=uksouth
export TF_VAR_regionlist='[uksouth,ukwest,useast2]'
export TF_VAR_tagmap='{ Environment = "dev", Project = "demo" }'

2) TF_LOG

The TF_LOG variable enables detailed logs in stderr, for debugging purposes:

export TF_LOG=trace

You can set TF_LOG to one of the log levels (in order of decreasing verbosity) TRACEDEBUGINFOWARN or ERROR to change the verbosity of the logs.

Setting TF_LOG to JSON outputs logs at the TRACE level or higher, and uses a parseable JSON encoding for formatting.

You can turn off logging when you have finished debugging:

export TF_LOG=off

3) TF_LOG_PATH

When TF_LOG is set, you can also use the TF_LOG_PATH variable to set the location where the log should persist its output to. The below example logs to a file called terraform.log in the local directory.

export TF_LOG_PATH=./terraform.log

4) TF_INPUT

TF_INPUT environment variable is useful when you want to replicate the -input=false flag behavior from the command line in an environment variable by specifying a value of 0 or FALSE. This disables prompts for input for variables that have not been specified.

export TF_INPUT=0

5) TF_CLI_ARGS and TF_CLI_ARGS_name

TF_CLI_ARGS is used to specify additional arguments to the command line. Arguments are inserted directly after the subcommand (such as plan) and before any flags specified directly on the command line. This behavior ensures that flags on the command line take precedence over environment variables.

For example, to run terraform plan with the debug mode enabled and specify the location of the state file, you can set the TF_CLI_ARGS variable to -state=terraform.tfstate -debug, which will pass the -state and -debug options to Terraform CLI.

export TF_CLI_ARGS="-state=terraform.tfstate -debug"

When the terraform plan command is run, Terraform uses the state file specified and outputs additional debugging information to the console.

A named command can also be specified, which will only affect that command. This is done using the TF_CLI_ARGS_name variable.

For example, to specify that only plans never refresh:

export TF_CLI_ARGS_plan="-refresh=false"

6) TF_DATA_DIR

By default, Terraform working data is written into a .terraform subdirectory of the current directory. The TF_DATA_DIR can be used to change the path where this data is held (useful in rare cases where the working directory is not writeable).

In automation, this must be set at each stage of the Terraform workflow for each command, e.g. terraform init , terraform plan , terraform apply — as each command will need to reference the working directory if it is changed from the default to find modules and configuration information.

export TF_DATA_DIR=./mydirectory/terraform

7) TF_WORKSPACE

This is the environment variable equivalent of setting your workspace using:

terraform workspace select my_workspace_name

This is useful in automation as it overrides any workspace selection but is not recommended when using Terraform interactively as it is easy to set and forget, which might cause inadvertent changes to the wrong Terraform state.

For example:

export TF_WORKSPACE=my_workspace_name

8) TF_IN_AUTOMATION

This is a variable used to set a purely cosmetic change to Terraform’s human-readable output, which prevents it from suggesting specific commands to run next after one command has been completed.

In automation, this wouldn’t be possible as the environment is non-interactive, so removing these suggestions makes the output less confusing. To use it, set it to any non-empty value.

export TF_IN_AUTOMATION=true

9) TF_CLI_CONFIG_FILE

Used to specify the location of the Terraform CLI configuration file. This is a file specified as .terraformrc or terraform.rc which configures per-user settings for CLI behaviors that apply across all Terraform working directories.

export TF_CLI_CONFIG_FILE=”./mydirectory/.terraformrc-custom”

10) TF_IGNORE

When debugging large repositories with .terraformignore files, the TF_IGNORE variable can be used to get Terraform to output debug messages to display ignored files and folders. It should be set to trace .

Files listed in a .terraformignore plan are simply a list of files that should not be considered as part of the configuration to speed up deployments when a large number of file exist.

export TF_IGNORE=trace

11) TF_REGISTRY_DISCOVERY_RETRY

Set TF_REGISTRY_DISCOVERY_RETRY to configure the max number of request retries, the remote registry client will attempt for client connection errors or 500-range responses that are safe to retry.

export TF_REGISTRY_DISCOVERY_RETRY=10

This example sets the value of TF_REGISTRY_DISCOVERY_RETRY to ten, which means that registry discovery operations will be retried up to ten times before failing.

12) TF_REGISTRY_CLIENT_TIMEOUT

This variable can be configured to increase the default client timeout to the remote registry during extraneous circumstances.

The default client timeout for requests to the remote registry is 10s.

export TF_REGISTRY_CLIENT_TIMEOUT=30

13) TF_STATE_PERSIST_INTERVAL

By default, Terraform persists the state to a remote backend every 20 seconds, but this value can be overridden by setting the TF_STATE_PERSIST_INTERVAL. Keep in mind that if you define a value lower than the minimum allowed for the backend, Terraform will default to the backend’s minimum interval. The value must be specified in seconds:

export TF_STATE_PERSIST_INTERVAL=50

14) TF_PLUGIN_CACHE_DIR

The TF_PLUGIN_CACHE_DIR is used to specify a directory where Terraform can cache provider plugins. This allows Terraform to reuse the same plugins across multiple projects or runs, rather than downloading them every time when terraform init runs.

export TF_PLUGIN_CACHE_DIR="$~/.terraform.d/plugin-cache"

Custom environment variables in Terraform modules

If you are using a module, and when you are specifying the variables for it, you can add values to them with environment variables.

Let’s take a look at a simple example. Suppose you have the following module that generates random pet names:

resource "random_pet" "this" {
 prefix = var.prefix
}

variable "prefix" {
 type = string
}

Now, let’s call the module:

module "pet" {
   source = "./module"
   prefix = var.prefix
}

variable "prefix" {
 type = string
}

Next, let’s add an environment variable for the prefix:

export TF_VAR_prefix=dog

If we apply the code, we will see that our random pet name will be generated with the dog prefix we’ve set above:

+ resource "random_pet" "this" {
     + id        = (known after apply)
     + length    = 2
     + prefix    = "dog"
     + separator = "-"
   }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
 Terraform will perform the actions described above.
 Only 'yes' will be accepted to approve.

 Enter a value: yes

module.pet.random_pet.this: Creating...
module.pet.random_pet.this: Creation complete after 0s [id=dog-evolved-dane]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Example: Using provider-specific Terraform environment variables

For this example, we will use the AWS provider. There are many ways in which you can configure authentication, but we will explore the most basic one, which is using an access key and a secret key. This is what it looks like with hardcoded values:

provider "aws" {
 region     = "eu-west-1"
 access_key = "my-access-key"
 secret_key = "my-secret-key"
}

AWS lets us source credentials in multiple ways (parameters in the provider configuration, environment variables, shared credentials files, and more). If we want to use environment variables, the AWS provider automatically reads values from the following variables:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN
  • AWS_REGION
  • AWS_DEFAULT_REGION

So you can set these if you’d like, by simply doing an export in your CLI. I will also show you how to configure custom ones by defining variables inside your Terraform configuration:

provider "aws" {
 region     = var.region
 access_key = var.access_key
 secret_key = var.secret_key
}

variable "region" {
   type = string
}

variable "access_key" {
   type = string
}

variable "secret_key" {
   type = string
}

Now to provide environment variables for these we could run the following in our terminal:

export TF_VAR_region="region"
export TF_VAR_access_key="access_key"
export TF_VAR_secret_key="secret_key"

Ensure you change the values to the ones from your AWS account, and that’s it.

Why use Spacelift with Terraform?

Terraform is really powerful, but to achieve an end-to-end secure GitOps approach, you need a platform that can orchestrate your Terraform workflows. Spacelift is the infrastructure orchestration platform built for the AI-accelerated software era. 

It manages the full lifecycle for both traditional infrastructure as code (IaC) and AI-provisioned infrastructure, giving you access to a powerful CI/CD workflow and unlocking features such as:

  • Policies (based on Open Policy Agent) – You can control how many approvals you need for runs, what kind of resources you can create, and what kind of parameters these resources can have, and you can also control the behavior when a pull request is open or merged.
  • Multi-IaC workflows – Combine Terraform with Kubernetes, Ansible, and other IaC tools such as OpenTofu, Pulumi, and CloudFormation, create dependencies among them, and share outputs.
  • Build self-service infrastructure – You can use Templates and Blueprints to build self-service infrastructure; simply complete a form to provision infrastructure based on Terraform and other supported tools.
  • AI-powered provisioning and diagnosticsSpacelift Intelligence adds an AI-powered layer for natural language provisioning, diagnostics, and operational insight across your infrastructure workflows.
  • Integrations with any third-party tools – You can integrate with your favorite third-party tools and even build policies for them. For example, see how to integrate security tools in your workflows using Custom Inputs.

Spacelift enables you to create private workers inside your infrastructure, which helps you execute Spacelift-related workflows on your end. Read the documentation for more information on configuring private workers.

You can check it for free by creating a trial account or requesting a demo with one of our engineers.

Key points

Terraform environment variables provide a flexible and secure way to manage configuration information, making it easier to use Terraform in a variety of environments and scenarios.

Environment variables are not required when using Terraform, but they can be helpful to change some of Terraform’s default behaviors in unusual situations.

Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

Achieve Terraform at scale

Spacelift effectively manages Terraform state and more complex workflows, and supports policy as code, programmatic configuration, context sharing, drift detection, resource visualization, and more.

Learn more

Frequently asked questions

  • Are Terraform environment variables secure?

    Environment variables are not encrypted by default and can leak through process listings, shell history, or CI logs, so use a secrets manager like Vault, AWS Secrets Manager, or masked CI variables for sensitive values.

  • What's the difference between TF_VAR_ and .tfvars?

    TF_VAR_<name> injects a variable through the environment at runtime, while .tfvars files store variable assignments in version-controllable files that Terraform loads automatically or via -var-file.

  • How do I set Terraform environment variables in GitHub Actions?

    Define them under an env: block at the workflow, job, or step level using the TF_VAR_<name> prefix, typically sourced from ${{ secrets.* }}. Terraform automatically picks up any TF_VAR_<name> value as input for the matching variable in your configuration.

  • Do TF_ environment variables work with OpenTofu?

    Yes, OpenTofu fully honors the TF_VAR_ prefix and other TF_ variables (like TF_LOG, TF_DATA_DIR, TF_WORKSPACE) for backward compatibility with Terraform configurations and CI/CD pipelines.

  • What is the order of precedence for Terraform variable resolution?

    From lowest to highest: variable defaults, environment variables (TF_VAR_*), terraform.tfvars, terraform.tfvars.json, *.auto.tfvars and *.auto.tfvars.json (lexical order), then -var and -var-file flags on the command line in the order provided. Later sources override earlier ones.

Article sources

HashiCorp Developer | Terraform Docs. Terraform CLI environment variables reference. Accessed: 21 October 2025

HashiCorp Developer | Terraform Docs. Customize Terraform configuration with variables. Accessed: 21 October 2025

Terraform Essential Components Cheat Sheet

Whenever you’re embarking on a new journey

or seeking to refine your foundational knowledge.

Share your data and download the cheat sheet