Using Variables in Terraform
Last updated on 2025-11-30 | Edit this page
Overview
Questions
- How can we make Terraform configurations flexible instead of hard-coded?
- How do we define and use variables in Terraform?
Objectives
- Define input variables in a
variables.tffile. - Use variables inside Terraform resources.
- Override variables from the command line or with
terraform.tfvars.
Why Variables Matter
In the previous episodes, we hard-coded details like the AMI ID, instance type, and allowed SSH CIDR. This is fine for experimentation, but not practical when:
- You deploy to different environments.
- You need to give learners flexibility.
- You plan to reuse your Terraform modules.
Terraform variables make your configuration more reusable and easier to maintain.
Creating a variables.tf File
Create a new file:
Add the following:
variable "aws_region" {
description = "AWS region for all resources"
type = string
default = "us-west-2"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
variable "instance_name" {
description = "Name tag for the EC2 instance"
type = string
default = "terraform-demo"
}
By convention, variables are collected in their own file. Terraform loads all .tf files automatically, so file names don’t affect execution order.
Using Variables in main.tf
Update your EC2 resource to reference variables:
provider "aws" {
region = var.aws_region
}
resource "aws_instance" "demo" {
ami = "ami-0adebe3adcec1fa34"
instance_type = var.instance_type
tags = {
Name = var.instance_name
}
}
Overriding Variables
- Override at apply time terraform apply -var=“instance_type=t3.small”
- Use a .tfvars file
Create a terraform.tfvars file:
Now apply normally:
Terraform automatically loads terraform.tfvars.
Challenge
Challenge: Create Your Own Variable
Add a new variable called ssh_cidr that lets the learner specify which IP is allowed to SSH into the instance.
Then update your Security Group to use it.
- Variables make Terraform code reusable and easier to maintain.
- Variables are defined once and used many times across configurations.
- You can override variables with -var or terraform.tfvars.