Create an EC2 Instance With an Elastic IP Address: Terraform Assignment 2

Visal Tyagi
DevOps-Guides
Published in
3 min readApr 7, 2024

Tasks to Be Performed:

1. Destroy the previous deployment

2. Create a new EC2 instance with an Elastic IP

Instance with Elastic IP Address
Instance with Elastic IP Address

Assignment 2 Github Repository Link:

Problem (1) Solution: Destroy the previous deployment

Here, we have to destroy the resources created in Terraform Assignment 1.

Step 1: First, we will destroy the resources using the command: terraform destroy.

terraform destroy
terraform destroy

Step 2: Type “yes” to destroy.

Yes
Yes

Step 3: Instance “assignment-1” has been successfully terminated. It will take approximately 30 seconds to destroy.

Resources Destroyed
Resources Destroyed
Assignment 1 Instance Terminated
Assignment 1 Instance Terminated

Problem (2) Solution: Create a new EC2 instance with an Elastic IP

Step 1: Create a main.tf file using the command: sudo nano main.tf

main.tf file
main.tf file

Step 2: Paste this script to create an EC2 Instance with the help of “EIP Address”.

provider "aws" {
region="us-east-2"
access_key="AKIAQRH4ND34WNGRNWOP"
secret_key="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"
}

resource "aws_instance" "assignment2" {
ami = "ami-0b4750268a88e78e0"
instance_type = "t2.micro"
tags = {
Name = "assignment2"
}
}

resource "aws_eip" "eip" {
domain = "vpc"
}

resource "aws_eip_association" "eip_assoc" {
instance_id = aws_instance.assignment2.id
allocation_id = aws_eip.eip.id
}
EC2 Terraform Script
EC2 Terraform Script

Do “CTRL+X” to exit & Press “Yes” to save the content. Also, press “enter” from the keyboard for complete exit.

Step 3: Run this command to initialize the terraform: terraform init.

terraform init
terraform init

Step 4: Run the “terraform plan” command to execute the plan.

terraform plan
terraform plan
Plan Created
Plan Created

Step 5: Run the “terraform apply” command to create the infrastructure.

terraform apply
terraform apply

Step 6: Type “yes” to create the infrastructure.

Yes
Yes

Step 7: The instance with “Elastic IP Address” has been successfully created within 30 seconds.

Instance with Elastic IP Address
Instance with Elastic IP Address

Step 8: Go to the “Instance” section & your instance (assignment2) will be successfully created with Elastic IP Address (18.116.188.17).

Instance with Elastic IP Address
Assignment 2 Instance Created

More Terraform Assignments:

Creating an Architecture using Terraform on AWS — Case Study Solution

Rename EC2 Instances After Creation — Assignment 3

Create a VPC & Deploy an EC2 Instance Inside It — Assignment 4

Install Apache 2 & Print the IP Address of the Instance in a File on Local - Assignment 5

--

--