Purpose of Variables in Terraform
- Variables prevent repetitive hardcoding of values in Terraform configuration files.
- They reduce errors due to inconsistent value entries across multiple resources.
- Simplify updating environment-specific configurations (e.g., changing from
devtostage).
Types of Variables Based on Purpose
Input Variables: Accept values from users or other sources.
Output Variables: Display or pass resource attributes after creation.
Locals: Define reusable, local values within a Terraform module for simplification and consistency.
Variable Types Based on Value
Primitive Types: string, number, bool(boolean).
Complex Types: list, set, map, object, tuple.
Special Types:
null (no specific type defined).
any (auto-detects type based on assigned value).
Variable Declaration Syntax
Basic format:
variable "environment" {
default = "dev"
type = string
}
Accessing variables in Terraform uses the syntax:
- For simple reference:
var.environment - For string interpolation:
"${var.environment}-bucket"
Locals Usage
Locals are defined using the locals block to store computed or concatenated values.
Example:
locals {
bucket_name = "${var.environment}-bucket"
}
Output Variables
Output variables allow capturing and displaying resource attributes after Terraform applies changes.
Example declaration:
output "vpc_id" {
value = aws_vpc.sample.id
}
Variable Precedence in Terraform
Terraform supports multiple methods to assign values to variables. These methods have a clear precedence hierarchy from lowest to highest:
1 (Lowest) Default value in variable block - Value assigned within the variable declaration as default.
2 Environment variables prefixed with TF_VAR_ - Shell environment variables such as export TF_VAR_environment=stage.
3 Variable definition files (.tfvars or .tfvars.json) - Separate files like terraform.tfvars with key-value pairs.
4 (Highest) Command-line flags (-var, -var-file) - Values passed directly during terraform plan or terraform apply.
- Using environment variables or command-line flags allows dynamic overrides without changing Terraform files.
-
.tfvarsfiles are preferred for organising variables when multiple environments or parameter sets are used. - Sensitive data (e.g., credentials) should be managed carefully, preferably using secret management tools instead of environment variables or command-line flags to avoid exposure in shell history.
Best Practices and Recommendations
- Use variables and locals to improve code reusability, consistency, and maintainability.
- Prefer
.tfvarsfiles for variable management in multi-environment setups. - Use output variables to expose important resource attributes for downstream use.
- Validate resource names and types against the latest Terraform AWS provider documentation.
- Manage sensitive variables securely outside of Terraform files.
- Clean up resources after testing with
terraform destroy -auto-approveto avoid unnecessary costs.
Top comments (0)