DEV Community

Cover image for Deploy a VPC with Terraform : AWS Project
Shubham Murti
Shubham Murti

Posted on

Deploy a VPC with Terraform : AWS Project

Introduction

In this blog post, I will guide you through the process of deploying a Virtual Private Cloud (VPC) using Terraform on Amazon Web Services (AWS). This project is classified as Advanced and is expected to take about one hour to complete. The main objective is to help you understand how to manage infrastructure using code and automate the provisioning process efficiently.

What you will learn:

  • How to use Terraform to create a VPC, subnets, route tables, gateways, and EC2 instances.
  • How to manage resources with Terraform for future scalability and automation.

Understanding Infrastructure as Code (IaC)

Q. What is Infrastructure as Code?

Infrastructure as Code (IaC) is a modern approach to managing and provisioning IT infrastructure through code and automation tools, rather than relying on manual processes. By utilizing IaC, I can manage servers, storage, networks, and other infrastructure components through machine-readable definition files.

Benefits of IaC
IaC provides several advantages:

  • Consistency: Ensures the same infrastructure setup every time it's deployed, reducing the chances of configuration drift.
  • Version Control: Infrastructure configurations can be tracked and versioned using systems like Git, making collaboration easier.
  • Reproducibility: Enables the recreation of infrastructure from scratch with the same configuration.
  • Automation: Speeds up deployment processes and reduces manual errors through automated provisioning.

Q. When to Use Infrastructure as Code

I find Infrastructure as Code particularly beneficial in various scenarios, including:

  • Cloud Deployments: Efficiently managing cloud resources like virtual machines and databases.
  • Multi-Environment Management: Maintaining consistent infrastructure across development, staging, and production environments.
  • Scaling Operations: Automating the scaling of infrastructure based on load or usage requirements.
  • Disaster Recovery: Quickly redeploying infrastructure in case of failures or disasters using version-controlled configurations.
  • Compliance and Security: Ensuring that infrastructure adheres to security and compliance requirements through codified policies and configurations.

Introduction to Terraform

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows me to define and provision infrastructure using a high-level configuration language called HashiCorp Configuration Language (HCL).

Key Features of Terraform

Some of the standout features of Terraform include:

  • Declarative Configuration: I can describe the desired state of my infrastructure, and Terraform manages the provisioning and management.
  • Provider Support: Terraform supports a wide range of cloud providers, making it versatile for different projects.
  • Resource Management: Manages the lifecycle of infrastructure resources, including creation, updates, and deletions.
  • State Management: Keeps track of the current state of my infrastructure, ensuring changes are applied correctly.

Importance of the State File

In Terraform, the state file is crucial as it stores the current state of my infrastructure. It acts as a source of truth, mapping real-world resources to my configuration. The state file helps with:

  • Tracking Resources: Keeps track of resources managed by Terraform, including their attributes and relationships.
  • Planning Changes: Assists in determining what changes need to be made to align real-world infrastructure with the configuration.
  • Managing Dependencies: Maintains information about dependencies between resources to apply changes in the correct order.
  • Storing Metadata: Stores metadata required for operations like resource updates and deletions.

Architectural Diagram

To give a clearer understanding of the setup, I recommend including an architectural diagram that visually represents your VPC architecture, showing the relationship between the VPC, subnets, route tables, and instances.

Image description

Pre-requisites

Before diving into the project of deploying a Virtual Private Cloud (VPC) using Terraform, it's crucial to ensure that you have the necessary tools and configurations in place. Below are the key pre-requisites for successfully completing the project:

1. Cloud Service Provider: AWS

For this project, we will be using Amazon Web Services (AWS) as our cloud service provider. AWS provides a comprehensive set of cloud services, including computing power, storage options, and networking features, making it an ideal platform for deploying a VPC.

2. Required Tools and Downloads: Terraform Binaries

To get started with Terraform, you'll need to download the Terraform binaries compatible with your operating system. Terraform is available for various platforms, including Windows, macOS, and Linux.

Download Terraform:

  • Visit the Terraform Downloads Page to access the latest versions ofTerraform.
  • Choose the appropriate version for your operating system:

1. Windows: Select the Windows zip file and extract it to a directory of your choice.
2. macOS: You can use Homebrew with the command: brew install terraform, or download the zip file from the website.
3. Linux: Download the appropriate zip file, extract it, and place the binary in a directory included in your system's PATH.

3. Setting Up Your Environment

After downloading Terraform, ensure your development environment is ready for deployment. Here are the steps to set up your environment:

Verify Installation:

  • Open a terminal or command prompt and run the following command to verify that Terraform is installed correctly:

terraform -v

AWS CLI (Optional but Recommended):

  • It's also recommended to install the AWS Command Line Interface (CLI) for easier interaction with AWS resources. You can download the AWS CLI from the AWS CLI Installation page.
  • After installation, configure the CLI using:

aws configure

Setting Up Your Workspace:
Create a new directory for your Terraform project. This directory will contain all the configuration files you will create later.



mkdir terraform-vpc-project
cd terraform-vpc-project


Enter fullscreen mode Exit fullscreen mode

Project Setup

1. Downloading Terraform Binaries

Start by downloading the Terraform binaries from the official Terraform website. Follow the installation instructions specific to your operating system.

2. Initializing the Terraform Working Directory

Next, create a working directory for your Terraform project. Navigate to that directory in your terminal and run the command:

terraform init

This command initializes the directory and downloads the necessary provider plugins.

3. Documenting Your Environment

To visualize your VPC architecture, I recommend using a diagramming tool like Draw.io to document your environment. This will help in understanding the components of the VPC.

Example: 
I created this diagram using draw.io

Image description

Terraform Configuration

Now, let's configure the necessary resources using Terraform.

1. Defining the Virtual Private Cloud (VPC)
Create a main.tf file in your working directory and define the VPC:



resource "aws_vpc" "my_vpc" {
  cidr_block = "10.0.0.0/16"
  enable_dns_support = true
  enable_dns_hostnames = true
}


Enter fullscreen mode Exit fullscreen mode

2. Creating Route Tables (Public/Private)
Next, create route tables for public and private subnets:



resource "aws_route_table" "public" {
  vpc_id = aws_vpc.my_vpc.id

route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.my_igw.id
  }
}


Enter fullscreen mode Exit fullscreen mode

3. Setting Up Route Table Associations
Associate the route tables with your subnets:



resource "aws_route_table_association" "public_association" {
  subnet_id      = aws_subnet.public_subnet.id
  route_table_id = aws_route_table.public.id
}


Enter fullscreen mode Exit fullscreen mode

4. Configuring the Internet Gateway
Create an Internet Gateway:



resource "aws_internet_gateway" "my_igw" {
  vpc_id = aws_vpc.my_vpc.id
}


Enter fullscreen mode Exit fullscreen mode

5. Allocating Elastic IP and NAT Gateway
Allocate an Elastic IP and create a NAT Gateway for your private subnets:



resource "aws_eip" "nat" {
  vpc = true
}

resource "aws_nat_gateway" "nat" {
  allocation_id = aws_eip.nat.id
  subnet_id     = aws_subnet.public_subnet.id
}


Enter fullscreen mode Exit fullscreen mode

6. Launching EC2 Instances in Public/Private Subnets
Define your EC2 instances:



resource "aws_instance" "public_instance" {
  ami           = "ami-0c55b159cbfafe1f0" // Amazon Linux 2 AMI
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.public_subnet.id

tags = {
    Name = "PublicInstance"
  }
}
resource "aws_instance" "private_instance" {
  ami           = "ami-0c55b159cbfafe1f0" // Amazon Linux 2 AMI
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.private_subnet.id
  tags = {
    Name = "PrivateInstance"
  }
}


Enter fullscreen mode Exit fullscreen mode

7. Configuring Security Groups
Set up security groups for your instances:



resource "aws_security_group" "allow_ssh" {
  vpc_id = aws_vpc.my_vpc.id

ingress {
    from_port   = 22
    to_port     = 22
    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"]
  }
}


Enter fullscreen mode Exit fullscreen mode

8. Verifying Connectivity
After the deployment, verify the connectivity:

  • Testing Connectivity for Public Instances
  • Testing Connectivity for Private Instances

9. Cleanup and Resource Deletion
Deleting the Terraform Deployment



terraform destroy


Enter fullscreen mode Exit fullscreen mode

10. Verifying Resource Deletion
Ensure that all resources have been successfully deleted and no additional costs are incurred.

Output

Image description

Closure

In this blog, I walked you through deploying a VPC with Terraform on AWS. We covered key concepts of Infrastructure as Code, explored Terraform's features, and completed a hands-on project to create and manage a VPC. Embracing Infrastructure as Code simplifies infrastructure management, ensuring consistency and reproducibility.

Resources

Shubham Murti — Aspiring Cloud Security Engineer | Weekly Cloud Learning !!

Let’s connect: Linkdin, Twitter, Github

Top comments (0)