Automating AWS VPC Setup and Website Deployment Through Terraform (IAC) Tool.

Ghazanfar Ali
4 min readAug 18, 2023

--

Introduction:

In this terraform project we will create AWS VPC, Internet gateway, public , private subnets, route table, subnets association, s3 bucket (to store terraform state), security group , EC2 instance in our own VPC then deploy static website on that instance. This all will be done with the help of terraform IAC tool.

Lets start!

First of all we will create new directory in our local system and start creating terraform files in it.

Providers.tf file:

This file will only conatin details of our provider like aws and region details which are mentioned in variable file, that variable will be use in this file:

Vars.tf file:

This file will contain all the variables that will be use in whole project.

Also generate ssh key in same directory we will push this key in our ec2 instance later.

Now create resource file for vpc:

This file will contain all the details reagrding VPC, subnets, interet gateway, route table, public subnet association with route table

Now time to test it:

First of all initialize the terraform in the current directory where all the files located:

Then run terraform validate to check any syntax error in all the files:

Then format all the files:

Now run plan command to check what changes terraform will make:

Now time to apply:

It just created the new VPC in AWS:

Subnets:

Internet Gateway:

Route table:

Now we will create security group through terraform:

For this we will create new file:

Now apply changes:

⇒ terraform apply

It has created security group:

Next we will launch instance using that security group and put in our VPC that created earlier:

We will use s3 bucket to save out terraform state file the reason behind this if we work in a team everyone should have same terraform state file:

First create s3 bucket in aws then terraform file:

Note: When we run terraform init command this will

Now we will write shell script that will install webserver and deploy static website on our ec2 instance:

Now we can write our instance.tf file which will create ec2 instance also push that web.sh file and run it.

Now time to test this:

It created the ec2 instance:

You can take the ssh of instance using private key that uploaded on instance through terraform.

Check the website with instance public ip:

At last delete everything by just single command:

--

--

Ghazanfar Ali
Ghazanfar Ali

Written by Ghazanfar Ali

I write technical blogs on DevOps and AWS, Azure and GCP

No responses yet