jq:匹配两个语句时如何获取值而不是布尔值?

jq: How to get a value rather than boolean when matching two statements?

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

示例:

{
  "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'

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

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

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 )