使用 hashicorp/aws v5.40.0 和 Terraform >= 1.7.4
我仍然是一个新手,试图通过更多的动态部署来扩展如何使用 Terraform。在这种情况下,使用子网进行部署很重要。
使用 var.subnetcount 创建公有子网,如下所示:
`resource "aws_subnet" "public" {
count = var.subnet_count # in order to use the count index, we need to declare that we are using the answer to the question about how many subnets are to be created
availability_zone = element(data.aws_availability_zones.azs.names, count.index)
map_public_ip_on_launch = true
vpc_id = aws_vpc.my-vpc.id
cidr_block = "10.1.${count.index}.0/24"
}`
我正在尝试将资源放入每个子网中,如下所示:
`resource "aws_instance" "EC2" {
ami = data.aws_ami.amazon_linux.id
instance_type = var.instance_type
key_name = var.key
for_each = toset(data.aws_subnets.public.ids)
subnet_id = "each.value.id"
vpc_security_group_ids = [aws_security_group.ssh.id]
}`
但是我在尝试申请时遇到以下错误
│ Error: creating EC2 Instance: InvalidSubnetID.NotFound: The subnet ID 'each.value.id' does not exist │ status code: 400, request id: c6cd6da1-1ce2-4502-b9ac-3f49b45c93bc │ │ with aws_instance.EC2["**subnet-04b3859df1d5ea4ca"**], │ on Test_EC2.tf line 12, in resource "aws_instance" "EC2": │ 12: resource "aws_instance" "EC2" {
我期望为每个子网创建一个 EC2 实例,并且使用“for_each”子网 ID 就可以了。
希望有更好的方法吗?
错误似乎发生是因为您将
.id
添加到 each.value
,这是不需要的。您可以直接在您的 each.value
资源中使用 aws_instance
,如下所示:
subnet_id = each.value