I need to collect some info from VMs in our VMware cluster and am having trouble figuring out how to print only the information I need.
When running the code below:
The debug module prints to the job log. It’s a common mistake to try to use the job log as formatted output for other purposes, like reports. Instead you could use the ansible.builtin.template module to output the desired data in some other file. Or you can take the often-warned-against shortcut of using the copy module to do the same, like so:
---
- name: Example
hosts: localhost
gather_facts: false
vars:
vm_info:
virtual_machines:
- {'guest_name': 'rhel8tst', 'guest_fullname': 'Red Hat Enterprise Linux 8 (64-bit)', 'power_state': 'poweredOn', 'ip_address': 'xxx.xxx.xxx.xxx', 'mac_address': ['xxx'], 'uuid': '422c523e-7bb0-1f95-1c16-742c30ba445d', 'vm_network': {'xxx': {'ipv4': ['xxx.xxx.xxx.xxx'], 'ipv6': ['xxx']}}, 'esxi_hostname': '.xxxx', 'datacenter': 'xxxx', 'cluster': 'xxxxx', 'resource_pool': None, 'attributes': {}, 'tags': [], 'folder': None, 'moid': 'vm-502018', 'datastore_url': [{'name': 'xxxx', 'url': 'xxx'}], 'allocated': {}}
tasks:
- name: Show virtual machines guest_name in job log
ansible.builtin.debug:
msg: "{{ item['guest_name'] }}"
with_items: "{{ vm_info.virtual_machines }}"
- name: Print virtual machines guest_name in output file
ansible.builtin.copy: # should really use template here
content: |
Virtual Machine Names
{% for vm in vm_info.virtual_machines %}
- {{ vm['guest_name'] }}
{% endfor %}
dest: /tmp/virtual_machine_names.txt