I'm having some issues pulling together some data using Ansible (v2.16.2 ; python v3.11.5) and I can't seem to find the right way to merge the data (type errors). I do have the community.general collection installed, but do not want to add any other collections right now (business requirement).
In an inventory file, I will be providing a list of hosts.
[myhosts]
SomeHost001
AnotherHost002
RandomHost-003
So far, I'm trying to do this:
- Get the hosts into an array
- Add additional details like ansible_facts for that host (based on a matching
nodenamevalue).
The outcome I'm looking for is this:
"provided_hosts": {
"SomeHost001": [{
"facts": [{ ...ansible_facts... }]
}],
"AnotherHost002": [{
"facts": [{ ...ansible_facts... }]
}],
"RandomHost-003": [{
"facts": [{ ...ansible_facts... }]
}],
Later on, I will add some other details like provided_hosts['SomeHost001'].vcenter and more. For example, I have an array of vcenters from VMware and put together this array:
"vcenters": {
"vcenter1": {
"hostname": "vc01.somewhere.com",
"ip_addr": "192.168.10.90"
},
"vcenter2": {
"hostname": "vc02.somewhere.com",
"ip_addr": "192.168.10.91"
},
# etc (there are 5 total)
}
I keep trying variations of this type of play:
---
- name: Data Collection
hosts: myhosts
gather_facts: yes
vars:
provided_hosts: {} # also tried []
tasks:
- name: Set provided hosts
set_fact:
provided_hosts: "{{ groups['myhosts'] }}"
- name: Add vcenters
set_fact:
provided_hosts: "{{ provided_hosts | default({}) | combine('vcenters', item, default={}, recursive=true, list_merge='append') }}"
loop: "{{ vcenters | list }}"
Apologies if this seems incomplete... I've tried quite a few variations (this one ends with recursive and list_merge are the only valid keyword arguments"), but fundamentally, I'm just trying to catch the related data into the array where <hostname> (provided_hosts[<hostname>] = ansible_facts guest_name). This is so I have all of the needed host data that will be used later to export the details.
Can anyone help me get to the right place here? Thank you in advance!
I've tried quite a few variations (including help from online tutorials), but I can't seem to wrap my head around defining the array correctly for this scenario.
You don't need to do it - it already exists: read about hostvars magic variable and other special variables.