VPC
In this section, you'll learn how to set up the networking for your AWS infrastructure using Terraform. We’ll guide you through creating a Virtual Private Cloud (VPC) and setting up public and private subnets.
Step 1: Understanding the Basics
What is a VPC?
A Virtual Private Cloud (VPC) is like a secure, isolated virtual network within AWS where you can place your resources, such as servers and databases.
What are Subnets? Subnets divide your VPC into smaller networks. There are two main types:
- Public Subnets: These are accessible from the internet, perfect for resources like web servers.
- Private Subnets: These are isolated from the internet, ideal for backend services like databases.
Step 2: Setting Up Your Network
Below is a single Terraform code block that sets up the entire networking structure, including the VPC, public subnets, and private subnets. You can copy and paste this code directly into your Terraform configuration.
locals {
context = {
namespace = "example"
stage = "test"
name = "networking"
}
}
module "vpc" {
source = "../modules/vpc"
name = "my-vpc"
cidr = "10.0.0.0/16"
context = local.context
}
module "public_subnet" {
source = "../modules/vpc-public-subnet"
context = local.context
vpc_id = module.vpc.id
internet_gateway_id = module.vpc.internet_gateway_id
config = {
"a" = { az = "eu-central-1a", cidr = "10.0.1.0/24", nat = true }
"b" = { az = "eu-central-1b", cidr = "10.0.2.0/24", nat = false }
}
}
module "private_subnet" {
source = "../modules/vpc-private-subnet"
context = local.context
vpc_id = module.vpc.id
config = {
"a" = { az = "eu-central-1a", cidr = "10.0.51.0/24" }
}
nat_gateway_routing = {
"a" = module.public_subnet.nat_gateways["eu-central-1a"]
}
}
module "database_subnet" {
source = "../modules/vpc-private-subnet"
context = local.context
vpc_id = module.vpc.id
config = {
"db-a" = {
az = "eu-central-1a"
cidr = "10.0.101.0/24"
}
}
database_subnet = true
}What This Does:
- VPC Module: Creates a Virtual Private Cloud (VPC) where all your resources will be hosted.
- VPC Module Outputs: VPC ID and Internet Gateway ID, which are used by the subnets.
- Public Subnet Module: Sets up public subnets in the VPC, allowing internet access for resources like web servers.
- Public Subnet Module Outputs: Generates NAT gateways used for routing traffic.
- Private Subnet Module: Creates private subnets that are isolated from direct internet access, routing their traffic through the NAT gateways in the public subnets.
Step 3: Applying the Configuration
After copying the above code into your Terraform configuration file (e.g., main.tf), run the following commands to apply the configuration:
terraform init
terraform applyThis will create the VPC and subnets as described, laying the foundation for your AWS infrastructure.