json_query & regular expression

In jason query how can i add regular expression ? eg if have vm1, vm2,vm3 below query can be adjusted ? eg query: “[?guest_name == ‘vm*’ ]” , seems does not work in below case

https://jmespath.org/specification.html#filterexpressions i tried few things but no luck

Thanks

Filter "selectattr" should do the job. For example

    - debug:
        msg: "{{ item.ip_address }}"
      loop: "{{ vm_facts|
                selectattr('guest_name', 'match', '^vm1$')|
                list }}"
    - debug:
        msg: "{{ item.ip_address }}"
      loop: "{{ vm_facts|
                selectattr('guest_name', 'match', '^vm(.*)$')|
                list }}"

I'm not aware of regex in JMESPath.
https://jmespath.readthedocs.io/en/latest/

HTH,

  -vlado

Thanks for the Reply Valdo

I get error

TASK [debug] *********************************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {“msg”: “‘str object’ has no attribute ‘guest_name’”}

I get error
TASK [debug]

***********************************************************************************************************************>
fatal: [localhost]: FAILED! => {"msg": "'str object' has no attribute

'guest_name'"}

Take a look at the structure of "vm_fact" and fix it. If you still have issues
post:

    - debug:
        var: vm_fact

Thanks for your reply Valdo. This is a JSON output

{
“attributes”: {},
“cluster”: “xx”,
“esxi_hostname”: “xx”,
“guest_fullname”: “Microsoftxx”,
“guest_name”: “xx”,
“ip_address”: “xx”,
“mac_address”: [
“xx”
],
“power_state”: “poweredOn”,
“tags”: ,
“uuid”: “xx”,
“vm_network”: {
“xx”: {
“ipv4”: [
“xx”
],
“ipv6”:
}

I am reading about - selectattr - as i am new to this.

Thanks

There shouldn't be any problem with the dictionary "vm_facts" you posted. The
attribute "guest_name" is in place. I can't explain the error. It's up to you
to fix the JSON paths.

I would do this in a simpler way -

  • name: Gather all VMs information
    vmware_vm_info:
    hostname: ‘{{ vcenter_hostname }}’
    username: ‘{{ vcenter_username }}’
    password: ‘{{ vcenter_password }}’
    validate_certs: no
    register: vm_facts
    delegate_to: localhost

  • debug:
    msg: “{{ item.ip_address }}”
    loop: “{{ vm_facts.virtual_machines }}”
    when:

  • item.guest_name | regex_search(‘^vm’)

Even this works for me - notice vm_facts.virtual_machines

  • debug:
    msg: “{{ item.ip_address }}”
    loop: “{{ vm_facts.virtual_machines | selectattr(‘guest_name’, ‘match’, ‘^vm(.*)$’)| list }}”

Thanks Abhijeet & Valdo for your time to check. This works !