On Day 05 of my Terraform learning journey, I focused on one of the most important building blocks of reusable and flexible Infrastructure as Code: Terraform variables.
Variables help remove hardcoded values, improve readability, and make Terraform configurations easier to manage across environments.
**
Types of Variables in Terraform
**
Terraform primarily works with three kinds of variables:
- Input variables
- Local variables
- Output variables
Each serves a specific purpose in Terraform configurations.
**
Input Variables
**
Input variables allow users to provide values dynamically instead of hardcoding them.
Example:
variable "bucket_name" {
type = string
default = "my-demo-bucket"
}
Used in a resource:
resource "aws_s3_bucket" "example" {
bucket = var.bucket_name
}
Input variables make configurations reusable and environment-independent.
**
Local Variables
**
Local variables are used to calculate or store values internally within a configuration.
They reduce repetition and improve readability.
Example:
locals {
environment = "dev"
bucket_tag = "${local.environment}-s3-bucket"
}
Usage:
tags = {
Name = local.bucket_tag
}
Locals cannot be overridden from the command line.
**
Output Variables
**
Output variables display values after Terraform applies the configuration.
They are useful for debugging and for passing information to other modules.
Example:
output "bucket_name" {
value = aws_s3_bucket.example.bucket
}
After terraform apply, the bucket name is printed in the terminal.
**
Terraform Variable Data Types
**
Terraform supports multiple data types, including:
- string – text values
- number – integers and decimals
- bool – true or false
Example:
variable "region" {
type = string
default = "ap-south-1"
}
variable "instance_count" {
type = number
default = 1
}
variable "enable_versioning" {
type = bool
default = true
}
**
Default Values and Null
**
Default Values
A default value allows Terraform to use a variable automatically if no value is provided.
variable "environment" {
type = string
default = "dev"
}
**
Null Values
**
The null value means no value is set.
Terraform ignores arguments set to null, which helps in conditional configurations.
variable "bucket_acl" {
type = string
default = null
}
If bucket_acl is null, Terraform simply does not apply it.
Key Takeaways from Day 05
- Variables make Terraform flexible and reusable
- Input variables accept user-provided values
- Local variables simplify internal expressions
- Output variables expose useful information.
- Data types improve validation and safety
- Default and null help with optional configurations.
Conclusion
Understanding variables is critical to writing clean and scalable Terraform code. By using input, local, and output variables correctly, Terraform configurations become more readable, reusable, and easier to maintain across different environments.
Day 05 strengthened the foundation needed to move toward more advanced Terraform concepts.
Top comments (0)