In the Using Variables In Terraform lecture of the Terraform course, it’s explained how the variable precedence works. I think it’s rather confusing to have them listed from bottom to top, when the logical and intuitive way would be the other way around. If I say
“Terraform loads variables in the following order”
and stop the sentence there, it’s implied that what follows is a list of items sorted in the desired order. I realize the official documentation does this differently and reverses the order with:
with later sources taking precedence over earlier ones
but this doesn’t make things easier to understand. I would suggest this to be updated in future iterations of the course.
The lecture lists the precedence in the same order as the official documentation.
environment variables - lowest precedence listed first
command line arguments - highest precedence listed last
This is the order in which terraform checks for variables.
When you run a plan or apply, then it will, in this specific order do
- If it sees an env var e.g.
TF_VAR_filename
set to /root/cats/txt
it will say: ok, filename = "/root/cats/txt"
- Say there’s not a
terraform.tfvars
file, or there is but it doesn’t define filename, then the value from #1 is still in force.
- Similarly for
*.auto.tfvars
- If there’s
-var filename=/root/dogs.txt
then that will override the value for above and be the final value for that variable.
Hi Alistair, thank you for the response.
I understand that is how it’s documented. I’m only making a suggestion to rephrase this content in the course, as it’s counter-intuitive. I should probably send the same feedback to Hashicorp
Maybe
Our course does it the way Hashicorp does as you’ve seen. If you come from a programming background it isn’t counter-intuitive as it’s in the execution order of the program itself - store the value found at the lowest precedence, then check all other sources up to the highest, replacing the stored value if you find a new value.
1 Like
Mmm I suppose that makes sense once you’re used to it. I’ll try to keep that in mind, thanks again!