In this guide, we’ll walk you through the process of using Terraform to establish an AWS VPC. This is what you’ll require,
Terraform installed and configured on your local machine
An AWS account
A code editor like VS Code
Step 1: Set Up the Terraform Provider
Create “providers.tf ” file with the following content to specify the AWS provider
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
provider "aws" {
region = "us-west-2"
shared_credentials_files = "~/.aws/credentials"
profile = "ica"
}
erraform block: lists the providers needed to complete this configuration. Here, we specify that the AWS provider — which comes from HashiCorp’s registry — is required.
provider “aws” block: Configures the AWS provider
region: Specifies the AWS region to create the resources
shared_credentials_files: Specifies the path to the AWS credentials file
profile: Specifies the profile name from the credentials file to use.(AWS IAM user)
Step 2: Define the AWS VPC
Create a main.tf file to define the AWS VPC resource
resource "aws_vpc" "infa_terraf_vpc" {
cidr_block = "10.126.0.0/16"
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "main"
}
}
This defines a VPC with the specified CIDR block and enables DNS hostnames and support.
cidr_block: The IP range for the VPC in CIDR notation
nable_dns_hostnames: When set to true, this enables instances within the VPC to have public DNS hostnames. This is useful for accessing instances over the internet.
enable_dns_support: When set to true, this enables DNS resolution within the VPC. This allows you to resolve internal domain names to their IP addresses.
tags: A map of key-value pairs used to tag the resource. Tags are useful for organizing and identifying resources
Step 3: Plan and Apply the Configuration
Preview the changes that Terraform will make by running
terraform plan
This command shows a summary of the actions Terraform will perform, such as creating the VPC.
Generates an execution plan, showing what actions Terraform will take to reach the desired state. This helps you verify the changes before applying them
Apply the configuration to create the VPC in AWS
terraform apply
Applies the changes required to reach the desired state of the configuration. It prompts for confirmation and then creates the resources in AWS
Step 4: Verify the VPC
Go to the AWS Management Console and navigate to the VPC section. So we can see the new VPC that was just created.
In summary
Using Terraform to create an AWS VPC is a strong method of managing cloud infrastructure. You may achieve consistency, scalability, and ease of maintenance by specifying your setup in code. Don’t forget to test changes thoroughly, adhere to best practices, and structure your code. Terraform is an essential tool for any cloud engineer since it allows you to automate and maintain your infrastructure effectively.