Search code examples
ansiblejmespath

Filter debug msg


I am using Ansible 2.9.13 and I have this playbook:

---
- hosts: localhost
  connection: local
  vars:
    ansible_python_interpreter: /usr/bin/env python3
  vars_files:
            - vars.yml
  tasks:
    - name: Get Tags from given VM Name
      vmware_vm_info:
         validate_certs: no
         hostname: '{{ vcenter_server }}'
         username: '{{ vcenter_user }}'
         password: '{{ vcenter_pass }}'
         folder: '{{ provision_folder }}'
      delegate_to: localhost
      register: vm_info
    - debug:
         msg:  "{{ vm_info.virtual_machines | json_query(query) }}"
      vars:
         query: "[?guest_name=='C97A1612171478']"

When I run it I am getting this output:

ok: [localhost] => {
    "msg": [
        {
            "attributes": {},
            "cluster": "xxx01",
            "esxi_hostname": "xxxx",
            "guest_fullname": "Microsoft Windows 10 (64-bit)",
            "guest_name": "C97A1612171478",
            "ip_address": "10.x.x.x",
            "mac_address": [
                "0x:x:x:x:xd:x"
            ],
            "power_state": "poweredOn",
            "tags": [],
            "uuid": "420xxaf-xxx-xe2-9xe-a5xxxxxa3c",
            "vm_network": {
                "0x:x:x:xa:x:x": {
                    "ipv4": [
                        "169.x.x.x"
                    ],
                    "ipv6": [
                        "x::x:x:x:xc"
                    ]
                },
                "x:x:x:x:x0:x1": {
                    "ipv4": [
                        "169.x.x.x"
                    ],
                    "ipv6": [
                        "x::x7:xf:x:x"
                    ]
                },
                "0x:5x:x:x:ax:x": {
                    "ipv4": [
                        "10.x.x.x"
                    ],
                    "ipv6": [
                        "x::1xx:x:8xx:x"
                    ]
                }
            }
        }
    ]
}

How can I filter the output to make it show only the "ip_address": "10.x.x.x". In the end only the 10.x.x.x.

I have tried some ways adding the key ip_address in the message code but all of them gave me an error.

I can filter the msg using Python but if there's a way to get it using Ansible I would like to know how.


Solution

  • If you want to get this information without a loop:

    • If you need an object as a result:
      - debug:
          msg: "{{ vm_info.virtual_machines | json_query(query) }}"
        vars:
          query: "[?guest_name=='C97A1612171478'] | [0].{ip_address: ip_address}"
      
      will yield
      {
        "ip_address": "10.x.x.x"
      }
      
    • If you need a string as a result:
      - debug:
          msg: "{{ vm_info.virtual_machines | json_query(query) }}"
        vars:
          query: "[?guest_name=='C97A1612171478'] | [0].ip_address"
      
      will yield
      "10.x.x.x"