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

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

Tasks to Be Performed:

1. Destroy the previous deployments

2. Create a VPC with the required components using Terraform

3. Deploy an EC2 instance inside the VPC

Instance Deployed in VPC
Instance Deployed in VPC

Assignment 4 Github Repository Link:

Problem (1) Solution: Destroy the previous deployments

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

Step 1: Go to “Master” & run the “terraform destroy” command to destroy the previous deployments.

terraform destroy
terraform destroy

Step 2: Type “yes” to destroy the resources.

Yes
Yes

Step 3: Both “hello-vriginia” & “hello-ohio” instances will be terminated successfully.

hello-virginia instance
hello-virginia instance
hello-ohio instance
hello-ohio instance

Problem (2) & (3) Integrated Solution:

2. Create a VPC with the required components using Terraform

3. Deploy an EC2 instance inside the VPC

Step 1: Go to the “Master” instance & create a “main.tf” file for VPC creation.

Use this command: sudo nano main.tf

sudo nano main.tf

Step 2: Paste this script to create the Instance with VPC:

provider "aws" {
region = "us-east-2"
access_key = "AKIAQRH4ND34WNGRNWOP"
secret_key = "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"
}
resource "aws_instance" "assignment-4" {
ami = "ami-0b4750268a88e78e0"
instance_type = "t2.micro"
subnet_id = aws_subnet.assignment-4-subnet.id
key_name = "Terraform"
tags = {
Name = "assignment-4"
}
}

resource "aws_vpc" "assignment-4-vpc" {
cidr_block="10.10.0.0/16"
tags= {
Name = "assignment-4-vpc"
}
}

resource "aws_subnet" "assignment-4-subnet" {
vpc_id=aws_vpc.assignment-4-vpc.id
cidr_block="10.10.0.0/18"
availability_zone="us-east-2a"
tags = {
Name = "assignment-4-subnet"
}
Terraform Script File (main.tf)
Terraform Script File (main.tf)

Do “CTRL+X” to exit & press “Yes” to save the file. Press “enter” to exit from the file completely.

Step 3: Run the “terraform init” command for initialization.

terraform init
terraform init

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

terraform plan
terraform plan
Resources Created
Resources Created

Step 5: Run the command: “terraform apply” to create the instance with new “VPC” & “subnet”.

terraform apply
terraform apply

Step 5: Type “yes” to create the Instance with the new “VPC” & “Subnet”.

Yes
Yes

Step 6: Go to the “Instance” section & “assignment-4” instance will be successfully created with the New “VPC” & its subnet.

Instance Deployed in VPC
Instance Deployed in VPC

Terraform Resources:

Create an EC2 Instance With an Elastic IP Address

Create an EC2 Instance Using Terraform

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

Creating an Architecture using Terraform on AWS

--

--