Create a virtual private cloud (VPC) and subnets in AWS using Terraform.
How to create a virtual private cloud (VPC) and subnets in AWS using Terraform. Here are the steps:
- Set up AWS credentials on your local machine, either by using the AWS CLI or by setting environment variables.
- Create a new directory for your Terraform configuration files, and create a new file named “main.tf” inside that directory.
- Inside “main.tf”, define the provider block for AWS, specifying the region and credentials to use:
provider "aws" {
region = "us-west-2"
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"
}
- Define a VPC resource block, specifying the CIDR block for the VPC:
resource "aws_vpc" "my_vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "my_vpc"
}
}
- Define one or more subnet resource blocks inside the VPC block, specifying the CIDR block for each subnet:
resource "aws_subnet" "public_subnet" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags = {
Name = "public_subnet"
}
}
- Repeat step 5 for each additional subnet you want to create.
- Save the “main.tf” file and run
terraform init
to download the necessary provider plugins. - Run
terraform plan
to see the changes that Terraform will make to your AWS infrastructure. - If the plan looks correct, run
terraform apply
to create the VPC and subnets in AWS. - Verify that the VPC and subnets were created correctly in the AWS console.
That’s it! You have now created a VPC and subnets in AWS using Terraform.