使用terraform创建vpc,分成4个subnet,每个可用区2个subnet。其中1个可用区是可以访问外网的,其中1个可用区是不能访问外网的。
时间: 2024-05-10 15:17:11 浏览: 138
可以使用以下Terraform代码来创建VPC和4个子网,其中2个子网位于可用区a,2个子网位于可用区b。其中一个子网(subnet-1)允许公共访问,另一个子网(subnet-2)不允许公共访问。
```terraform
# 定义VPC
resource "aws_vpc" "my_vpc" {
cidr_block = "10.0.0.0/16"
}
# 定义Internet网关
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.my_vpc.id
}
# 定义路由表
resource "aws_route_table" "public_route_table" {
vpc_id = aws_vpc.my_vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.gw.id
}
}
resource "aws_route_table" "private_route_table" {
vpc_id = aws_vpc.my_vpc.id
}
# 定义子网
resource "aws_subnet" "subnet_a1" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
map_public_ip_on_launch = true
tags = {
Name = "subnet-1"
}
route_table_id = aws_route_table.public_route_table.id
}
resource "aws_subnet" "subnet_a2" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.2.0/24"
availability_zone = "us-east-1a"
map_public_ip_on_launch = false
tags = {
Name = "subnet-2"
}
route_table_id = aws_route_table.private_route_table.id
}
resource "aws_subnet" "subnet_b1" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.3.0/24"
availability_zone = "us-east-1b"
map_public_ip_on_launch = true
tags = {
Name = "subnet-3"
}
route_table_id = aws_route_table.public_route_table.id
}
resource "aws_subnet" "subnet_b2" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.4.0/24"
availability_zone = "us-east-1b"
map_public_ip_on_launch = false
tags = {
Name = "subnet-4"
}
route_table_id = aws_route_table.private_route_table.id
}
```
在上面的代码中,我们首先定义了一个VPC和一个Internet网关。然后,我们定义了两个路由表,一个用于公共子网,另一个用于私有子网。接下来,我们定义了四个子网,其中两个子网(subnet_a1和subnet_b1)允许公共访问,另外两个子网(subnet_a2和subnet_b2)不允许公共访问。我们使用了map_public_ip_on_launch参数来控制是否为实例分配公共IP地址。我们还使用了route_table_id参数来分配路由表。在这里,公共子网使用public_route_table,私有子网使用private_route_table。
阅读全文