To create public and private subnets in Terraform, you can use the AWS provider to define your network configuration. Here’s an example configuration that demonstrates how to create public and private subnets within a Virtual Private Cloud (VPC) in AWS:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Define your AWS provider configuration
provider "aws" {
  region = "us-west-2"  # Update with your desired region
}

# Create the VPC
resource "aws_vpc" "my_vpc" {
  cidr_block = "10.0.0.0/16"  # Update with your desired VPC CIDR block

  tags = {
    Name = "my-vpc"
  }
}

# Create the public subnet
resource "aws_subnet" "public_subnet" {
  vpc_id            = aws_vpc.my_vpc.id
  cidr_block        = "10.0.0.0/24"  # Update with your desired public subnet CIDR block
  availability_zone = "us-west-2a"  # Update with your desired availability zone

  tags = {
    Name = "public-subnet"
  }
}

# Create the private subnet
resource "aws_subnet" "private_subnet" {
  vpc_id            = aws_vpc.my_vpc.id
  cidr_block        = "10.0.1.0/24"  # Update with your desired private subnet CIDR block
  availability_zone = "us-west-2b"  # Update with your desired availability zone

  tags = {
    Name = "private-subnet"
  }
}

In this example, the aws_vpc resource creates a VPC with the specified CIDR block. The aws_subnet resources create the public and private subnets within the VPC, using different CIDR blocks and availability zones.

Make sure you have the AWS CLI configured with appropriate credentials and the required permissions for creating VPCs and subnets. You can then run the Terraform commands (terraform init, terraform plan, and terraform apply) in the directory where you have saved your Terraform configuration files to create the infrastructure.

This example assumes you have already initialized Terraform with the AWS provider and have the necessary plugins installed.