2

我有创建 VPC 的代码,有 2 个私有子网、2xec2 私有实例和公共堡垒。

ec2 代码使用 VPC 模块 subnet_ids 的 outputs.tf。由于有 2 个私有子网,因此生成了 2 个子网 ID。当这些生成的子网 ID 被馈送到 ec2 实例而不是一个子网 ID 时,它一次将 2 个子网 ID 作为单个值提供。

结果 terraform 找不到该 subnet_ids 值,创建失败。

错误:子网 ID 'subnet-0*************,subnet-0*************' 不存在

编辑子网* vpc.tf

private_subnets     = "10.10.20.#/#,10.10.20.#/#"

实例ec2.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 个错误:

  • aws_instance.ec2-instance.0:启动源实例时出错:InvalidSubnetID.NotFound:子网 ID 'subnet-0**********,subnet-0***********'不存在
4

2 回答 2

1

您正在输出变量中加入子网 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)}"
于 2019-05-09T18:10:29.663 回答
0

由于您已“加入”结果,因此如果您只需要一个子网值,则必须再次拆分。就像是:

element(split(",", var.private_subnets), 0) 
于 2019-05-09T18:03:29.957 回答