Environment variables (TF_VAR_) in Terraform - Time & Space Complexity
We want to understand how using environment variables with Terraform affects the number of operations Terraform performs.
Specifically, how does the number of environment variables influence Terraform's processing steps?
Analyze the time complexity of Terraform reading environment variables prefixed with TF_VAR_.
# Terraform automatically loads environment variables starting with TF_VAR_
# Example:
# export TF_VAR_region="us-west-1"
# export TF_VAR_instance_count="3"
variable "region" {
type = string
}
variable "instance_count" {
type = number
}
This sequence shows Terraform reading environment variables to set input variables before applying configuration.
Terraform scans environment variables to find those starting with TF_VAR_.
- Primary operation: Checking each environment variable for the
TF_VAR_prefix and loading its value. - How many times: Once per environment variable present in the system.
As the number of environment variables increases, Terraform checks each one to see if it starts with TF_VAR_.
| Input Size (n) | Approx. Env Vars Checked |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of checks grows directly with the number of environment variables.
Time Complexity: O(n)
This means the time to load environment variables grows in a straight line as the number of variables increases.
[X] Wrong: "Terraform only reads the environment variables that match my variables, so the number of checks is small."
[OK] Correct: Terraform actually scans all environment variables to find those starting with TF_VAR_, so the total number of environment variables affects the work done.
Understanding how Terraform processes environment variables helps you explain how input size affects configuration loading time in real projects.
What if Terraform cached environment variables after the first scan? How would that change the time complexity?