如何将对象列表转换为简单列表,从对象列表中选择单个属性?

How to convert a list of objects into a simple list, selecting a single attribute from the list of objects?

假设我们有这个:

whitelist = [
  { 
     cidr = "10.0.0.0/8",
     desc = "customer1"
  },
  {
     cidr = "10.1.0.0/8",
     desc = "customer2"
  },...
]

如何制作一个简单的列表 whitelist_cidrs 即:

whitelist_cidrs = [ "10.0.0.0/8", "0.1.0.0/8",...]

如何将对象列表转换为简单的字符串列表?

for expression 可能是您正在寻找的:

locals {
  whitelist = [
    {
      cidr = "10.0.0.0/8",
      desc = "customer1"
    },
    {
      cidr = "10.1.0.0/8",
      desc = "customer2"
    }
  ]
}

output "whitelist_cidrs" {
  value = [for p in local.whitelist : p.cidr]
}

输出:

Changes to Outputs:
  + whitelist_cidrs = [
      + "10.0.0.0/8",
      + "10.1.0.0/8",
    ]