Make Your Code Flexible with Variables
Lesson 4
Ready to make your Terraform code smarter and more reusable? Variables are like settings you can easily change without rewriting your entire code. Think of them like adjustable dials on a machine—instead of rebuilding the machine every time you want different settings, you just turn the dials!
Why use variables? Right now, your server settings are “hardcoded”—locked into your files. With variables, you can quickly change server sizes, regions, or names without touching your main code. It’s like having a control panel for your infrastructure!
Table of contents
- Make Your Code Flexible with Variables
- Understanding Terraform’s Variable System
- Setting Up Your Variable Files
- Creating Your Variables Menu (
variables.tf
) - Setting Your Values (
terraform.tfvars
) - Connecting Variables to Your Resources
- Test Your Variables
- The Power of Variables
- Best Practices for Variables
- Common Variable Patterns
- What You’ve Accomplished
- Interactive Practice
- Advanced Challenges
- Troubleshooting
- The Big Picture
- Next Steps
Understanding Terraform’s Variable System
Terraform uses a two-file system for variables—like having a form and filling it out:
variables.tf
- The blank form (defines what settings you can change)terraform.tfvars
- The filled-out form (your actual settings)
This separation is powerful because you can:
- Share the blank form (
variables.tf
) with others - Keep your specific settings (
terraform.tfvars
) private - Easily switch between different environments (dev, staging, production)
Why Two Files?
Think of it like a restaurant:
variables.tf
is the menu (what’s available to order)terraform.tfvars
is your order (what you actually choose)
The menu stays the same, but everyone can order different things!
Setting Up Your Variable Files
Let’s add variables to your existing project. You’ll continue working in your my-first-ec2
directory.
Step 1: Create the Variable Files
# Make sure you're in your project directory
cd my-first-ec2
pwd # Should show your project path
# Create the two variable files
touch variables.tf terraform.tfvars
# Verify they exist
ls # Should show: aws.tf ec2.tf terraform.tfvars variables.tf
Important: These file names are special! Terraform automatically looks for files with these exact names, so don’t change them.
Creating Your Variables Menu (variables.tf
)
This file defines what settings can be changed. It’s like creating a configuration panel for your infrastructure.
Variable Structure
Each variable has this format:
variable "name_of_variable" {
type = variable_type
}
Step 2: Define Your Variables
Open variables.tf
in your code editor and add these four variables:
# AWS Region - where to create resources
variable "region" {
type = string
description = "AWS region for resources"
}
# Server operating system
variable "ami" {
type = string
description = "AMI ID for EC2 instance"
}
# Server size
variable "instance_type" {
type = string
description = "EC2 instance type"
}
# Security key for server access
variable "key_name" {
type = string
description = "Name of AWS key pair"
}
What each part means:
variable "region"
- Creates a variable called “region”type = string
- This variable accepts text valuesdescription
- A note explaining what this variable does
Why these four variables?
- Region: Where in the world your server runs
- AMI: What operating system your server uses
- Instance Type: How powerful your server is
- Key Name: Which key pair to use for secure access
Setting Your Values (terraform.tfvars
)
Now let’s fill out your “order form” with actual values.
Step 3: Add Your Settings
Open terraform.tfvars
in your code editor and add:
# AWS Region
region = "us-east-1"
# Amazon Linux 2 AMI
ami = "ami-0c02fb55956c7d316"
# Free tier instance type
instance_type = "t2.micro"
# Your key pair name (replace with YOUR actual key pair name!)
key_name = "yourname-us-east-1"
Remember: Replace yourname-us-east-1
with the exact key pair name you created earlier!
What’s happening:
region = "us-east-1"
assigns the value “us-east-1” to your region variable- No
type
needed here—Terraform knows from thevariables.tf
file - Values in quotes because they’re all strings (text)
Connecting Variables to Your Resources
Now you need to tell your existing Terraform files to use these variables instead of hardcoded values.
Step 4: Update Your EC2 Configuration
Open ec2.tf
and replace the hardcoded values with variable references:
# Create a virtual server in the cloud
resource "aws_instance" "my_first_server" {
ami = var.ami # Use the ami variable
instance_type = var.instance_type # Use the instance_type variable
key_name = var.key_name # Use the key_name variable
# Add labels to identify this server
tags = {
Name = "My-Variable-Server"
Environment = "Learning"
Owner = "Your Name"
}
}
What’s new:
var.ami
instead of"ami-0c02fb55956c7d316"
var.instance_type
instead of"t2.micro"
var.key_name
instead of"yourname-us-east-1"
The pattern: To use any variable, write var.
followed by the variable name.
Step 5: Update Your AWS Provider
Open aws.tf
and update it to use the region variable:
# Tell Terraform we want to use AWS
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
required_version = ">= 1.0"
}
# Configure AWS settings
provider "aws" {
region = var.region # Use the region variable
profile = "learn-aws" # Use the profile we created earlier
}
What changed: region = var.region
instead of region = "us-east-1"
Test Your Variables
Time to see your variables in action!
Step 6: Deploy with Variables
# Initialize (if needed)
terraform init
# Preview changes
terraform plan
# Deploy your server
terraform apply
Type yes
when prompted.
What to expect: Your server should deploy exactly like before, but now it’s using variables!
Step 7: Verify in AWS Console
- Go to AWS Console → EC2 → Instances
- Find your server named “My-Variable-Server”
- Check that:
- Instance type is
t2.micro
- AMI matches your variable
- Region is
us-east-1
- Instance type is
Step 8: Clean Up
terraform destroy
Type yes
to delete your server.
The Power of Variables
Now for the magic! Let’s see how easy it is to change your infrastructure.
Example: Deploy to a Different Region
Want to create the same server in a different region? Just change one line!
- Open
terraform.tfvars
- Change the region:
region = "us-west-2" # Changed from us-east-1
- Deploy:
terraform apply
Result: Same server, different location—without changing any other code!
Example: Use a Larger Server
Need more power? Change the instance type:
instance_type = "t3.small" # Upgraded from t2.micro
Result: More powerful server with one line change!
Best Practices for Variables
1. Use Descriptive Names
# Good
variable "web_server_instance_type" { ... }
# Avoid
variable "type" { ... }
2. Add Helpful Descriptions
variable "instance_type" {
type = string
description = "EC2 instance type (t2.micro for free tier)"
}
3. Group Related Variables
# Server configuration
variable "instance_type" { ... }
variable "ami" { ... }
# Network configuration
variable "vpc_id" { ... }
variable "subnet_id" { ... }
Common Variable Patterns
Setting Default Values
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro" # Used if no value provided
}
Validation Rules
variable "instance_type" {
type = string
description = "EC2 instance type"
validation {
condition = contains(["t2.micro", "t2.small", "t3.micro"], var.instance_type)
error_message = "Instance type must be t2.micro, t2.small, or t3.micro."
}
}
What You’ve Accomplished
✅ Created a flexible configuration system - Variables make your code reusable
✅ Separated configuration from code - Clean, maintainable infrastructure
✅ Learned the two-file pattern - Industry standard for Terraform projects
✅ Made infrastructure changes easy - One-line updates for different environments
✅ Applied professional practices - Descriptions, validation, and organization
You’ve just learned one of the most important Terraform concepts! Variables are what make Infrastructure as Code truly powerful and scalable.
Interactive Practice
Test your understanding with these interactive exercises! Get instant feedback on your answers.
Practice 1: Create a Variable Declaration
Create a variable called environment
that accepts string values:
Practice 2: Set Variable Values
Create a variable assignment where environment = "production"
:
Practice 3: Use Variables in Resources
Replace this hardcoded value with a variable reference: instance_type = "t2.micro"
Practice 4: Complete Variable Block
Create a complete variable declaration for server_name
with type string
and description "Name for the EC2 instance"
:
Advanced Challenges
Challenge 1: Multiple Variable Types
Create variables for:
port_number
(number type)enable_monitoring
(bool type)tags
(object type with name and environment keys)
Challenge 2: Environment-Specific Configs
Create separate .tfvars
files:
dev.tfvars
- Small instances, monitoring disabledprod.tfvars
- Larger instances, monitoring enabled
Challenge 3: Add Validation Rules
Add validation to ensure:
- Instance types are only t2.micro, t2.small, or t3.micro
- Regions are only us-east-1 or us-west-2
- Environment is only “dev”, “staging”, or “prod”
Troubleshooting
“No value for variable” error:
- Check that your variable is defined in
variables.tf
- Verify the name matches exactly in
terraform.tfvars
“Invalid variable type” error:
- Ensure string values are in quotes:
region = "us-east-1"
- Numbers don’t need quotes:
port = 80
Variables not taking effect:
- Run
terraform plan
to see what values Terraform is using - Check for typos in variable names (
var.regoin
vsvar.region
)
The Big Picture
What you’ve learned applies everywhere:
- Configuration Management: Separate settings from logic
- Environment Management: Same code, different settings per environment
- Team Collaboration: Share templates while keeping personal settings private
- Change Management: Update infrastructure safely and predictably
Next Steps
Ready to learn about server images and customization? Head to AMIs where you’ll discover how to create custom server templates!
Pro Tip: Variables are the foundation of professional Terraform. Every real-world project uses them extensively. You’re now thinking like a DevOps engineer!