首页 > 解决方案 > Terraform:在应用之前无法确定数据源上的长度()?

问题描述

我试图通过aws_nat_gateway数据源检索公共子网列表来动态声明多个数据aws_subnet_ids源。但是,当我尝试将count参数设置为等于子网 ID 的长度时,我收到一条错误消息The "count" value depends on resource attributes that cannot be determined until apply...

这几乎与他们文档中的示例直接矛盾!我该如何解决?他们的文件有问题吗?

我正在使用 Terraform v0.12。

data "aws_vpc" "environment_vpc" {
  id = var.vpc_id
}

data "aws_subnet_ids" "public_subnet_ids" {
  vpc_id = data.aws_vpc.environment_vpc.id
  tags = {
    Tier = "public"
  }
  depends_on = [data.aws_vpc.environment_vpc]
}

data "aws_nat_gateway" "nat_gateway" {
  count      = length(data.aws_subnet_ids.public_subnet_ids.ids)  # <= Error
  subnet_id  = data.aws_subnet_ids.public_subnet_ids.ids.*[count.index]
  depends_on = [data.aws_subnet_ids.public_subnet_ids]
}

我希望能够成功应用此模板,但出现以下错误:

Error: Invalid count argument

  on ../src/variables.tf line 78, in data "aws_nat_gateway" "nat_gateway":
  78:   count      = "${length(data.aws_subnet_ids.public_subnet_ids.ids)}"

The "count" value depends on resource attributes that cannot be determined
until apply, so Terraform cannot predict how many instances will be created.
To work around this, use the -target argument to first apply only the
resources that the count depends on.

标签: amazon-web-servicesterraform

解决方案


您似乎正在尝试获取尚未创建或无法确定的子网,terraform cmd 输出建议您添加 -target 标志以创建 VPC 和子网或先执行其他任务,之后,您将应用 nat_gateway 资源。我建议你使用 AZs 列表而不是子网 id,我将在下面添加一个简单的示例。

variable "vpc_azs_list" {
  default = [
    "us-east-1d",
    "us-east-1e"
  ]
}

resource "aws_nat_gateway" "nat" {
  count         = var.enable_nat_gateways ? length(var.azs_list) : 0
  allocation_id = "xxxxxxxxx"
  subnet_id     = "xxxxxxxxx"
  depends_on = [
    aws_internet_gateway.main,
    aws_eip.nat_eip,
  ]
  tags = {
    "Name"       = "nat-gateway-name"
    "costCenter" = "xxxxxxxxx"
    "owner"      = "xxxxxxxxx"
  }
}

我希望对您和其他用户有用。


推荐阅读