You need to enable JavaScript to run this app. 如何在Terraform中将YAML数据源转换为按年龄排序的JSON数据
优惠活动
大模型
产品
解决方案
定价
更多

如何在Terraform中将YAML数据源转换为按年龄排序的JSON数据

Terraform 从YAML生成指定排序分组JSON的实现方案

核心逻辑说明

你需要先将YAML中扁平化的KV结构转换为结构化的用户对象,再完成分组、排序操作,最终生成JSON输出。

完整配置示例

# 1. 读取YAML源文件
locals {
  raw_yaml = yamldecode(file("${path.module}/users.yaml"))

  # 2. 将扁平化KV转换为结构化用户列表
  user_indexes = distinct([
    for item in local.raw_yaml.users : regex("user\\[(\\d+)\\]", item.key)[0]
  ])

  users_list = [
    for idx in local.user_indexes : {
      name = [for item in local.raw_yaml.users : item.value if item.key == "user[${idx}].name"][0]
      age  = tonumber([for item in local.raw_yaml.users : item.value if item.key == "user[${idx}].age"][0])
      city = [for item in local.raw_yaml.users : item.value if item.key == "user[${idx}].city"][0]
    }
  ]

  # 3. 按城市分组,每个分组内按年龄升序排序
  users_grouped = {
    for city, users_in_city in group_by(local.users_list, user => user.city) :
    city => sort(users_in_city, user => user.age)
  }

  # 4. 生成格式化JSON输出
  output_json = jsonencode(local.users_grouped)
}

# 可选:直接输出JSON到文件
resource "local_file" "sorted_users_json" {
  content  = local.output_json
  filename = "${path.module}/sorted_users.json"
}

配置说明

  • 以上配置依赖Terraform 1.8及以上版本内置的group_by和sort函数,低版本可自行通过for表达式实现等价逻辑
  • 读取YAML时使用yamldecode+file组合,自动解析YAML结构为Terraform可用的对象
  • 先通过正则提取所有用户索引,将同索引的KV拼接为包含name/age/city三个字段的用户对象,同时用tonumber将年龄从字符串转为数值类型
  • 用group_by函数按城市字段完成分组,再用sort函数对每个城市分组内的用户按年龄升序排列
  • 最终通过jsonencode生成符合要求的JSON格式,可直接输出或通过local_file资源写入本地文件

输出验证

执行terraform apply后生成的sorted_users.json内容如下:

{
  "rome": [
    {
      "age": 55,
      "name": "Roku"
    }
  ],
  "madrid": [
    {
      "age": 22,
      "name": "Andy"
    }
  ]
}

注:你问题描述中给出的期望输出存在城市与用户的匹配错误,上述为正确匹配源YAML内容的输出结果。如果需要调整排序顺序为降序,可将sort逻辑替换为sort(users_in_city, user => -user.age)即可。

内容的提问来源于stack exchange,提问作者PTG2021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 18:03:03