If you're new to Terraform and infrastructure as code (IaC), I recommend going through my previous post here, where I covered the fundamentals of Terraform. Understanding the basics will help you follow along smoothly as we dive into provisioning an AWS EC2 instance using Terraform. This guide is beginner-friendly, so even if you're just getting started, you'll be able to follow along and apply Terraform in a real-world use case with ease.
Introduction
I am Prajwal KP, a second-year student from Bangalore, passionate about full-stack web development and DevOps.
Here are my LinkedIn, GitHub
What Is Terraform?
Terraform, developed by HashiCorp, is a powerful open-source Infrastructure as Code (IaC) tool that enables declarative provisioning, management, and automation of infrastructure across multiple cloud providers and on-premises environments.
It allows users to define infrastructure using a high-level configuration language (HCL) and facilitates infrastructure lifecycle management through execution plans, resource graphs, and state management. Terraform’s provider ecosystem extends beyond traditional cloud platforms like AWS, Azure, and Google Cloud to include Kubernetes, databases, networking, and even SaaS applications, making it a highly versatile tool for modern DevOps and cloud-native architectures.
Spinning Up an EC2 Instance with Terraform Magic
Let's Start Writing Some Terraform Code.
In this post, I'll walk you through the step-by-step process of launching an AWS EC2 instance using Terraform, making infrastructure deployment seamless and automated.
Open your VS Code or any other code editor to start coding.
Step 1: Find instanceId to launch an instance
- Create a new file named
instId.tf
and copy the below code into it.
# data "resource type" "resource name"
data "aws_ami" "amiId" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"]
}
# output block
output "instance_id" {
description = "AMI ID of the instance"
value = data.aws_ami.amiId.id
}
Breakdown:
- This file is basically used to find an instance Id to launch an instance.
To launch an EC2 instance, we'll create additional .tf
files to define the required configurations. Additionally, since an instance requires a key pair and a security group, I'll organize these resources into separate folders for better structure and maintainability.
Step 2: Create provider.tf
- Our provider for this setup will be AWS, where we can specify important details such as the desired region, the key pair to use, and additional provider configurations to customize our deployment.
- Paste the below code.
provider "aws" {
region = "us-east-1"
}
- For more details click here
Step 3: Set Up a Key Pair and Security Group
Create a new file under the same directory as
KeyPair.tf
and one more file asSecGrp.tf
Open file
KeyPair.tf
and paste the following
resource "aws_key_pair" "my-key" {
key_name = "my-key"
public_key = ""
}
-
To generate the keys
- Open the terminal in the same directory and type
ssh-keygen
. - Enter the name as
mykey
and let other fields be default. - Then type
ls
and check whether the private and public keys are present. - Then type
cat mykey.pub
and copy the output and paste it as the value for public_key insideKeyPair.tf
and save it.
- Open the terminal in the same directory and type
Now let's create the security group
Open the SecGrp.tf
and paste the code.
resource "aws_security_group" "my-sg" {
name = "my-sg"
description = "my-sg"
tags = {
Name = "my-sg"
}
}
resource "aws_vpc_security_group_ingress_rule" "sshfromyIp" {
security_group_id = aws_security_group.my-sg.id
cidr_ipv4 = "Your_Ip/32"
from_port = 22
ip_protocol = "tcp"
to_port = 22
}
resource "aws_vpc_security_group_ingress_rule" "allow_http" {
security_group_id = aws_security_group.my-sg.id
cidr_ipv4 = "0.0.0.0/0"
from_port = 80
ip_protocol = "tcp"
to_port = 80
}
resource "aws_vpc_security_group_egress_rule" "allow_all_outbound_ipv4" {
security_group_id = aws_security_group.my-sg.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1" # -1 for all incoming protocols
}
resource "aws_vpc_security_group_egress_rule" "allow_all_outbound_ipv6" {
security_group_id = aws_security_group.my-sg.id
cidr_ipv6 = "::/0"
ip_protocol = "-1" # -1 for all incoming protocols
}
Breaking Down the Security Group Configuration
Creating the Security Group – Defines a security group named my-sg with basic tagging for identification.
Allowing SSH Access – Enables SSH (port 22) access only from your IP for security. Replace
Your_Ip
with your actual public IP find it here.Allowing HTTP Access – Opens port 80 to allow HTTP traffic from anywhere (0.0.0.0/0).
Allowing All Outbound Traffic – Ensures the instance can access the internet by allowing unrestricted outbound traffic for both IPv4 and IPv6.
Step 4:
Let's write the code to launch instance or we can say that to maintain an instance
- Create a new file as
instance.tf
and copy the below code.
resource "aws_instance" "web" {
ami = data.aws_ami.amiId.id
instance_type = "t2.micro"
key_name = aws_key_pair.my-key.key_name
vpc_security_group_ids = [aws_security_group.my-sg.id]
availability_zone = "us-east-1a"
tags = {
Name = "my-web"
Project = "First"
}
}
resource "aws_ec2_instance_state" "web-state" {
instance_id = aws_instance.web.id
state = "running"
}
Breaking Down the EC2 Instance Configuration
Defining the EC2 Instance – Creates an EC2 instance using an AMI (
amiId
), sets the instance type tot2.micro
, and assigns it a key pair for SSH access.Security Group Association – Attaches the previously created security group (
my-sg
) to control inbound and outbound traffic.Availability Zone Selection – Specifies the instance should launch in
us-east-1a
, ensuring control over its placement within the AWS region.Tagging for Organization – Adds metadata with the name
"my-web"
and associates it with the project"First"
.Ensuring the Instance is Running – Uses a separate resource to maintain the EC2 instance in a
"running"
state, preventing unintended shutdowns.
Cool! Now that we've defined our infrastructure, let's put it into action by executing our Terraform commands. We'll initialize the configuration, review the changes, and apply them to deploy our EC2 instance. 🚀
-
terraform init
( to download all the required libraries from the registry) -
terraform fmt
( to correct the format ) -
terraform validate
( to check the syntax ) -
terraform plan
( it is important to read all the changes ) terraform apply
Voila! 🎉 If everything executed without errors, your EC2 instance should now be up and running. To verify, head over to the AWS Management Console, ensure you're in the correct region, and navigate to the EC2 Dashboard. Here, you can check the instance state to confirm it's running. Also, review the Security Group settings to ensure the correct inbound and outbound rules are applied. Happy automating! 🚀
After checking it and using it to delete the instance we can type terraform destroy
to completely delete the instance.
Conclusion
And that’s a wrap! 🎉 You’ve successfully deployed and managed an EC2 instance using Terraform, making infrastructure automation easier and more efficient. But this is just the beginning! There’s so much more to explore in cloud computing, DevOps, and automation.
Stay tuned for my upcoming posts, where I'll dive into more exciting topics and hands-on guides to help you level up your skills. 🚀 See you in the next one! 😊
Top comments (0)