terraform -v
Terraform v0.12.23
+ provider.aws v2.53.0
我正在尝试创建 4 个实例并将它们放在 2 个不同的子网上
resource "aws_subnet" "private-subnet-1" {
vpc_id = aws_vpc.vpc.id
cidr_block = "10.150.2.0/24"
availability_zone = "us-west-2a"
tags = {
Name = "private-subnet-1"
}
}
resource "aws_subnet" "private-subnet-2" {
vpc_id = aws_vpc.vpc.id
cidr_block = "10.150.4.0/24"
availability_zone = "us-west-2b"
tags = {
Name = "private-subnet-2"
}
}
variable "subnet_ids" {
type = list(string)
default = ["aws_subnet.private-subnet-1.id","aws_subnet.private-subnet-2.id"]
}
resource "aws_instance" "web" {
count = 4
ami = "ami-0dc33a373d61e6ce0"
instance_type = "t2.micro"
key_name = "AF_KEY_PAIR"
subnet_id = element(var.subnet_ids, count.index)
vpc_security_group_ids = ["${aws_security_group.web-SG.id}"]
}
当我尝试申请时,出现了以下错误
Error: Error launching source instance: InvalidSubnetID.NotFound: The subnet ID 'aws_subnet.private-subnet-1.id' does not exist
status code: 400, request id: 17b46634-5319-4f78-9898-09142e9cb449
on test.tf line 175, in resource "aws_instance" "web":
175: resource "aws_instance" "web" {
Error: Error launching source instance: InvalidSubnetID.NotFound: The subnet ID 'aws_subnet.private-subnet-2.id' does not exist
status code: 400, request id: d092e6a6-d430-4a28-bd75-5af373c76ac7
on test.tf line 175, in resource "aws_instance" "web":
175: resource "aws_instance" "web" {
Error: Error launching source instance: InvalidSubnetID.NotFound: The subnet ID 'aws_subnet.private-subnet-1.id' does not exist
status code: 400, request id: ec672172-3bf7-4cbb-bce0-ae752c59393f
on test.tf line 175, in resource "aws_instance" "web":
175: resource "aws_instance" "web" {
Error: Error launching source instance: InvalidSubnetID.NotFound: The subnet ID 'aws_subnet.private-subnet-2.id' does not exist
status code: 400, request id: 4136f03c-1a5b-44ab-b0bf-a209134c08c9
on test.tf line 175, in resource "aws_instance" "web":
175: resource "aws_instance" "web" {
我尝试过改变
subnet_id = element(var.subnet_ids, count.index)
和
variable "subnet_ids" {
type = list(string)
default = [aws_subnet.AF-private-subnet-1.id,aws_subnet.AF-private-subnet-2.id]
}
我仍然收到同样的错误
当我手动创建 subnet_id 时它将起作用
subnet_id = aws_subnet.public-subnet-1.id
答案1
您遇到的问题是如何variable subnet_ids
解释您的列表。它没有将 ID 视为变量,而是将其解释为字符串。
我使用了locals
变量并且它的工作正如您预期的那样。
尝试对您的代码进行以下更改:
locals {
subs = concat([aws_subnet.private-subnet-1.id], [aws_subnet.private-subnet-2.id])
}
resource "aws_instance" "web" {
count = 4
ami = "ami-0dc33a373d61e6ce0"
instance_type = "t2.micro"
key_name = "AF_KEY_PAIR"
subnet_id = element(local.subs, count.index)
vpc_security_group_ids = ["${aws_security_group.web-SG.id}"]
}
参考