Create VPC in AWS using Terraform Modules

In this article, we will explore how to efficiently create a Virtual Private Cloud (VPC) in Amazon Web Services (AWS) using Terraform modules | Create VPC in AWS using Terraform Modules, streamlining the process of infrastructure provisioning and management.

Create a MySQL RDS Database Instance with Terraform 12 1

What is Terraform?

1280px Terraform Logo.svg removebg preview 1
  • It is an open-source IaaC (Infrastructure as a code) software tool where you define and create resources using providers in the declarative configuration language example JSON.
  • With Terraform, You can package and reuse the code in the form of modules.
  • It supports a number of cloud infrastructure providers such as AWS, Azure, GCP, IBM Cloud, OCI, etc.

What are the components of VPC in AWS?

  1. Private Subnet:
    • No direct internet access, suitable for resources needing enhanced security, like databases.
  2. Public Subnet:
    • Has a route to the internet via an Internet Gateway, used for resources that require public accessibility, such as web servers.
  3. Internet Gateway:
    • A scalable and redundant component that enables communication between instances in a VPC and the internet, allowing resources in a public subnet to connect to the internet and vice versa.
  4. Route Table (Public):
    • Routes traffic in and out of a public subnet, directing it through the Internet Gateway for internet access.
  5. Route Table (Private):
    • Routes traffic within the VPC, typically without a direct route to the internet. Used for communication between instances in different subnets.
  6. Security Group:
    • Acts as a virtual firewall for instances. It controls inbound and outbound traffic based on rules defined by the user, providing an additional layer of security.
  7. NAT Gateway:
    • A managed network address translation (NAT) service that allows instances in a private subnet to initiate outbound traffic to the internet while preventing inbound traffic from reaching those instances. Useful for instances without public IP addresses.

What is Terraform Modules?

A Terraform module is a set of configuration code files with structured folder architecture. we create these modules to combine resources that are used for a specific single operation, which reduces the lines of code needed to create related infrastructure components.

Module Components

A typical Terraform module consists of the following components:

  1. main.tf: This file contains the main configuration for the resources defined in the module.
  2. variables.tf: Defines input variables that users can customize when using the module.
  3. outputs.tf: Specifies output values that users can retrieve when the module is applied.
  4. README.md: Documentation detailing how to use the module, including variables, outputs, and any specific considerations.

Types of Terraform Modules

With Terraform, you are most likely to come across one of three main categories of modules:

Root Module

  • The primary entry point for Terraform configurations.
  • Contains the main configuration files, typically orchestrating the deployment of multiple resources.
  • Serves as the top-level module in a Terraform project.

Child Module

  • Subordinate modules encapsulated within the root module or other child modules.
  • Focus on specific functionalities or resources, contributing to the modular structure of the infrastructure code.
  • Enhances code organization and maintainability within the broader project.

Published Modules

  • External modules shared and published for broader use.
  • Created by the community or organizations to facilitate the reuse of well-designed infrastructure components.
  • Accessed through various sources, such as the Terraform Registry, offering pre-built solutions for common infrastructure patterns.
image 7

Applying Terraform Modules Across Environments

  1. Development Environment:
    • Purpose: Customize modules for rapid development and testing.
    • Example: In the development environment, use smaller instance types and enable debugging features for faster iterations.
  2. Staging Environment:
    • Purpose: Test integration with realistic configurations.
    • Example: In the staging environment, adjust configurations for larger instance types and use more realistic resource settings.
  3. Production Environment:
    • Purpose: Emphasize high availability, scaling, and security.
    • Example: In the production environment, configure modules for larger instance types, auto-scaling groups, and stringent security measures.

VPC Architecture Overview

Screenshot 2023 12 15 124141

AWS VPC (Virtual Private Cloud) is a networking service that allows you to create a private, isolated virtual network within the AWS cloud. Here are some key points to note about AWS VPC.

  1. Isolated Virtual Network: A VPC provides a logically isolated virtual network environment where you can launch AWS resources such as EC2 instances, RDS databases, and more. This means that your resources are not directly accessible from the public internet, which can help to improve security and compliance
  2. IP Addressing: You can define your own IP address range for your VPC, known as a CIDR (Classless Inter-Domain Routing) block. This gives you complete control over IP address assignment and helps in network segmentation
  3. Subnets: Within a VPC, you can create subnets to partition the IP address range. Subnets allow you to allocate resources in different Availability Zones, providing high availability and fault tolerance for your applications
  4. Routing: VPC comes with a routing table that controls the traffic flow between subnets and to the internet. You can define custom routing rules to direct traffic within the VPC or to external networks.
  5. Internet Connectivity: By default, VPC provides internet connectivity through an Internet Gateway (IGW). This allows resources within the VPC to communicate with the internet, enabling access to external services and updates.
  6. Security: VPC offers built-in security features such as Security Groups and Network Access Control Lists (ACLs) to control inbound and outbound traffic at the instance and subnet level. You can define rules to allow or deny specific types of traffic based on protocols, ports, and IP addresses.
  7. Peering and VPN: VPC supports peering connections, which allow you to connect multiple VPCs together, enabling secure communication between them. Additionally, you can establish Virtual Private Network (VPN) connections to connect your VPC with your on-premises network.
  8. VPC Endpoints: VPC endpoints enable private connectivity to AWS services without requiring internet access. This provides secure and efficient access to services like S3, DynamoDB, and more from within your VPC.
  9. VPC Flow Logs: VPC Flow Logs capture information about the IP traffic flowing in and out of your VPC. You can use this feature for monitoring, troubleshooting, and security analysis of network traffic.

Prerequisite

  • AWS Account: You should have an active AWS account with the necessary permissions to create and manage resources.
  • Terraform: Terraform is an infrastructure provisioning tool that you’ll need to install on your local machine.
  • Visual Studio Code Editor Installed

Create VPC in AWS using Terraform Modules

Summary view of the terraform files in VS code:

Screenshot 2023 12 15 133444

Step 1:- Create provider.tf file

The provider.tf file in Terraform is a configuration file that specifies the cloud provider and its corresponding plugin that Terraform will use to manage resources in that provider.

Provider.tf file is used for the following:-

  • Provider Declaration: Declares the cloud or infrastructure provider, such as AWS or Azure.
  • Authentication Details: Includes credentials (e.g., access and secret keys) for connecting to the chosen provider.
  • Region Specification: Specifies the geographic region where resources will be provisioned.
  • Version Constraints: Optionally sets constraints on the provider version for compatibility.
  • Additional Settings: May include other provider-specific configurations, like endpoints or custom parameters.
provider.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.6" # which means any version equal & above
    }
  }
  required_version = ">= 0.13"
}

provider "aws" {
  region = var.region
  profile = "default" 

}
Screenshot 2023 12 15 135538

Step 2:- Create vpc.tf file

In Terraform, the vpc.tf file typically contains the configuration code for creating and defining an Amazon Virtual Private Cloud (VPC) along with its associated resources.vpc.tf

Module- terraform-aws-module/vpc

vpc.tf
# Create VPC using Terraform Module
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  # Details
  name            = "${var.name}-${local.name}"
  cidr            = var.cidr
  azs             = var.azs
  public_subnets  = var.public_subnets
  private_subnets = var.private_subnets

  database_subnets                   = var.database_subnets
  create_database_subnet_group       = var.create_database_subnet_group
  create_database_subnet_route_table = var.create_database_subnet_route_table
  # create_database_internet_gateway_route = true
  # create_database_nat_gateway_route = true

  # NAT Gateways - Outbound Communication
  enable_nat_gateway = var.enable_nat_gateway
  single_nat_gateway = var.single_nat_gateway

  # DNS Parameters in VPC
  enable_dns_hostnames = true
  enable_dns_support   = true

  # Additional tags for the VPC
  tags     = local.tags
  vpc_tags = local.tags

  # Additional tags
  # Additional tags for the public subnets
  public_subnet_tags = {
    Name = "VPC Public Subnets"
  }
  # Additional tags for the private subnets
  private_subnet_tags = {
    Name = "VPC Private Subnets"
  }
  # Additional tags for the database subnets
  database_subnet_tags = {
    Name = "VPC Private Database Subnets"
  }
  map_public_ip_on_launch = true
}
Screenshot 2023 12 15 135620

Step 3:- Create variables.tf file

A variables.tf file in Terraform is where you define input variables for your infrastructure code, allowing for customization and flexibility by parameterizing values that can be easily modified without changing the core code.

variables.tf
# generic variables defined

# AWS Region
variable "region" {
  description = "Region in which AWS Resources to be created"
  type        = string
  default     = "ap-south-1"
}
# Environment Variable
variable "environment" {
  description = "Environment Variable used as a prefix"
  type        = string
  
}
# Business Division
variable "owners" {
  description = "organization this Infrastructure belongs"
  type        = string
  default     = "business Divison"
}

# VPC variables defined as below
# VPC Name
variable "name" {
  description = "VPC Name"
  type        = string
  default     = "vpc"
}

# VPC CIDR Block
variable "cidr" {
  description = "VPC CIDR Block"
  type        = string
  default     = "10.0.0.0/16"
}

# VPC Availability Zones
variable "azs" {
  description = "A list of availability zones names or ids in the region"
  type        = list(string)
  default     = ["ap-south-1a", "ap-south-1b"]
}

# VPC Public Subnets
variable "public_subnets" {
  description = "A list of public subnets inside the VPC"
  type        = list(string)
  default     = ["10.0.101.0/24", "10.0.102.0/24"]
}

# VPC Private Subnets
variable "private_subnets" {
  description = "A list of private subnets inside the VPC"
  type        = list(string)
  default     = ["10.0.1.0/24", "10.0.2.0/24"]
}

# VPC Database Subnets
variable "database_subnets" {
  description = "A list of database subnets inside the VPC"
  type        = list(string)
  default     = ["10.0.151.0/24", "10.0.152.0/24"]
}

# VPC Create Database Subnet Group (True / False)
variable "create_database_subnet_group" {
  description = "VPC Create Database Subnet Group"
  type        = bool
  default     = true
}

# VPC Create Database Subnet Route Table (True or False)
variable "create_database_subnet_route_table" {
  description = "VPC Create Database Subnet Route Table"
  type        = bool
  default     = true
}


# VPC Enable NAT Gateway (True or False) 
variable "enable_nat_gateway" {
  description = "provision NAT Gateways for each of your private networks"
  type        = bool
  default     = true
}

# VPC Single NAT Gateway (True or False)
variable "single_nat_gateway" {
  description = "single shared NAT Gateway across all of your private networks"
  type        = bool
  default     = true
}
Screenshot 2023 12 15 135559

Step 4:- Create outputs.tf file

An outputs.tf file in Terraform defines output values that you want to display after the infrastructure deployment, providing a way to expose specific information, such as resource IDs or computed results, for easier access or use in subsequent processes.outputs.tf

outputs.tf
# VPC ID
output "vpc_id" {
  description = "The ID of the VPC"
  value       = module.vpc.vpc_id
}

# VPC CIDR blocks
output "vpc_cidr_block" {
  description = "The CIDR block of the VPC"
  value       = module.vpc.vpc_cidr_block
}

# VPC Private Subnets
output "private_subnets" {
  description = "A list of private subnets inside the VPC"
  value       = module.vpc.private_subnets
}

# VPC Public Subnets
output "public_subnets" {
  description = "A list of public subnets inside the VPC"
  value       = module.vpc.public_subnets
}

# VPC NAT gateway Public IP
output "nat_public_ips" {
  description = "List of public Elastic IPs created for AWS NAT Gateway"
  value       = module.vpc.nat_public_ips
}

# VPC AZs
output "azs" {
  description = "A list of availability zones specified as argument to this module"
  value       = module.vpc.azs
}
Screenshot 2023 12 15 135606

Step 5:- Create terraform.tfvars file

A terraform.tfvars file is used to set values for Terraform variables, providing a convenient way to customize configurations without modifying the main Terraform files.This file allows users to input specific configuration details, such as AWS region, environment names, or any other variable defined in the Terraform code, making it easier to manage and share configurations.

terraform.tfvars
# Generic Variables
region      = "ap-south-1"
environment = "prod"
owners      = "aws"


# VPC Variables
name                               = "vpc-terraform" # Overridning the name defined in variable file
cidr                               = "10.0.0.0/16"
azs                                = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
public_subnets                     = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
private_subnets                    = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
database_subnets                   = ["10.0.151.0/24", "10.0.152.0/24", "10.0.153.0/24"]
create_database_subnet_group       = true
create_database_subnet_route_table = true
enable_nat_gateway                 = true
single_nat_gateway                 = true
Screenshot 2023 12 15 135612

Step 6:- Create locals.tf file

A locals.tf file is a Terraform configuration file that defines local values. Local values are variables that are only accessible within the module where they are defined.

locals.tf
# Local Values in Terraform
locals {
  owners      = var.owners
  environment = var.environment
  name        = "${local.owners}-${local.environment}"
  tags = {
    owners      = local.owners
    environment = local.environment
  }
}
Screenshot 2023 12 15 141706

Step 7:- Let’s Deploy

 Let’s run our configuration and make sure everything works correctly. On the command line, run the following commands:

  • terraform init

The terraform init the command is used to initialize a new or existing Terraform configuration. This command downloads the required provider plugins and sets up the backend for storing state.

Screenshot 2023 12 15 135839
  • terraform plan

The terraform plan the command is used to create an execution plan for the Terraform configuration. This command shows what resources Terraform will create, modify, or delete when applied.

Screenshot 2023 12 15 135901
Screenshot 2023 12 15 135939
  • terraform apply

The terraform apply the command is used to apply the Terraform configuration and create or modify resources in the target environment.

Screenshot 2023 12 15 140049
Screenshot 2023 12 15 140243
  • terraform destroy

The primary purpose of terraform destroy is to remove all the resources that were created by the Terraform configuration. 

Step 8:- Go to the AWS console and verify

Screenshot 2023 12 15 141810

Conclusion:

We have covered Create VPC in AWS using Terraform Modules | Implementing AWS VPC creation with Terraform modules enhances scalability, consistency, and collaboration. This modular approach simplifies customization, promotes code reuse, and ensures efficient management of AWS infrastructure. Terraform’s abstraction of VPC configuration into modules facilitates standardized and organized deployment.

Reference:-

For reference visit the official website TerraformRegistry.

Any queries pls contact us @Devopshint.

Related Articles:

Terraform State File Management | Terraform Local State File | Terraform Remote State

About Akash Bhujbal

Hey, I am Akash Bhujbal, I am an aspiring DevOps and Cloud enthusiast who is eager to embark on a journey into the world of DevOps and Cloud. With a strong passion for technology and a keen interest in DevOps and Cloud based solutions, I am driven to learn and contribute to the ever-evolving field of DevOps and Cloud.

1 thought on “Create VPC in AWS using Terraform Modules”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link