Using Default Values with Variable Blocks
By assigning default values directly within your variable blocks, you ensure that Terraform uses these values if no alternative is provided. For example, consider the following configuration that creates a local file resource and a random pet resource:Providing Variable Values Interactively and via the Command Line
If a variable does not have a default value or if you want to override an existing default, Terraform will prompt you for a value duringterraform apply. To streamline automation and avoid interactive prompts, you can pass values using the -var flag. You can supply multiple -var flags as needed:
TF_VAR_. For example, you can configure your shell as follows:
Using Variable Definition Files
When managing many variables, it becomes practical to store their values in a dedicated variable definition file. These files typically have a.tfvars or .tfvars.json extension. For example, you can create a file named terraform.tfvars with the following contents:
terraform.tfvars, terraform.tfvars.json, or files with extensions like .auto.tfvars or .auto.tfvars.json. If you use a differently named file (e.g., variables.tfvars), be sure to specify it explicitly with the -var-file flag:
Variable Definition Precedence
Terraform allows you to set variable values from multiple sources. When the same variable is defined in multiple places, Terraform uses a specific order of precedence to determine which value to apply. Consider the following scenario where a variable is defined in various ways:-
Environment Variable:
-
terraform.tfvars File:
-
File Ending with .auto.tfvars:
-
Command-Line Flag:
| Precedence Level | Example Call or File |
|---|---|
1. Environment variables (TF_VAR_) | export TF_VAR_filename=“/root/cats.txt” |
| 2. terraform.tfvars file | filename = “/root/pets.txt” |
3. Files ending with .auto.tfvars or .auto.tfvars.json | filename = “/root/mypet.txt” |
4. Command-line flags (-var or -var-file) | terraform apply -var “filename=/root/best-pet.txt” |
-var) has the highest precedence in this example, the variable filename will ultimately be assigned the value /root/best-pet.txt.
Remember, the order in which variable values are applied ensures predictability in your deployment. This hierarchy allows you to override defaults and maintain control over your configuration settings.
That’s it for this lesson. With these variable assignment techniques, you’re ready to build flexible and maintainable Terraform configurations. Now, let’s head to the hands-on lab and put these concepts into practice!