在 Ansible 中过滤 JSON 文档

Adr*_*.S. 2 json ansible jmespath

我有一个来自 GitHub 存储库的 JSON 回复,其中包含某个版本(assets文档中的数组)的可能下载列表。

我想获得浏览器的下载URL时,name资产端有x64.AppImage

在 Ansible 中,过滤器是基于jmespath它的终端工具构建的,我可以使用以下表达式查询 url:

assets[?ends_with(name, 'x64.AppImage')].browser_download_url
Run Code Online (Sandbox Code Playgroud)

使用以下 playbook,查询 JSON 文档并将其存储在json_reply变量中。

---
- hosts: local
  tasks:
    - name: Get list of Rambox releases
      uri:
        url: "https://api.github.com/repos/saenzramiro/rambox/releases/latest"
        body_format: json
      register: json_reply

    - name: Filter reply
      debug: URL -> "{{ item }}"
      with_items:
        - "{{ json_reply.json | json_query(json_filter) }}"
      vars:
        - json_filter: assets[?ends_with(name, 'x64.AppImage')].browser_download_url
Run Code Online (Sandbox Code Playgroud)

但是,执行此操作会出现以下错误:

fatal: [localhost]: FAILED! => {
    "msg": "JMESPathError in json_query filter plugin:\nIn function ends_with(), invalid type for value: latest-mac.json, expected one of: ['string'], received: \"unknown\""
}
Run Code Online (Sandbox Code Playgroud)

数组中latest-mac.json的第一个对象在哪里assets

如何让 Ansible 遍历所有assets数组并应用我的过滤器?

PS:

如果name我直接指定它而不是查询是否以单词结尾,则过滤器起作用:

assets[?name == 'Rambox-0.5.13-x64.AppImage')].browser_download_url
Run Code Online (Sandbox Code Playgroud)

JSON 示例:

{
  "url": "https://api.github.com/repos/saenzramiro/rambox/releases/8001922",
  "prerelease": false,
  "created_at": "2017-10-04T21:14:15Z",
  "published_at": "2017-10-05T01:10:55Z",
  "assets": [
    {
      "url": "https://api.github.com/repos/saenzramiro/rambox/releases/assets/4985942",
      "id": 4985942,
      "name": "latest-mac.json",
      "uploader": {
        "login": "saenzramiro",
        "id": 2694669
      },
      "browser_download_url": "https://github.com/saenzramiro/rambox/releases/download/0.5.13/latest-mac.json"
    },
    {
      "url": "https://api.github.com/repos/saenzramiro/rambox/releases/assets/4985640",
      "id": 4985640,
      "name": "Rambox-0.5.13-x64.AppImage",
      "uploader": {
        "login": "saenzramiro",
        "id": 2694669
       },
       "browser_download_url": "https://github.com/saenzramiro/rambox/releases/download/0.5.13/Rambox-0.5.13-x64.AppImage"
    }
  ],
  "tarball_url": "https://api.github.com/repos/saenzramiro/rambox/tarball/0.5.13"
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*rov 7

JMESPath 过滤器中的类型错误问题在issue 27299 中讨论。

您可以使用此修补的 json_query.py过滤器插件。

或应用双转换到你的对象作为一种解决方法:| to_json | from_json |
这会将对象转换为 JSON(因此是纯字符串)并返回,因此 json_query 会将字符串视为受支持的类型。