Defining Variables
variable "instance_type" { description = "Type of instance to launch" type = string default = "t2.micro" }
Using Variables
resource "aws_instance" "example" { ami = "ami-0c55b159cb41deb1b" instance_type = var.instance_type }
Variables allow you to parameterize your configuration, making it reusable and configurable across different environments.
Best Practices
-
✓
Use
default
values for optional parameters -
✓
Organize related variables into
*.tfvars
files -
✓
Use
count
andfor_each
for dynamic resources
Example tfvars file
# variables.tf variable "region" { description = "AWS region" type = string default = "us-east-1" } variable "vpc_cidr" { description = "VPC CIDR block" type = string default = "10.0.0.0/16"