Automate Building AWS EC2 Instances with Terraform

Terraform is an infrastructure as code (IaC) tool that allows you to build, change, and version infrastructure safely and efficiently. This includes low-level components such as compute instances, storage, and networking, as well as high-level components such as DNS entries, SaaS features, etc. Terraform can manage both existing service providers and custom in-house solutions.

Terraform allows you to create infrastructure in configuration files(tf files) that describe the topology of cloud resources. These resources include virtual machines, storage accounts, and networking interfaces.

Step1-Login to AWS management console and create security credentials

Click My Security Credentials
Select Create New Access Key
Choose Download Access Key and save it locally. Best practice Click Show Access key and noted access key ID and secret access key.

Step2-Install AWS CLI and Terraform first on your Windows/Linux using the following links


Download Terraform

Install Terraform

Checking Version of terraform “terraform version

Step3-Create a local directory in your machine and go inside this folder

Ex:- mkdir demoec2 && cd demoec2

Step4-Open PowerShell or Terminal and configure AWS account

Create file and store it inside the previously created folder

provider “aws” {
access_key = “##”
secret_key = “##”
region = “us-east-2”

Run “terraform init” command. After that, You can successfully be connected

Step5-Create file and added the following code here

resource “aws_instance” “myFirstInstance” {
ami = “ami-00399ec92321828f5
key_name = “ubuntuos
instance_type = “t2.micro”
security_groups= [ “security_jenkins_port”]
tags= {
Name = “jenkins_instance”
#Create security group with firewall rules
resource “aws_security_group” “security_jenkins_port” {
name = “security_jenkins_port”
description = “security group for jenkins”

ingress {
from_port = 8080
to_port = 8080
protocol = “tcp”
cidr_blocks = [“”]

ingress {
from_port = 22
to_port = 22
protocol = “tcp”
cidr_blocks = [“”]

# outbound from jenkis server
egress {
from_port = 0
to_port = 65535
protocol = “tcp”
cidr_blocks = [“”]

tags= {
Name = “security_jenkins_port”

# Create Elastic IP address
resource “aws_eip” “myFirstInstance” {
vpc = true
instance =
tags= {
Name = “jenkins_elstic_ip”

Step6-Run “terraform plan” command will show how many resources will be added

Step7-Run “terraform apply” command and enter “yes”. After that, you can see your ec2 instance and security group created

Step8-Run “terraform state list” for a view list of the resources created by Terraform

Step9-Run “terraform destroy” to remove previously created all services.

Thank You!!!


DevOps Intern | AWS | Undergraduate | Tech enthusiast