Terraform:在另一个模块中使用一个模块的输出

Terraform: use output of one module in another module

我有一个名为 vpc 的模块和另一个名为 ecs 的模块。我正在尝试引用在 ecs 的 vpc 模块中创建的 AWS 子网。到目前为止,这是我所拥有的:

main.tf

module "ecs" {
  source = "./service/ecs"
  public_subnet_ids = module.vpc.ecs-public-subnet.ids
}

vpc.tf

resource "aws_subnet" "public-subnet-1" {
...
}
resource "aws_subnet" "public-subnet-2" {
...
}
output "ecs-public-subnet" {
  value = [
    aws_subnet.public-subnet-1.id,
    aws_subnet.public-subnet-2.id
}

ecs.tf

variable "public_subnet_ids" {
  type = list(string)
  description = "public subnets"
}

resource "aws_ecs_service" "foo" {
  name = "foo"
  ...
  network_configuration {
    ...
    subnets = ["${element(var.public_subnet_ids, count.index)}"]

当我执行计划时,我得到以下信息:

Error: Reference to "count" in non-counted context The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count" argument is set.

Terraform 版本 1.1.8, aws 提供商版本 4.10.0

如果有更好的方法,我很乐意改变整个方法。

count 用于当您使用旨在制作多个资源的块时。把它想象成一个循环的索引。您正在做的事情更简单、更容易。

首先,只需在模块定义中引用您的数组。 .ids 无效:

module "ecs" {
  source = "./service/ecs"
  public_subnet_ids = module.vpc.ecs-public-subnet
}

接下来,您可以在模块中引用同一个数组。您只是将数组分配给需要数组的字段:

resource "aws_ecs_service" "foo" {
  name = "foo"
  ...
  network_configuration {
    ...
    subnets = var.public_subnet_ids