Understanding Interpolation in Terraform with EC2 Example
By Raees Qazi | DevOps Engineer | Learner | Mentor | Creator
Today, let’s understand what interpolation is and how we can create an EC2 instance using Terraform while extracting values using interpolation.
This guide is going to be simple and practical — no jargon, just real working code.

💡 Prerequisites
Before we begin, I’m assuming:
- You have already created the
provider.tffile. - Terraform is initialized (
terraform initalready run). - AWS CLI is configured with an IAM user.
If all of the above is done, let’s move to the next step.
🛠 Create EC2 Instance with Terraform
Now, we’ll create a file named ec2.tf and write our resource configuration.
# ec2.tf
resource "aws_instance" "my_instance" {
count = 2 # How many machines you want to create
ami = "ami-xxxxxxxxxxxxxxxxx" # Replace with a valid AMI ID for your region
instance_type = "t2.micro" # Type of instance
key_name = "private-key" # Use an existing key pair name
tags = {
Name = "My-Auto-server" # Name tag for the instance
}
}
output "my_ec2_ip" {
value = aws_instance.my_instance[0].public_ip
}🧠 Explanation
- Resource Block:
We define a resource of typeaws_instancewith the namemy_instance.
Thecount = 2means Terraform will create two EC2 machines. - Tags:
We’re giving the instance a tag"Name" = "My-Auto-server"so it’s easy to identify in the AWS console. - AMI:
Every EC2 machine is created from an Amazon Machine Image (AMI). You must provide a valid AMI ID according to your region. - Instance Type:
t2.microis a free-tier eligible instance type, perfect for testing and learning. - Key Name:
Here you define the name of your existing EC2 key pair to enable SSH access.
🔁 Interpolation in Action
Look at this block:
output "my_ec2_ip" {
value = aws_instance.my_instance[0].public_ip
}Here we are using interpolation to access a value from the Terraform object.
aws_instance.my_instance→ refers to our EC2 resource.[0]→ since we created 2 instances, we’re getting the first one (index starts from 0)..public_ip→ this fetches the public IP of that instance.
This is called interpolation — it allows you to reference values dynamically from other resources in Terraform.
🚀 Deploy the Infrastructure
Once your ec2.tf is ready, simply run:
terraform plan
terraform applyWait a few moments…
✨ Jaddo is in front of you! ✨
Your EC2 machines are created and the public IP of the first instance is displayed on your screen — thanks to the output block.
📣 Final Words
That’s it — simple and clear!
We understood:
- What interpolation is in Terraform.
- How to create multiple EC2 instances.
- How to extract values like public IP using interpolation.
If you found this helpful, please share and follow for more DevOps content like this.
By Raees Qazi
DevOps Engineer | Learner | Mentor | Creator
Comments
Post a Comment