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
あなたが遭遇している問題は、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}"]
}
参照