How To Create An AWS EC2 Instance and Attach EBS to EC2 With Terraform?
Last Updated :
04 Mar, 2024
Terraform is an IaaC tool, used to provision infrastructure on cloud platforms. In this guide, I will first discuss what is Terraform. Then I will discuss about AWS EC2 service. After this, I will walk you through the different steps to create an AWS EC2 Instance and attach an EBS volume to EC2 Instance using Terraform and then connect the EC2 Instance's public IP to access the website.
What is Terraform?
Terraform is an Infrastructure As Code tool that uses declarative configurational language that is Hashicorp Configurational Language (HCL) to define and provision infrastructure on a different cloud platform. Terraform helps organizations to have multiple cloud platform strategies which helps organizations to avoid depending on only one type of cloud platform. Terraform can provision on multiple cloud platforms such as AWS, Azure, GCP, and many more. If Terraform is not developed then organizations have to use AWS Console, Azure Console, or GCP Console to create the entire infrastructure. This could lead to many manual errors while creating infrastructure. Finding these errors and resolving them would take too much time. But if the same task is done using Terraform then it would eliminate manual error occurrence. In summary, Terraform stands out as an essential solution offering simplicity, cross-platform compatibility, and automation capabilities for maintaining control, reliability, and scalability in any infrastructure setup.
What Is AWS EC2?
EC2 also called Elastic Cloud Compute (EC2), which is an AWS web service that allows user to rent virtual server on a AWS cloud platform . These virtual servers are called EC2 Instances . There are different types of EC2 instances which users can select on their requirement. For example if an user is doing any high compute work , they can choose t2.large or any higher EC2 instance type or if they are doing any low compute work they can choose t2.micro or t2.medium . EC2 service also provides variety of operating system images such as Ubuntu, CentOs , Amazon Linux, Windows and many more . EC2 instances can also be scaled up or down on the basis of traffic it receives by using a load balancer . In summary we can say EC2 provides flexible, scalable and cost effective solutions to organizations to run their application on AWS cloud platform .
Steps To Create AWS EC2 Instance and Attach EBS To EC2 Using Terraform
Step 1 : Mention the provider and region in which you want to create the AWS resources in provider.tf file.
provider "aws" {
region = "us-east-1"
}

Step 2 : Then create a variables file where you have to mention all the variables that is EC2 instance going to use such as ami-id , instance type , server port , ssh port in variables.tf file.
variable "instance_type" {
description = "This describes the instance type"
type = string
default = "t2.micro"
}
variable "ami_id" {
description = "This describes the ami image"
type = string
default = "ami-01c647eace872fc02"
}
variable "server_port" {
description = "Server use this port for http requests"
type = number
default = 80
}
variable "ssh_port" {
description = "Describes the ssh port"
type = number
default = 22
}
variable "availability_zone" {
default = "us-east-1a"
}

Step 3 : Then create a file where you can define the security group configurations in security_group.tf file.
resource "aws_security_group" "instance" {
name = "terraform-SG"
ingress {
from_port = var.server_port
to_port = var.server_port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = var.ssh_port
to_port = var.ssh_port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

Step 4: Then create aws instance resource . Here mentions the variables and also in the user data write a script that will install httpd service and index.html on the EC2 instance in main.tf terraform file.
resource "aws_instance" "server" {
ami = var.ami_id
instance_type = var.instance_type
vpc_security_group_ids = [ aws_security_group.instance.id ]
availability_zone = var.availability_zone
tags = {
Name = "EC2-Server"
}
user_data = <<-EOF
#!/bin/bash
sudo yum update -y
sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
echo "Terraform is easy!!!" > /var/www/html/index.html
EOF
user_data_replace_on_change = true
}

Step 5: Create an EBS volume . Then attach it to the EC2 instance in ebs_volume.tf file.
resource "aws_volume_attachment" "ebs_att" {
device_name = "/dev/sdh"
volume_id = aws_ebs_volume.ebs_vol.id
instance_id = aws_instance.server.id
}
resource "aws_ebs_volume" "ebs_vol" {
availability_zone = var.availability_zone
size = 1
}

Step 6 : Create a output file which will give the public IP of the EC2 instance as output in output.tf terraform file.
output "public_ip" {
description = "The public IP address of the web server"
value = aws_instance.server.public_ip
}

Step 7 : Then run all the terraform files using the below commands one by one .
terraform init
- The following command shows the definition of the Terrform files that you provided.
terraform plan
- The following command helps in executing the configured/defined tasks.
terraform apply

Step 8 : Check on AWS console whether the EBS volume is attached to the EC2 instance or not .
Step 9 : Then connect the public IP to see the website.

Conclusion
First we have learned what is Terraform and then we have learned what is AWS EC2 service . After this we have implemented the steps to create an EC2 instance and attach a EBS volume to the EC2 using Terraform . Here all the resources are then created and we got the EC2 instance public IP as output in the command line and finally accessed the website through browser .
Terraform And AWS EC2 - FAQ's
How To Remove All The Resources Created Using Terraform ?
Use terraform destroy command to remove all the resources created using Terraform.
What Is Benefit Of Using Terraform To Launch EC2 instance ?
Terraform helps us to manage the infrastructure by using code . This provides version control and automation benefits .
What Is AMI ?
AMI stands for Amazon Machine Image . It includes operating system , application server and applications that is required to run an EC2 instance.
What Is Difference Between 'terraform plan' And 'terraform apply' Command ?
Terraform plan shows the execution plan without making any changes to infrastructure while terraform apply makes the changes to infrastructure as per the execution plan.
How To Define Security Groups For EC2 Instance Using Terraform ?
In terraform you can use aws_security_group resource to create a security group for EC2 instance .
Similar Reads
How To Create An AWS EC2 Instance and Attach EBS to EC2 With Terraform?
Terraform is an IaaC tool, used to provision infrastructure on cloud platforms. In this guide, I will first discuss what is Terraform. Then I will discuss about AWS EC2 service. After this, I will walk you through the different steps to create an AWS EC2 Instance and attach an EBS volume to EC2 Inst
6 min read
How to Create Alarm to Terminate an EC2 Instance using the Amazon CloudWatch?
Amazon CloudWatch Alarms are a feature of AWS(Amazon Web Services) that allows you to monitor various metrics and take automated actions based on the conditions, you define. CloudWatch Alarms help you keep track of the health and performance of your AWS resources and Applications. Different States O
6 min read
How To Create EBS Volume In AWS Using Terraform
EBS Stands for Elastic Block Storage is a block-level storage service provided by Amazon web services to use with Amazon's Elastic Compute Cloud (EC2) instances.It provides persistent, high-performance storage volumes that can be attached to Amazon EC2 instances. it acts as an attached external hard
6 min read
How To Create Custom AMI In AWS Using Terraform
In the present cloud-centric software development landscape, the capacity to efficiently manage infrastructure resources is vital. Making custom Amazon Machine Images (AMIs) is a pivotal part of this process, permitting organizations to normalize their application environments and streamline sending
7 min read
How to Create AWS EC2 using Terraform?
AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, cl
13 min read
How To Create Elastic IP In AWS Using Terraform ?
Using Terraform, creating an Elastic IP (EIP) on AWS entails specifying the resources required in a Terraform configuration file in order to create the EIP. A static IPv4 address intended for dynamic cloud computing is called an elastic IP. It is helpful in situations when you require a public IP ad
4 min read
How To Create Spot Instance In Aws-Ec2 In Aws Latest Wizards?
Spot instances are available at up to 90% discount because when instances are not used then the instance available in spot instance at a cheaper rate so that people can utilize. it. When the demand increases then amazon sent a notification your spot instance will disappear after two minutes. We can
6 min read
How To Create Redhat EC2 Instance in AWS
provisioning the Red Hat Enterprise Linux (RHEL) instances on Amazon Web Services (AWS) offers a powerful and versatile solution for hosting and running applications, overseeing the jobs, and utilizing the abilities of both platforms. Red Hat Enterprise Linux is a main Linux distribution eminent for
5 min read
How To Create SNS Topic In AWS In Using Terraform
Amazon Simple Notification Service (SNS) is a fully managed messaging service given by Amazon Web Services (AWS), offering a versatile and reliable solution for sending notices and messages to different endpoints or subscribers. SNS points act as correspondence channels to which messages can be dist
6 min read
How to Attach and Mount an Extra Volume to an Linux Instance in AWS?
EBS is a block type durable and persistent storage that can be attached to EC2-instances for additional storage. Unlike EC-2 instance storage volumes which are suitable for holding temporary data EBS volumes are highly suitable for essential and long term data. EBS volumes are specific to availabili
11 min read