This guide will look at Terraform variables and how you can use them in your daily cloud operations.
There are three main ways of providing variables to Terraform configurations. These methods include:
- Environment Variables
- Variable files such as variables.tf or variables.tfvars files
- Command-line arguments using the -var option in the commands.
You can use either method or both when declaring variables in a Terraform configuration. However, if you provide the same variable with different values, Terraform will use the last value encountered, overriding previous values.
Terraform variable precedence is as follows: the top sources prioritize higher than those in the lower levels.
- Environment variables
- *.auto.tfvars or *.auto.tfvars.json
- -var or -var-file.
What is a Variable
Variables, also known as input variables, are parameters that allow various aspects of Terraform modules to be customized without the need to edit the module’s source code. Variables provide flexibility in the Terraform configurations allowing modules to be shared between various configurations.
Variable Definitions (.tfvars) Files
If you want to set variables in Terraform, it is recommended to specify their values in a file. The file holding variable definition is known as a variable definition file. A variable definition file in Terraform ends in .tfvars or .tfvars.json.
To specify a variable definition file in the command, use the -var-file followed by the path to the file.
terraform apply -var-file=”variables.tfvars”
.tf vs .tfvars
There is a concept in Terraform that tends to be confusing. What is the difference between *.tfvars and *.tf files.
.tfvars files are used to define variables. They are also known as variable definition files while .tf files are used to declare variables.
The variable declaration refers to the process of declaring an intention to create an object but does not hold a value.
On the other hand, the Variable definition means assigning a value to a declared variable.
This simple guide outlines the purpose of variables and the .tfvars file in Terraform configurations. Check the documentation to learn more.