Why Use Variables in Terraform?
Imagine writing the same configuration multiple times or manually updating details like instance types or regions. Sounds tedious, right? That’s where Terraform variables come in! They make your Terraform code reusable, manageable, and dynamic.
Types of Variables in Terraform
Terraform supports three primary types of variables:
Input Variables: Pass values into your Terraform modules.
Output Variables: Extract values from your Terraform modules.
Input Variables
What Are Input Variables?
Input variables allow you to define dynamic values for your infrastructure. For example, instead of hardcoding the region, you can create a variable to set it dynamically.
How to Declare Input Variables
Here's a simple example of declaring and using a variable:
resource "aws_instance" "one" {
tags = var.iname
ami = var.ami_id
instance_type = var.itype
key_name = "your-key-pair"
availability_zone = var.az ? "us-east-1a" : "us-east-1b"
vpc_security_group_ids = var.security_group_ids
root_block_device {
volume_size = var.volume
}
count = var.icount
}
Variable Types
You can specify types like string
, number
, list
, or map
. Here's an example of each:
String:
variable "itype" { type = string default = "t2.micro" } variable "ami_id" { type = string default = "ami-0c55b159cbfafe1f0" }
Number:
variable "volume" { type = number default = 10 } variable "icount" { type = number default = 1 }
List:
variable "security_group_ids" { description = "List of existing security group IDs to attach to the EC2 instance" type = list(string) default = ["sg-0123456789abcdef0", "sg-0fedcba9876543210"] }
Map:
variable "iname" { type = map(string) default = { Name = "MyInstance" Project = "DevOps" } }
Boolean:
variable "az" { type = bool default = true }
Here i selected “true” so my instance will launch on “us-east-1a” availability zone, if you choose “false” it will launch on “us-east-1b”.
Output Variables
Why Use Output Variables?
Output variables let you retrieve information like IP addresses, IDs, or endpoints after running Terraform.
How to Use Output Variables
Example:
output "instance_id" { description = "The ID of the EC2 instance" value = aws_instance.one.id }
After applying, the output will display the instance ID in your terminal.
Conclusion
Terraform variables are the foundation for creating reusable and scalable infrastructure as code. By mastering variables, you’ll not only write cleaner code but also prepare for real-world scenarios and Terraform certification.
If you love stories that inspire learning, growth, and productivity, consider subscribing for more! If this article added value to your journey, your support would mean the world to me — only if it’s within your means. Let’s stay connected on LinkedIn too. Thank you for reading! 💕