【问题标题】:How to filter aws subnets in terraform如何在 terraform 中过滤 aws 子网
【发布时间】:2021-11-28 14:05:54
【问题描述】:

我正在将定制的部署基础架构移植到 terraform。在该自定义代码库中,有一些内容表明 - 从默认区域 vpc 获取所有可用子网,但仅获取那些具有 20 个或更多可用 IPv4 地址的子网。

所以我正在试验这段代码

data "aws_vpc" "main" {
  default = true
}

data "aws_subnets" "vpcsubnets" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.main.id]
  }
  filter {
    name   = "default-for-az"
    values = [true]
  }
  filter {
    name   = "state"
    values = ["available"]
  }
}

output "ids2" {
  value = {
    for k, v in data.aws_subnets.vpcsubnets : k => v if v.available_ip_address_count > 20
  }
}

但是我遇到了这样的错误

 Error: Invalid reference
│ 
│   on main.tf line 51, in output "ids2":
│   51:     for k, vid in data.aws_subnets.vpcsubnets : k => v if v.available_ip_address_count > 20
│ 
│ A reference to a resource type must be followed by at least one attribute access, specifying the resource name.

使用 Terraform 1.0.8 和 aws provider 3.62

【问题讨论】:

    标签: terraform terraform-provider-aws


    【解决方案1】:

    您需要一个额外的中间步骤。可用子网的完整列表在属性 data.aws_subnets.vpcsubnets.ids 中可用,但属性 available_ip_address_count 将仅在 aws_subnet 数据中可用。您需要为中间数据中的每个可用子网检索该信息:

    data "aws_subnet" "vpcsubnet" {
      for_each = toset(data.aws_subnets.vpcsubnets.ids)
    
      id = each.value
    }
    

    现在该属性在命名空间data.aws_subnet.vpcsubnet["<id>"].available_ip_address_count 中可用。为此,您可以轻松地对您的 output 进行小幅更新:

    output "ids2" {
      value = {
        for id, attributes in data.aws_subnet.vpcsubnet : id => attributes if attributes.available_ip_address_count > 20
      }
    }
    

    为了清楚起见,我还重命名了临时 lambda 变量。

    【讨论】:

    • 这不适用于 AWS 提供商,因为 ids 是列表,而 for_each 可用于 map 或 set,但它确实帮助我实现了完整的工作示例。
    • @DarkoMiletic 我确实忘记了类型转换。稍微更新了答案,现在它可以工作了。
    【解决方案2】:

    这行得通

    data "aws_vpc" "main" {
      default = true
    }
    
    data "aws_subnets" "vpcsubnets" {
      filter {
        name   = "vpc-id"
        values = [data.aws_vpc.main.id]
      }
      filter {
        name   = "default-for-az"
        values = [true]
      }
      filter {
        name   = "state"
        values = ["available"]
      }
    }
    
    data "aws_subnet" "vpcsubnet" {
      for_each = { for index, subnetid in data.aws_subnets.vpcsubnets.ids : index => subnetid }
      id       = each.value
    }
    
    output "ids2" {
      value = [
        for v in data.aws_subnet.vpcsubnet : v if v.available_ip_address_count > 20
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-26
      • 2019-11-27
      • 2022-01-17
      • 1970-01-01
      • 2023-04-06
      • 2020-10-25
      • 1970-01-01
      • 2021-03-14
      相关资源
      最近更新 更多