AWS VPC — Using Terraform Modules

AWS VPC (Virtual Private Cloud)



AWS VPC revolutionizes networking in the AWS ecosystem, offering a suite of features for creating secure and customizable virtual networks. Here's a deep dive into its core functionalities:

Isolated Virtual Network

With AWS VPC, you construct a secluded virtual network environment to host your AWS resources, shielding them from direct exposure to the public internet. This heightened isolation enhances security and aligns with compliance standards.

IP Addressing Flexibility

Customize your VPC's IP address range using CIDR blocks, granting granular control over IP address allocation and facilitating network segmentation.

Subnets for Resilience

Divide your VPC into subnets, strategically distributing resources across Availability Zones. This redundancy boosts availability and resilience for your applications.

Dynamic Routing Control

Leverage VPC's routing table to govern traffic flow within your virtual network and towards external destinations. Craft tailored routing rules to steer traffic effectively.

Internet Connectivity

By default, VPC offers internet connectivity via an Internet Gateway (IGW), enabling seamless communication between resources within the VPC and external services.

Robust Security Measures

Safeguard your VPC using Security Groups and Network Access Control Lists (ACLs) to regulate inbound and outbound traffic at both instance and subnet levels. Fine-tune rules based on protocols, ports, and IP addresses.

Interconnectivity Options

Establish peering connections between VPCs for secure communication across multiple environments. Additionally, set up Virtual Private Network (VPN) connections to link your VPC with on-premises networks.

VPC Endpoints for Enhanced Privacy

Ensure private connectivity to AWS services with VPC endpoints, eliminating the need for internet access. This offers secure and efficient access to services like S3 and DynamoDB from within your VPC.

Insightful Monitoring

Gain visibility into your VPC's traffic patterns with VPC Flow Logs, capturing data on inbound and outbound IP traffic. Analyze these logs for monitoring, troubleshooting, and security analysis purposes.

Seamless Integration

Seamlessly integrate VPC with a plethora of AWS services such as AWS Lambda, AWS Elastic Beanstalk, and AWS CloudFormation. This integration empowers you to build robust and scalable applications within your VPC environment.

Prerequisites

  • AWS Account: Ensure you have an active AWS account with the requisite permissions to create and manage resources.
  • Terraform Installation: Install Terraform, an infrastructure provisioning tool, on your local machine to streamline resource management.

Folder Structure

provider.tf

The provider.tf file is responsible for authenticating and establishing a connection with your AWS account. Start by configuring the AWS provider to authenticate with your AWS account and name this file 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" #AWS Credentials Profile (profile = "default") configured on local
  #   access_key = var.aws_access_key
  #   secret_key = var.aws_secret_key
}
  

vpc.tf

Use the vpc.tf file to define the Virtual Private Cloud (VPC) resources using a module. This file will create a VPC with the specified CIDR block and a subnet within that VPC. Name this file 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"
  }
  # Instances launched into the Public subnet should be assigned a public IP address. Specify true to indicate that instances launched into the subnet should be assigned a public IP address
  map_public_ip_on_launch = true
}
  

vpc-variables.tf

The vpc-variables.tf file is used to define Terraform variables for AWS resources. Name this file vpc-variables.tf.

# generic variables defined

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

# 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     = ["eu-west-2a", "eu-west-2b"]
}

# 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, Controls if database subnet group should be created"
  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, Controls if separate route table for database should be created"
  type        = bool
  default     = true
}


# VPC Enable NAT Gateway (True or False) 
variable "enable_nat_gateway" {
  description = "Should be true if you want to 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 = "Should be true if you want to provision a single shared NAT Gateway across all of your private networks"
  type        = bool
  default     = true
}
  

output.tf

Use the output.tf file to define outputs that can be retrieved after applying your Terraform configuration. Name this file output.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
}
  

terraform.tfvars

The terraform.tfvars file is for defining input variables and their values for the VPC and cluster. Name this file terraform.tfvars.

# Generic Variables
region      = "eu-west-2"
environment = "prod"
owners      = "aws"

# VPC Variables
name                               = "vpc-terraform" # Overriding the name defined in variable file
cidr                               = "10.0.0.0/16"
azs                                = ["eu-west-2a", "eu-west-2b", "eu-west-2c"]
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
  

locals.tf

The 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. Name this file 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
  }
}
  

Running Terraform

Now, let’s go to the terminal and run Terraform. First, initialize to download all module information, then run terraform apply.

$ terraform fmt
$ terraform init # Initialize
$ terraform plan # Check the plan before apply
$ terraform apply -auto-approve
  

GOOD JOB: Your VPC setup is now ready on AWS.

terraform, terraforming, terraform install, terraformars, terraform aws, terraform cloud, terraform import, terraform aws provider, ansible vs terraform, terraform vs ansible, terraform certification, terraform modules, terraform download, terraform registry, terraform azure, terraform associate certification, terraform apply, terraform aws_instance, terraform alternatives, terraform aws_iam_role, terraform azurerm, terraform aws security group, aws terraform, azure terraform, atlantis terraform, azurerm terraform, aws_instance terraform, aws security group terraform, aws_lambda_function terraform, aws_iam_role terraform, aws_s3_bucket terraform, terraform backend, terraform backend s3, terraform best practices, terraform basics, terraform block, terraform base64 encode, terraform book, terraform boolean, terraform backend local, terraform block comment, brew install terraform, bicep vs terraform, backend terraform, backend s3 terraform, basic terraform commands, basics of terraform, backend azurerm terraform, backend local terraform, base64 terraform, boolean terraform, terraform count, terraform commands, terraform concat, terraform cdk, terraform coalesce, terraform conditional, terraform contains, terraform console, coalesce terraform, cloudformation vs terraform, concat terraform, count terraform, crossplane vs terraform, cloudflare terraform, contains terraform, cdk terraform, cloudfront terraform, cidrsubnet terraform, terraform definition, terraform dynamic block, terraform destroy, terraform docs, terraform depends_on, terraform data block, terraform debug, terraform dynamodb, terraform docker, download terraform, dynamic block terraform, depends on terraform, databricks terraform, data terraform, datadog terraform, dynamodb terraform, docker terraform, debug terraform, digitalocean terraform, terraform enterprise, terraform eks module, terraform ec2 instance, terraform environment variables, terraform example, terraform error cycle, terraform ecs service, terraform element, terraform ecr, terraform eventbridge, eks terraform, ec2 terraform, element terraform, error cycle terraform, eventbridge terraform, ecs terraform, ecs task definition terraform, ecr terraform, efs terraform, eks cluster terraform, terraform for_each, terraform functions, terraform for loop, terraform fmt, terraform flatten, terraform format, terraform file, terraform force unlock, terraform for_each list, terraform fileset, for_each terraform, flatten terraform, for loop terraform, format terraform, file terraform, functions in terraform, force unlock terraform, for each terraform list, for_each output terraform, fmt terraform, terraform github, terraform gcp, terraform github provider, terraform gitignore, terraform graph, terraform github actions, terraform getting started, terraform get, terraform gitlab provider, terraform gke, github terraform, gitlab terraform, github terraform provider, gcp terraform, gta 5 terraform, github actions terraform, gitignore terraform, gitlab terraform state, gitlab terraform provider, grafana terraform, terraform helm provider, terraform helm_release, terraform hashicorp, terraform hcl, terraform heredoc, terraform http provider, terraform hello world, terraform hyper-v, terraform hashicorp/aws, terraform hashicorp certification, hashicorp terraform, hashicorp terraform certification, how to install terraform on windows, how to terraform mars, how to debug terraform, how to download terraform, how to terraform import, how to import a resource in terraform, how to loop in terraform, how to ignore changes in terraform, terraform init, terraform interview questions, terraform import block, terraform ignore changes, terraform if statement, terraform iam role, terraform import resource, install terraform, iam role terraform, ignore changes terraform, if statement terraform, import terraform, interview questions on terraform, import block terraform, if terraform, install terraform brew, import resource terraform, terraform jsonencode, terraform join function, terraform jsondecode, terraform jobs, terraform json, terraform join lists, terraform jenkins, terraform jsonencode example, terraform json variable, terraform join two strings, jsonencode terraform, join terraform, jsondecode terraform, jenkins terraform, json to terraform converter, jenkins terraform plugin, jenkins vs terraform, jfrog terraform, jhooq terraform, jetbrains terraform, terraform kubernetes provider, terraform kms key, terraform kubernetes deployment, terraform kubectl provider, terraform kubernetes_secret, terraform kubernetes_manifest, terraform kubernetes namespace, terraform kubectl_manifest, terraform keys function, terraform keycloak, kubernetes provider terraform, kms key terraform, kubernetes vs terraform, key vault terraform, keycloak terraform, kubernetes_manifest terraform, kubectl provider terraform, kubernetes_secret terraform, kubectl_manifest terraform, kubernetes_namespace terraform, terraform labs, terraform locals, terraform lookup, terraform lifecycle, terraform lambda, terraform latest version, terraform logo, terraform language, terraform list, terraform license change, lookup terraform, learn terraform, lambda terraform, latest terraform version, locals terraform, lifecycle terraform, local exec terraform, local_file terraform, list in terraform, linux install terraform, terraform meaning, terraform mars, terraform map, terraform merge, terraform moved, terraform multiline string, terraform module source, terraform merge lists, terraform module example, merge terraform, modules in terraform, map terraform, mac install terraform, moved terraform, meta arguments in terraform, module source terraform, module eks terraform, module vpc terraform, map variable terraform, terraform null resource, terraform nested for_each, terraform nested for loop, terraform null value, terraform nat gateway, terraform new relic, terraform naming conventions, terraform null provider, terraform nullable, terraform nlb, null resource terraform, new relic terraform, nested for loop terraform, nat gateway terraform, nested for_each terraform, null provider terraform, nonsensitive terraform, nutanix terraform, nlb terraform, netbox terraform, terraform output, terraform open source, terraform optional variable, terraform optional, terraform okta provider, terraform output for_each, terraform opensearch, terraform object variable, terraform oci provider, output terraform, oci terraform, open terraform, opentofu vs terraform, okta terraform, opensearch terraform, openstack terraform, optional variable terraform, optional terraform, openshift terraform, terraform providers, terraform plan, terraform proxmox, terraform provider aws, terraform path.module, terraform provisioner, terraform pricing, terraform provider alias, terraform plan options, pulumi vs terraform, path.module terraform, provider aws terraform, proxmox terraform, provisioners in terraform, plan b terraform, providers terraform, provider alias terraform, provider kubernetes terraform, provider helm terraform, terraform quickstart, terraform quicksight, terraform questions, terraform question mark, terraform quick tutorial, terraform qemu, terraform quotes in string, terraform query state, terraform quiz, terraform query data source, quicksight terraform, quiz introducing to terraform for google cloud, questions on terraform, question mark in terraform, quiz introduction to terraform state, queue visibility timeout terraform, qualys terraform, query terraform state, quicksight terraform module, quicksight dashboard terraform, terraform refresh, terraform replace, terraform rds, terraform remote state, terraform resource, terraform required_providers, terraform releases, terraform remove from state, terraform random_password, registry terraform, rds terraform, random_password terraform, replace terraform, route53 terraform, regex terraform, required_providers terraform, rds terraform module, random provider terraform, resource terraform, terraform s3 bucket, terraform state rm, terraform state file, terraform security group, terraform split, terraform s3 backend, terraform scripts, terraform secrets manager, terraform snowflake, terraform stacks, s3 bucket terraform, security group terraform, storage account terraform, snowflake terraform, sqs terraform, split terraform, state file in terraform, s3 backend terraform, secrets manager terraform, substring terraform, terraform tutorial, terraform templatefile, terraform try, terraform taint, terraform test, terraform toset, terraform training, terraform tfvars, terraform ternary, terraform target, toset terraform, templatefile terraform, try terraform, tfvars terraform, taint terraform, terraform terraform_data, test terraform, tutorial terraform, terraform terraform-aws-modules/eks/aws, terraform terraform-aws-modules/vpc/aws, terraform upgrade, terraform unlock, terraform untaint, terraform unit testing, terraform update provider, terraform ui, terraform user_data, terraform uppercase, terraform update state, ubuntu install terraform, unsupported terraform core version, upgrade terraform, upgrade terraform version, udemy terraform, uninstall terraform, unlock terraform state, user_data terraform, use of terraform, unit testing terraform, terraform versions, terraform variables, terraform variable types, terraform vs cloudformation, terraform validate, terraform vault provider, terraform vpc module, terraform vpc, terraform vs kubernetes, vpc module terraform, variables in terraform, vpc terraform, vpc endpoint terraform, vault terraform, vmware terraform, variable types terraform, validation terraform, variable map terraform, variable list terraform, terraform workspaces, terraform windows, terraform wiki, terraform workflow, terraform windows install, terraform waf, terraform workspace select, terraform what is it, terraform will damage your computer, terraform wait for resource, what is terraform cloud, what is terraform module, what is terraform in aws, what is terraform backend, what is locals in terraform, what is terraform init, what is terraform import, what is terraform in azure, what are terraform providers, what is output in terraform, terraform xcp-ng, terraform x509 certificate, terraform xen orchestra, terraform xor, terraform xray, terraform x-amazon-apigateway-integration, terraform xml, terraform xml encode, terraform x86_64, terraform xray provider, xcp-ng terraform, x-amazon-apigateway-integration terraform, x-men terraform mars, x4 how to terraform, xray terraform, xen orchestra terraform, xor terraform, xray terraform provider, xsoar terraform, xmatters terraform, terraform yaml, terraform yamldecode, terraform yamlencode, terraform yugioh, terraform youtube, terraform yaml template, terraform yamldecode from file, terraform yaml example, terraform yaml file, terraform yaml variables, yum install terraform, yamldecode terraform, yamlencode terraform, youtube terraform, yaml to terraform, yaml vs terraform, yaml to terraform converter, yamldecode terraform example, yeoman terraform, yum install terraform specific version, terraform zipmap, terraform zero pokemon, terraform zip file, terraform zscaler, terraform zero to hero, terraform zabbix, terraform zip lambda, terraform zip multiple files, terraform zpa, terraform zsh completion, zsh command not found terraform, zipmap terraform, zscaler terraform, zeal vora terraform, zsh killed terraform, zsh exec format error terraform, zeal vora terraform github, zscaler terraform provider, zabbix terraform, zsh terraform plugin, terraform 0.13 upgrade process, terraform 0.13, terraform 0.12, terraform 0.14, terraform 0.12.31, terraform 0.13.7, terraform 0.15, terraform 003, terraform 0.11, terraform 0.13.5, 0 1 terraform, 0.14.11 terraform, 0 in terraform, 0.13.7 terraform, 0.12.31 terraform, 0.11.15 terraform, 0.13.5 terraform, 02d terraform, count = 0 in terraform, gta 0.7 by terraform, terraform 1.7, terraform 101, terraform 1.6, terraform 1.5.7, terraform 1.5, terraform 1password, terraform 1.5.5, terraform 1.5.7 download, terraform 1.7 changelog, 1password terraform, 1 0 terraform, 1password terraform provider, 1password cli terraform, 1 0 meaning in terraform, 1.5.7 terraform, 1.4.6 terraform, 1password terraform plugin, 100 days of terraform, 1.5.0 terraform, terraform 2.0, terraform 2024, terraform 2 for_each, terraform 2 providers, terraform 2 tier architecture, terraform 2 conditions, terraform 250 questions, terraform 2 or 4 spaces, terraform 2023, 250 terraform questions, 2 for_each terraform, 20 terraform best practices, 2d array terraform, prelude 2 terraforming mars, is tuple with 2 elements terraform, endless space 2 terraforming, fs 22 terraform mod, ubuntu 22.04 install terraform, cities skylines 2 terraforming, terraform 386 vs amd64, terraform 3 tier application aws, terraform 3 dots, terraform 3 tier architecture, terraform 3 tier application aws github, terraform 3d, terraform 3 commands, terraform 3 planets with azaryn, terraform 3 conditions, 3 tier architecture aws terraform, 386 vs amd64 terraform, 3 tier architecture azure terraform, 3 musketeers terraform, 3 dots terraform, is tuple with 3 elements terraform, exit code 3 terraform, microsoft 365 terraform, jak 3 terraformer, age of wonders 3 terraforming, terraform 409 conflict, terraform 400 parameter verification failed, terraform 401 unauthorized, terraform 403 forbidden, terraform 403 access denied, terraform 4 stages, terraform 401, terraform 422 unprocessable entity, terraform 4.0, terraform 409, 401 unauthorized terraform init, 401 unauthorized terraform, 403 error terraform, 403 error terraform init, 400 error in terraform, 409 terraform, 4 terraform commands, age of wonders 4 terraforming, status code 400 terraform, simcity 4 terraformer, terraform 5 commands, terraform 500 internal server error, terraform 5.0, terraform 503 service unavailable, terraform 502 bad gateway, terraform 500 error, terraform 502, terraform 55, terraform 5 minutes, 5 terraforming mars, route 53 terraform, route 53 terraform module, simple terraform example, terraform list of numbers, 5 terra, terraform in 5 minutes, terraform 64 bit download, terraform 64bit, terraform base64, terraform protocol 6, terraform windows 64bit, terraform encode 64, terraform install windows 64 bit, terraform for windows 64 bit, terraform lambda .net 6, download terraform for windows 64-bit, tropico 6 terraforming, civ 6 terraforming, is tuple with 6 elements terraform, tropico 6 terraformer achievement, dominions 6 terraforming, civ 6 terraforming mod, terraform 706, terraform centos 7, terraform .net 7, terraform rhel 7, terraform elasticache redis 7, terraform for windows 7, rapid7 terraform, terraform elasticache version 7, terraform 1 5 7, terraform aws redis 7, examtopics terraform associate question 70, examtopics terraform associate question 76, examtopics terraform associate question 78, examtopics terraform associate question 72, examtopics terraform associate question 73, examtopics terraform associate question 77, examtopics terraform associate question 74, examtopics terraform associate question 75, examtopics terraform associate question 71, install terraform on rhel 7.9, terraform proxmox 8, terraform centos 8, terraform dotnet 8, terraform .net 8, terraform vsphere 8, terraform iso 8601, terraform utf-8, terraform rhel 8, terraform nist 800-53, terraform vra 8, terraform-aws-modules/security-group/aws//modules/http-80, terraform alb redirect 80 to 443, rhel 8 install terraform, vra 8 terraform integration, iso 8601 terraform, cisco 8000v terraform, vra 8 terraform, perimeter 81 terraform, centos 8 install terraform, rhel 8 terraform, terraform killed 9, terraform cloud 9, terraform rhel 9, terraform killed 9 mac, terraform issue 953, terraform install centos 9, terraform mac killed 9, terraform 91, terra 9mm, terraform 0.12.9, cloud 9 terraform, killed 9 terraform, aws cloud9 terraform, cloud 9 install terraform, rocky 9 install terraform, rocky linux 9 terraform, rhel 9 install terraform, install terraform rocky linux 9, install terraform centos 9
Previous Post Next Post