Ansible variables question from output and filtered with json_query

Viewed 42

I am trying to get the pertinent fields from a vmware module output, I am filtering with json, but the says my variable target_vm_name is undefined. how do I get a variable with only the matching criteria which is filtered by the ip address of the list of hosts I want to iterate through?

code is below:


- name: Loop thru hosts and get IPs
  hosts: rpa_test

  vars:
     ip_addr:
          "{{ lookup('dig', ansible_host) }}"
  tasks:
        - debug:
             msg: "System {{ inventory_hostname }} has ip address of {{ ip_addr }}"
        - name: get vm info based on ip
          community.vmware.vmware_vm_info:
                            hostname: "{{ vcenter_hostname }}"
                            username: "{{ vault_vcenter_admin_name }}"
                            password: "{{ vault_vcenter_admin_password }}"
                            validate_certs: False
          delegate_to: localhost
          register: vm_info
          vars:
                           target_vm_name: "{{ vm_info.virtual_machines | json_query(query) }}"
                           query: "[?ip_address=={{ ip_addr }}]"
        - debug:
                           msg:  "{{ target_vm_name.virtual_machines.guest_name }}"


1 Answers

vars is not at the right place inside the community.vmware.vmware_vm_info task ,

you should put it in the debug task:

  tasks:
        - debug:
            msg: "System {{ inventory_hostname }} has ip address of {{ ip_addr }}"
        - name: get vm info based on ip
          community.vmware.vmware_vm_info:
                            hostname: "{{ vcenter_hostname }}"
                            username: "{{ vault_vcenter_admin_name }}"
                            password: "{{ vault_vcenter_admin_password }}"
                            validate_certs: False
          delegate_to: localhost
          register: vm_info

        - debug:
            msg:  "{{ target_vm_name.virtual_machines.guest_name }}"
          vars:
            target_vm_name: "{{ vm_info.virtual_machines | json_query(query) }}"
            query: "[?ip_address=={{ ip_addr }}]"
Related