【问题标题】:Is it possible to use select as an element in a jq list?是否可以将 select 用作​​ jq 列表中的元素?
【发布时间】:2020-09-22 17:05:33
【问题描述】:

我正在尝试使用 jq 从以下部分输出中解析实例 ID、状态、启动时间和名称:

{
  "AmiLaunchIndex": 0,
  "ImageId": "ami-07c1483ef8c3dfece",
  "InstanceId": "i-0309XXXXXf6d500c",
  "InstanceType": "m5.2xlarge",
  "KeyName": "k8s-prod-ap-southeast-1",
  "LaunchTime": "2019-01-27T12:23:55+00:00",
  "Monitoring": {
    "State": "enabled"
  },
  "Placement": {
    "AvailabilityZone": "ap-southeast-1c",
    "GroupName": "",
    "Tenancy": "default"
  },
  "PrivateDnsName": "ip-X-X-X-X.ap-southeast-1.compute.internal",
  "PrivateIpAddress": "X.X.X.X",
  "ProductCodes": [],
  "PublicDnsName": "",
  "State": {
    "Code": 16,
    "Name": "running"
  },
  "SourceDestCheck": true,
  "Tags": [
    {
      "Key": "Environment",
      "Value": "dev"
    },
    {
      "Key": "Project",
      "Value": "someproject"
    },
    {
      "Key": "Name",
      "Value": "k8s-prod-ap-southeast-1-mongodb"
    },
    {
      "Key": "aws:autoscaling:groupName",
      "Value": "k8s-prod-ap-southeast-1-mongodb-moved-marmoset-20190127122348196400000006"
    },
    {
      "Key": "extra_tag1",
      "Value": "extra_value1"
    },
    {
      "Key": "extra_tag2",
      "Value": "extra_value2"
    }
  ],
  .
  .
  .
}

如果没有以标签 (.Tags[].Name) 表示的实例名称,则运行此:

aws ec2 describe-instances --filters "Name=instance.group-id,Values=${group_id}" --profile ${profile} --region ${region} --output json | jq -r '.Reservations[].Instances[] | [ .InstanceId, .State.Name, .LaunchTime ] | @tsv'

产生以下输出:

i-01eb8b857e00e61d6 running 2019-01-27T12:23:55+00:00
i-0b013248c2a238598 running 2019-01-27T12:23:55+00:00
i-03094d164ff6d500c running 2019-01-27T12:23:55+00:00

但是当我尝试同时显示实例名称时,命令失败:

✗ aws ec2 describe-instances --filters "Name=instance.group-id,Values=${group_id}" --profile ${profile} --region ${region} --output json | jq -r '.Reservations[].Instances[] | [ .InstanceId, .State.Name, .LaunchTime, select(.Tags[].Key=="Name" | .Value) ] | @tsv'
jq: error (at <stdin>:448): Cannot index boolean with string "Value"

我做错了什么?

【问题讨论】:

    标签: json amazon-web-services select jq aws-cli


    【解决方案1】:

    我做错了什么?

    您对select 的使用不太正确。相反,您似乎想要:

    [ .InstanceId, 
      .State.Name,
      .LaunchTime, 
      (.Tags[] | select(.Key=="Name").Value) ] 
    | @tsv
    

    【讨论】:

    • 感谢您的回答,我已编辑我的问题以向您显示命令的输出。
    • 是的,我写错了 :-) 已修复。
    【解决方案2】:

    无需使用 jq 从 AWS CLI 输出中提取值。

    您可以改用--query,它遵循JMESPATH 语法。

    这是一个例子:

    aws ec2 describe-instances --query "Reservations[].Instances[].[InstanceId,State.Name,LaunchTime,Tags[?Key=='Name'].Value|[0]]"
    

    可以通过--output指定输出格式,例如jsontexttable或(对于AWS CLI v2)yaml

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 1970-01-01
      • 2021-11-24
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2020-03-28
      • 2011-11-17
      相关资源
      最近更新 更多