如何根据参数对Terraform中的数据源进行排序

时间:2019-09-17 03:33:29

标签: sorting terraform alibaba-cloud

我使用以下Terraform代码获取可用数据库资源的列表:

data "alicloud_db_instance_classes" "resources" {
  instance_charge_type = "PostPaid"
  engine               = "PostgreSQL"
  engine_version       = "10.0"
  category = "HighAvailability"
  zone_id = "${data.alicloud_zones.rds_zones.ids.0}"
  multi_zone = true
  output_file = "./classes.txt"
}

输出文件如下:

[
    {
        "instance_class": "pg.x4.large.2",
        "storage_range": {
            "max": "500",
            "min": "250",
            "step": "250"
        },
        "zone_ids": [
            {
                "id": "cn-shanghai-MAZ1(b,c)",
                "sub_zone_ids": [
                    "cn-shanghai-b",
                    "cn-shanghai-c"
                ]
            }
        ]
    },
    {
        "instance_class": "pg.x8.medium.2",
        "storage_range": {
            "max": "250",
            "min": "250",
            "step": "0"
        },
        "zone_ids": [
            {
                "id": "cn-shanghai-MAZ1(b,c)",
                "sub_zone_ids": [
                    "cn-shanghai-b",
                    "cn-shanghai-c"
                ]
            }
        ]
    },
    {
        "instance_class": "rds.pg.c1.xlarge",
        "storage_range": {
            "max": "2000",
            "min": "5",
            "step": "5"
        },
        "zone_ids": [
            {
                "id": "cn-shanghai-MAZ1(b,c)",
                "sub_zone_ids": [
                    "cn-shanghai-b",
                    "cn-shanghai-c"
                ]
            }
        ]
    },
    {
        "instance_class": "rds.pg.s1.small",
        "storage_range": {
            "max": "2000",
            "min": "5",
            "step": "5"
        },
        "zone_ids": [
            {
                "id": "cn-shanghai-MAZ1(b,c)",
                "sub_zone_ids": [
                    "cn-shanghai-b",
                    "cn-shanghai-c"
                ]
            }
        ]
    }
]

我想买一个最便宜的。

一种方法是通过使用storage-range.min进行排序,但是如何基于'storage_range.min'对该列表进行排序?

或者我可以按“ instance_class”进行过滤,但是“ alicloud_db_instance_classes”似乎不喜欢过滤器,因为它说:错误:data.alicloud_db_instance_classes.resources ::无效或未知键:filter

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

sort()函数按字典顺序排序,您在这里没有简单的键。 您可以对类似(v0.12)这样的代码使用过滤功能

locals {
  best_db_instance_class_key = "rds.pg.s1.small"
  best_db_instance_class = element( alicloud_db_instance_classes.resources, index(alicloud_db_instance_classes.resources.*.instance_class, best_db_instance_class_key) )
}

(未经测试的代码)