我有创建VPC的代码,它具有2个私有子网,私有2xec2实例,公共堡垒。
ec2代码使用VPC模块subnet_ids的output.tf。由于有2个私有子网,因此将生成2个subnet_id。当将这些生成的subnet_id而不是一个subnet_id馈入ec2实例时,它一次将2个subnet_id作为单个值馈入。
由于地形无法找到subnet_ids值,因此创建失败。
错误: 子网ID'subnet-0 ***********,subnet-0 *************'不存在
编辑子网* vpc.tf
private_subnets = "10.10.20.#/#,10.10.20.#/#"
instanceec2.tf
subnet_id = "${module.vpc.private_subnets}"
以下是模块:
vpc_main.tf
// Private subnet/s
resource "aws_subnet" "private" {
vpc_id = "${aws_vpc.vpc.id}"
cidr_block = "${element(split(",", var.private_subnets), count.index)}"
availability_zone = "${element(split(",", var.azs), count.index)}"
count = "${length(split(",", var.private_subnets))}"
tags {
Name = "${var.name}-private-${element(split(",", var.azs), count.index)}"
Team = "${var.team}"
Environment = "${var.environment}"
Service = "${var.service}"
Product = "${var.product}"
Owner = "${var.owner}"
Description = "${var.description}"
managed_by = "terraform"
}
}
resource "aws_route_table" "private" {
vpc_id = "${aws_vpc.vpc.id}"
count = "${length(split(",", var.private_subnets))}"
tags {
Name = "${var.name}-private-${element(split(",", var.azs), count.index)}"
Team = "${var.team}"
Environment = "${var.environment}"
Service = "${var.service}"
Product = "${var.product}"
Owner = "${var.owner}"
Description = "${var.description}"
managed_by = "terraform"
}
}
resource "aws_route_table_association" "private" {
subnet_id = "${element(aws_subnet.private.*.id, count.index)}"
route_table_id = "${element(aws_route_table.private.*.id, count.index)}"
count = "${length(split(",", var.private_subnets))}"
}
``````
vpc_outputs.tf
```````
output "private_subnets" {
value = "${join(",", aws_subnet.private.*.id)}"
}
预期值只是一个子网ID作为值:
错误:提供2个子网ID作为一个值。
aws_instance.ec2-instance [0]:发生1个错误:
答案 0 :(得分:0)
由于您已经“加入”了结果,因此如果您只需要一个子网值,就必须再次拆分。 像这样:
element(split(",", var.private_subnets), 0)
答案 1 :(得分:0)
您要在输出变量中加入子网ID:
output "private_subnets" {
value = "${join(",", aws_subnet.private.*.id)}"
}
当您从instanceec2.tf
访问此输出值时,您将仅收到此ID字符串。
因此,您必须像以前一样再次滑动接收的值,并使用ec2资源的计数索引访问各自的ID:
resource "aws_instance" "default" {
count = "${length(split(",", module.vpc.private_subnets))}"
subnet_id = "${element(split(",", module.vpc.private_subnets), count.index)}"
....
}
那应该可以解决您的问题。
或者,您也可以将子网ID直接作为列表输出:
output "private_subnets" {
description = "The IDs of the private subnets as list"
value = ["${aws_subnet.private.*.id}"]
}
,然后通过以下方式访问它们:
subnet_id = "${element(module.vpc.private_subnets, count.index)}"