Terraform:从对象列表中检索值

Posted

技术标签:

【中文标题】Terraform:从对象列表中检索值【英文标题】:Terraform: retrieving a value from a list of objects 【发布时间】:2021-09-20 00:22:42 【问题描述】:

星期五快乐,

使用以下数据集(从输出中查看)如何获取 CIDR 块列表以输入“aws_security_group”资源的“cidr_blocks”(列表)属性?

Changes to Outputs:
  + subnet_ids = 
      + subnet-<id_hidden> = 
          + arn                             = "<arn_hidden>"
          + assign_ipv6_address_on_creation = false
          + availability_zone               = "<az_hidden>"
          + availability_zone_id            = "<az_id_hidden>"
          + available_ip_address_count      = 1000
          + cidr_block                      = "<cidr_hidden>"    <== Want this
          + customer_owned_ipv4_pool        = ""
          + default_for_az                  = false
          + filter                          = null
          + id                              = "<id_hidden>"
          + ipv6_cidr_block                 = null
          + ipv6_cidr_block_association_id  = null
          + map_customer_owned_ip_on_launch = false
          + map_public_ip_on_launch         = false
          + outpost_arn                     = ""
          + owner_id                        = "<owner_hidden>"
          + state                           = "available"
          + tags                            = 
              + "Environment" = "dev"
            
          + vpc_id                          = "<id_hidden>"
        
      + subnet-<id_hidden> = 
            ...
            + cidr_block                      = "<cidr_hidden>"    <== Want this
            ...   
        ...many more subnets...

编辑(代码块生成输出):

data "aws_subnet" "management_vpc_private_subnets" 
  for_each = data.aws_subnet_ids.management_vpc_private_subnet_ids.ids
  id       = each.value


data "aws_subnet_ids" "management_vpc_private_subnet_ids" 
  vpc_id = <vpc_id_hidden>

  filter 
    name   = "tag:Subnet"
    values = ["private"]
  


output "subnet_ids" 
  value = data.aws_subnet.management_vpc_private_subnets

谢谢!

【问题讨论】:

您介意发布生成此输出的代码块吗? 添加了块。谢谢。 【参考方案1】:

Terraform 文档中讨论了这个确切的例子。

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/subnet_ids#example-usage

你应该可以做这样的事情。

data "aws_subnet_ids" "example" 
  vpc_id = <vpc_id_hidden>

  filter 
    name   = "tag:Subnet"
    values = ["private"]
  


data "aws_subnet" "example" 
  for_each = data.aws_subnet_ids.example.ids
  id       = each.value


output "subnet_cidr_blocks" 
  value = [for s in data.aws_subnet.example : s.cidr_block]

结果输出如下

subnet_cidr_blocks = [
  "10.0.8.0/21",
  "10.0.136.0/21",
  "10.0.72.0/21",
  "10.0.104.0/21",
  "10.0.40.0/21",
]

【讨论】:

以上是关于Terraform:从对象列表中检索值的主要内容,如果未能解决你的问题,请参考以下文章

使用 Terraform 删除以前的快照并创建 EBS 卷的新快照

Terraform:如何从对象列表创建 API 网关端点和方法?

如何在Ansible set_fact中使用fact?

使用 github-script@v5 操作提取 terraform 资源更改

Terraform 是不是支持带有少量操作的 CloudFormation 模板

需要说明如何使用 Terraform 管理 Google Cloud 项目