使用terraform v0.12.21和AWS提供程序v2.51.0,我试图从头开始创建一些基础结构(没有以前的terraform状态。
目标是在单个VPC中具有一些可公开访问的EC2实例,我认为这些是实现该目标所需的资源:
使用此terraform配置:
locals {
office_cidr = ["x.x.x.x/32", "x.x.x.x/32"]
}
provider "aws" {
region = var.region
version = "~> 2.51"
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
}
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.main.id
}
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
resource "aws_route_table" "r" {
vpc_id = aws_vpc.main.id
route {
cidr_block = aws_subnet.main.cidr_block
gateway_id = aws_internet_gateway.gw.id
}
}
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.main.id
route_table_id = aws_route_table.r.id
}
resource "aws_security_group" "allow_http" {
name = "security group"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = local.office_cidr
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = local.office_cidr
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = local.office_cidr
}
}
resource "aws_instance" "a" {
ami = "ami-xxxxxxxxxxxxxxxxx"
instance_type = "t2.micro"
vpc_security_group_ids = ["${aws_security_group.allow_http.id}"]
subnet_id = aws_subnet.main.id
associate_public_ip_address = true
}
resource "aws_instance" "b" {
ami = "ami-xxxxxxxxxxxxxxxxx"
instance_type = "t2.micro"
vpc_security_group_ids = ["${aws_security_group.allow_http.id}"]
subnet_id = aws_subnet.main.id
associate_public_ip_address = true
}
当我计划时,一切似乎都正常(这里仅显示计划输出的aws_route_table
部分:
# aws_route_table.r will be created
+ resource "aws_route_table" "r" {
+ id = (known after apply)
+ owner_id = (known after apply)
+ propagating_vgws = (known after apply)
+ route = [
+ {
+ cidr_block = "10.0.1.0/24"
+ egress_only_gateway_id = ""
+ gateway_id = (known after apply)
+ instance_id = ""
+ ipv6_cidr_block = ""
+ nat_gateway_id = ""
+ network_interface_id = ""
+ transit_gateway_id = ""
+ vpc_peering_connection_id = ""
},
]
+ vpc_id = (known after apply)
}
aws_subnet.main.cidr_block
中cidr_block
的route
输入插值到"10.0.1.0/24"
。
但是当我申请时出现此错误:
Error: Error creating route: InvalidParameterValue: Route target is not supported. This route only supports interface and instance targets.
status code: 400, request id: a303e768-69e2-4af0-88d4-e97ebcaeae5d
on main.tf line 38, in resource "aws_route_table" "r":
38: resource "aws_route_table" "r" {
“接口目标”是指网络接口吗?如果是这样,创建VPC时会自动创建一个网络接口,还是我也应该创建一个aws_network_interface
resource并将Internet网关连接到该接口?
[基本上,我想知道在子网中创建实例的最佳实践,这些实例需要具有公共IP地址并且可以公开访问,是否不需要我的任何资源,以及是否缺少通常会占用的资源。被包括在内。
但是出于这个问题的目的:我应该如何更改aws_route_table
资源块以及任何其他资源块,以解决此错误并使它可以使我的实例可以公开访问?
如果在路由中使用Internet网关gateway_id = aws_internet_gateway.gw.id,则此路由cidr_block必须为0.0.0.0/0,但不能为aws_subnet.main.cidr_block