Site icon Ninotronix

Create a virtual private cloud (VPC) and subnets in AWS using Terraform.

vpc-subnet-terraform

vpc-subnet-terraform

How to create a virtual private cloud (VPC) and subnets in AWS using Terraform. Here are the steps:

  1. Set up AWS credentials on your local machine, either by using the AWS CLI or by setting environment variables.
  2. Create a new directory for your Terraform configuration files, and create a new file named “main.tf” inside that directory.
  3. 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"
}
  1. 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"
  }
}
  1. 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"
  }
}
  1. Repeat step 5 for each additional subnet you want to create.
  2. Save the “main.tf” file and run terraform init to download the necessary provider plugins.
  3. Run terraform plan to see the changes that Terraform will make to your AWS infrastructure.
  4. If the plan looks correct, run terraform apply to create the VPC and subnets in AWS.
  5. 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.

Exit mobile version