Problem
When managing variable values in an HCP Terraform or Terraform Enterprise workspace, two common methods are configuring them directly in the workspace's Variables section or including a Terraform variable definition file in your configuration.
By default, Terraform automatically loads variables from files named terraform.tfvars, terraform.tfvars.json, and any files with names ending in .auto.tfvars or .auto.tfvars.json. Using an .auto.tfvars file applies the same variable values to all workspaces that use the same Terraform configuration, such as multiple workspaces connected to a single version control system (VCS) repository.
Use Case
In some scenarios, you may need to maintain several distinct variable definition files within a single Terraform configuration and direct each HCP Terraform or Terraform Enterprise workspace to use a specific file for its runs.
Procedure
Follow these steps to configure a workspace to use a specific variable definition file.
- Create one or more Terraform variable definition files with names that do not end in
.auto.tfvars(for example,dev.tfvarsorprod.tfvars). Commit these files to the VCS repository connected to your workspace(s). - Navigate to the desired workspace in the HCP Terraform or Terraform Enterprise UI.
- Select Variables from the workspace's settings menu.
-
Add a new Environment Variable with the following details:
-
Key:
TF_CLI_ARGS_plan -
Value:
-var-file="myfile.tfvars"
Replace
myfile.tfvarswith the path to your variable definition file, relative to the workspace's configured working directory. -
Key:
- To ensure the variables are also available during the apply phase, create a second environment variable with the same value:
-
Key:
TF_CLI_ARGS_apply -
Value:
-var-file="myfile.tfvars"
-
Key:
After saving these variables, subsequent runs in this workspace will load variables from the specified file.
Additional Information
- For more details on this feature, refer to the documentation on specifying command-line arguments via environment variables.
- For general information on workspace variables, see the guide on managing variables in HCP Terraform.