I am trying to find a way of creating the following result with the Ansible debug module.
Desired Results
{
"myserver01": {
"host_var_one": "foo",
"host_var_two": "bar"
},
"myserver02": {
"host_var_one": "biz",
"host_var_two": "baz"
},
"myserver03": {
"host_var_one": "fizz",
"host_var_two": "buzz"
}
}
Example Inventory
[my_servers]
myserver01 host_var_one=foo host_var_two=bar
myserver02 host_var_one=biz host_var_two=baz
myserver03 host_var_one=fizz host_var_two=buzz
I would like to be able to provide a list of hostvars and have them displayed in a dict under each host in the inventory, where the key is the hostvar name, and the value is the hostvar value. Including another hostvar in the results should ideally just require adding another variable name to a list.
For example, in the task I would list that I want ["host_var_one", "host_var_two"] for each host in the inventory and get the above desired results.
I have the following task that gets somewhat close to what I want. I just can't figure out a way of listing all desired variables that I want for each host in the format described above. The following only works with one variable, and it doesn't list the variable name along with the value.
myplaybook.yml
---
- name: Test
hosts: all
gather_facts: yes
user: ansible
become: yes
tasks:
- name: Debug
debug:
msg: "{{ dict(query('inventory_hostnames', 'all') | zip(query('inventory_hostnames', 'all') | map('extract', hostvars, 'host_var_one'))) }}"
run_once: yes
Results of myplaybook.yml
$ ansible-playbook -i inventory test.yml --limit "myserver01"
PLAY [Test] **************************************************************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************************************
ok: [myserver01]
TASK [Debug] *************************************************************************************************************************************************
ok: [myserver01] => {
"msg": {
"myserver01": "foo",
"myserver02": "biz",
"myserver03": "fizz"
}
}