【问题标题】:jq: How to get a value rather than boolean when matching two statements?jq:匹配两个语句时如何获取值而不是布尔值?
【发布时间】:2021-05-02 11:38:28
【问题描述】:

我正在尝试提取与“CREATE COMPLETE”或“UPDATE_COMPLETE”的键 StackName 和 StackStatus 中的特定字符串匹配的所有 AWS CloudFormation 堆栈的 ARN (.StackId)。

例子:

{
  "StackSummaries": [
    {
      "StackId": "arn:aws:cloudformation:us-east-1:AWS_ACCOUNT_ID:stack/some-service-name/9ad489b0-ab22-11eb-af8f-0a56fXXXX8ad",
      "StackName": "some-service-name",
      "CreationTime": "2021-05-02T08:44:28.106000+00:00",
      "StackStatus": "CREATE_COMPLETE",
      "DriftInformation": {
        "StackDriftStatus": "NOT_CHECKED"
      }
    },
    {
      "StackId": "arn:aws:cloudformation:us-east-1:AWS_ACCOUNT_ID:stack/some-service-name/44239210-9703-11eb-b085-12daXXXX6186",
      "StackName": "some-service-name",
      "TemplateDescription": "some-service-name",
      "CreationTime": "2021-04-06T18:09:45.470000+00:00",
      "LastUpdatedTime": "2021-04-13T13:09:37.683000+00:00",
      "StackStatus": "UPDATE_COMPLETE",
      "DriftInformation": {
        "StackDriftStatus": "NOT_CHECKED"
      }
    }
  ]
}

这些是我尝试过的命令:

aws cloudformation list-stacks --profile production |
    jq -r '.StackSummaries[] |
        select(.StackName | match("some-service-name";"i")) and
        select(.StackStatus | match("UPDATE_COMPLETE";"i")) .StackId'
aws cloudformation list-stacks --profile production |
    jq -r '.StackSummaries[] |
        select(.StackName | contains("some-service-name")) and
        select(.StackStatus | contains("UPDATE_COMPLETE")) .StackId'
aws cloudformation list-stacks --profile production |
    jq -r '.StackSummaries[] |
        select(.StackName | match("some-service-name";"i")) and
        select(.StackStatus | match("UPDATE_COMPLETE";"i") or
        select(.StackStatus | match("CREATE_COMPLETE";"i"))) .StackId'

以上所有命令都返回布尔值而不是 StackId 本身。如何获取 StackId 而不是布尔值?

【问题讨论】:

    标签: shell jq aws-cli


    【解决方案1】:

    如果你有两个条件要满足,过滤两次

    select(condition1) | select(condition2)
    

    或and条件

    select(condition1 and condition2)
    

    正如您所发现的,and-ing select 的结果没有意义。

    jq -r '
       .StackSummaries[] |
       select( 
          .StackName == "some-service-name" and (
             .StackStatus == "CREATE_COMPLETE" or
             .StackStatus == "UPDATE_COMPLETE"
           )
       ) |
       .StackId
    '
    

    jqplay


    注意|的优先级很低,所以

    a | b and c | d
    

    意思

    a | ( b and c ) | d
    

    如果你的意思是使用括号

    ( a | b ) and ( c | d )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多