json - 使用JQ过滤cloudformation堆栈资源

标签 json aws-cloudformation jq

我正在尝试编写一个 JQ 过滤器,用于根据资源属性从 AWS cloudformation 模板中过滤特定资源。

例如,当从以下(缩短的)cloudformation 模板开始时:

{
"Resources": {
"vpc001": {
  "Type": "AWS::EC2::VPC",
  "Properties": {
    "CidrBlock": "10.1.0.0/16",
    "InstanceTenancy": "default",
    "EnableDnsSupport": "true",
    "EnableDnsHostnames": "true"
  }
},
"ig001": {
  "Type": "AWS::EC2::InternetGateway",
  "Properties": {
    "Tags": [
      {
        "Key": "Name",
        "Value": "ig001"
      }
    ]
  }
}
}
}

我想构建一个 jq-filter,使我能够根据(一个或多个)属性字段过滤特定资源。

例如:

过滤 Type="AWS::EC2::InternetGateway"时,结果应为

{
 "Resources": {
"ig001": {
  "Type": "AWS::EC2::InternetGateway",
  "Properties": {
    "Tags": [
      {
        "Key": "Name",
        "Value": "ig001"
      }
    ]
  }
}
}
}

一个额外的好处是能够过滤“OR”组合的值。 因此,“AWS::EC2::InternetGateway”或“AWS::EC2::VPC”的过滤器应该生成原始文档。

任何建议或见解将不胜感激。

发送!

最佳答案

@hek2mgl 的建议可能足以满足您的目的,但它并不能完全产生您所要求的答案。这是一个非常相似的解决方案。它使用 jq 的 map() 和 map_values() 过滤器的泛化,这通常很有用:

def mapper(f):
  if type == "array" then map(f)
  elif type == "object" then
  . as $in
  | reduce keys[] as $key
      ({};
       [$in[$key] | f ] as $value
       | if $value | length == 0 then . else . + {($key): $value[0]}
         end)
  else .
  end;

.Resources |= mapper(select(.Type=="AWS::EC2::VPC"))

使用您的示例输入:

$ jq -f resources.jq resources.json
{
  "Resources": {
    "vpc001": {
      "Type": "AWS::EC2::VPC",
      "Properties": {
        "CidrBlock": "10.1.0.0/16",
        "InstanceTenancy": "default",
        "EnableDnsSupport": "true",
        "EnableDnsHostnames": "true"
      }
    }
  }

正如 @hek2mgl 指出的那样,现在指定更复杂的选择标准很简单。 }

关于json - 使用JQ过滤cloudformation堆栈资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34105038/

相关文章:

javascript - 将 JSON 解析为子集

javascript - 如何在不获取空对象的情况下进行 JSON.stringify 和 JSON.parse?

php - 在 Laravel Blade View 中从 JSON 数据创建菜单

amazon-web-services - AWS CLI Cloudformation - 终端节点 URL 读取超时 : "https://cloudformation.us-east-1.amazonaws.com/"

json - 在使用 jq 验证 JSON 内容时结合多个测试

javascript - 如何响应 javascript 中的 SyntaxError

amazon-web-services - 在 AWS 中,我们可以仅对两个不同的 dynamodb 表使用一个客户托管 key 吗?这是好的做法吗?

amazon-web-services - "WaitCondition timed out. Received 0 conditions when expecting 1"云信息错误

bash - 使用 jq 更改变量中的 json 对象和字段值

json - 如何从 JSON 对象流中获取第一个元素?