代码之家  ›  专栏  ›  技术社区  ›  Neddy

用jq用lightmail解析awscli工具的json输出

  •  0
  • Neddy  · 技术社区  · 6 年前

    我正试图修改一个脚本来自动化lightsail快照,但修改jq查询时遇到了问题。

    我正在尝试分析 aws lightsail get-instance-snapshots

    这是脚本中的原始行:

    aws lightsail get-instance-snapshots | jq '.[] | sort_by(.createdAt) | select(.[0].fromInstanceName == "WordPress-Test-Instance") | .[].name'
    

    它返回快照名称列表,每行一个。

    我需要修改查询,以便它不会返回所有快照,而只返回名称以“autosnap”开头的快照。我在脚本旋转快照时这样做,但我不希望它删除我手动创建的快照(不会以“autosnap”开头)。

    以下是来自 aws lightsail获取实例快照

    {
        "instanceSnapshots": [
            {
                "location": {
                    "availabilityZone": "all",
                    "regionName": "*****"
                },
                "arn": "*****",
                "fromBlueprintId": "wordpress_4_9_2_1",
                "name": "autosnap-WordPress-Test-Instance-2018-04-16_01.46",
                "fromInstanceName": "WordPress-Test-Instance",
                "fromBundleId": "nano_1_2",
                "supportCode": "*****",
                "sizeInGb": 20,
                "createdAt": 1523843190.117,
                "fromAttachedDisks": [],
                "fromInstanceArn": "*****",
                "resourceType": "InstanceSnapshot",
                "state": "available"
            },
            {
                "location": {
                    "availabilityZone": "all",
                    "regionName": "*****"
                },
                "arn": "*****",
                "fromBlueprintId": "wordpress_4_9_2_1",
                "name": "Premanent-WordPress-Test-Instance-2018-04-16_01.40",
                "fromInstanceName": "WordPress-Test-Instance",
                "fromBundleId": "nano_1_2",
                "supportCode": "*****",
                "sizeInGb": 20,
                "createdAt": 1523842851.69,
                "fromAttachedDisks": [],
                "fromInstanceArn": "*****",
                "resourceType": "InstanceSnapshot",
                "state": "available"
            }
        ]
    }
    

    我本以为这样的事情会奏效,但经过多次尝试,我一点运气都没有。。。

    aws lightsail get-instance-snapshots | jq '.[] | sort_by(.createdAt) | select(.[0].fromInstanceName == "WordPress-Test-Instance") | select(.[0].name | test("autosnap")) |.[].name'
    

    任何帮助都将不胜感激!

    1 回复  |  直到 6 年前
        1
  •  0
  •   peak    6 年前

    进行您描述的选择的基本查询是:

    .instanceSnapshots | map(select(.name|startswith("autosnap")))
    

    (如果不需要保留数组结构,可以使用:

    .instanceSnapshots[] | select(.name|startswith("autosnap"))
    

    )

    然后,您可以通过扩展管道来执行其他过滤。

    如果你要用 test/1 ,相应的调用将是 test("^autosnap") 或者也许 test("^autosnap-")

    实例

    .instanceSnapshots
    | map(select(.name|startswith("autosnap")))
    | map(select(.fromInstanceName == "WordPress-Test-Instance"))
    | sort_by(.createdAt)
    | .[].name
    

    两个连续的 select s当然可以压缩成一个。为了提高效率,应尽可能晚地进行分拣。

    后记

    尽管您可能确实能够通过 .[] 而不是 .instanceSnapshots ,如果JSON模式发生更改,建议使用后者。从某种意义上说,JSON等数据格式的全部目的是使编写针对(sane)的健壮查询变得容易 schema-evolution