Variables in Terraform
Video guide: Here.
In the world of Infrastructure as Code (IaC), Terraform stands out for its declarative approach to provisioning resources. But what happens when you need to deploy the same resource, say, an S3 bucket, across different environments like staging, development, and production? This is where variables become the fundamental building blocks of flexible and reusable configurations.
Terraform organises its variables into three distinct and purpose-driven types, each playing a crucial role in managing complexity and adaptability.
1. Input Variables: The Configuration's Parameters
Input variables are the parameters that allow users to customise a Terraform configuration without modifying the underlying code. They serve as the primary interface for injecting dynamic values into a module or root configuration.
A common analogy used for input variables is that they are like function parameters in traditional programming. They define what external information the configuration needs to run.
Defining and Using Input Variables
Input variables are typically defined in a dedicated file, often named variables.tf. A definition includes the variable's name, its expected data type, and an optional description and default value.
Terraform
variable "environment" {
description = "Environment name (staging, prod, dev)"
type = string
default = "staging" # Provides a fallback value
}
Within the main configuration file (main.tf), these values are referenced using the var. prefix, making the code dynamic:
Terraform
resource "aws_s3_bucket" "demo" {
bucket = var.bucket_name
tags = {
Environment = var.environment
}
}
Providing Values: The Precedence Hierarchy
Terraform offers multiple ways to supply values to input variables, and the order in which it checks and overrides these values is key to understanding its behaviour.
| Precedence | Source | Description |
| Highest | Command Line Flags | terraform plan -var="environment=production" |
tfvars Files | Explicitly loaded using -var-file="prod.tfvars" | |
terraform.tfvars | Automatically loaded file in the current directory. | |
| Environment Variables | Variables prefixed with TF_VAR_, e.g., export TF_VAR_environment="development". | |
| Lowest | Default Value | Defined in the variables.tf file. |
The Command Line flag offers the ultimate override, ensuring that a specific deployment run can be tailored without altering persistent files.
2. Local Variables: Computed Internal Values
Local variables, defined in locals.tf, are values computed and reused internally within the configuration. Unlike input variables, they are not intended for external input but serve as a way to avoid repetition and create cleaner, more readable code. They are analogous to local variables within a function body in programming.
They are particularly useful for:
Creating common tags: Ensuring all resources share a standard set of metadata.
Constructing resource names: Combining input variables with random suffixes or project names for globally unique identifiers.
Terraform
locals {
common_tags = {
Environment = var.environment
Project = "Terraform-Demo"
}
# Combining input variable and random suffix for a unique name
full_bucket_name = "${var.environment}-${var.bucket_name}-${random_string.suffix.result}"
}
These values are referenced using the local. prefix, such as local.common_tags.
3. Output Variables: Sharing the Results
Output variables, defined in output.tf, serves one critical purpose: to display important information about the infrastructure after it has been created. They are the return values of the configuration.
Outputs are essential for integrating multiple Terraform configurations (e.g., using the output of a network module as the input for a security module) or simply for providing human-readable feedback to the user.
Viewing the Infrastructure's Attributes
An output variable defines a name, a description, and the value it should expose, which is typically an attribute of a provisioned resource.
Terraform
output "bucket_name" {
description = "Name of the S3 bucket created"
value = aws_s3_bucket.demo.bucket # Exposes the final, unique bucket name
}
output "tags" {
description = "Tags applied to the S3 bucket (from local variable)"
value = local.common_tags
}
After successfully running terraform apply, outputs are visible in the terminal and can be retrieved programmatically using the terraform output command, which also supports a JSON format for scripting.
Revisiting;
Terraform's variable system is a powerful mechanism for building flexible and maintainable infrastructure:
Input Variables: Parameterise the configuration for different environments.
Local Variables: Compute and reuse internal values like common tags and unique names.
Output Variables: Share the results of the deployment for human review or other automated systems.
By mastering these three variable types and understanding their precedence, engineers can create truly reusable and robust Infrastructure as Code.
Being busy with the schedule, will update the blog ASAP. Keep an eye.
Arigato!