首页 > 解决方案 > 带有条件的ansible中的json查询

问题描述

在 Ansible 中,我使用 json_query 和循环。当“contentId”为“2565845434839sdsfc9we”时,我想获取“controllerKey”。尝试了几件事,它们似乎都不起作用。甚至可能吗?

        result": {
                "hardware": {
                    "_vimtype": "vim.vm.VirtualHardware", 
                    "device": [                     
                        {
                            "_vimtype": "vim.vm.device.VirtualDisk", 
                            "backing": {
                                "contentId": "2565845434839sdsfc9we", 
                                "writeThrough": false
                            }, 
                            "controllerKey": 1000, 
                        },
                        {
                            "_vimtype": "vim.vm.device.VirtualDisk", 
                            "backing": {
                                "contentId": "5264578434839sdsfc9rt", 
                                "writeThrough": false
                            }, 
                            "controllerKey": 1001, 
                        }                       
                    ], 
                    "memoryMB": 16384, 
                    "numCPU": 2, 
                    "numCoresPerSocket": 1, 
                    "virtualICH7MPresent": false, 
                    "virtualSMCPresent": false
                }

标签: pythonjsonansiblejinja2jmespath

解决方案


下面的任务

- debug:
    msg: "{{ result.hardware.device|
             json_query('[?backing.contentId==`2565845434839sdsfc9we`].controllerKey')|
             first }}"

"msg": "1000"

也可以迭代查询。下面的任务

- debug:
    msg: "contentId: {{ item }}
          controllerKey: {{ result.hardware.device|
                            json_query(query)|
                            first }}"
  vars:
    query: "[?backing.contentId=='{{ item }}'].controllerKey"
  loop:
    - '2565845434839sdsfc9we'

"msg": "contentId: 2565845434839sdsfc9we controllerKey: 1000"

推荐阅读