sherri
sherri

Reputation: 461

json query in ansible with conditions

In Ansible i am using json_query and loops. I want to grab the 'controllerKey' when 'contentId' is ' 2565845434839sdsfc9we'. tried several things, none of them seems to work. Is it even possible?

        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
                }

Upvotes: 1

Views: 1188

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

The task below

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

gives

"msg": "1000"

It is also possible to iterate the query. The task below

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

gives

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

Upvotes: 1

Related Questions