Ansible - ansible_play_hosts magic variable
by
Jeremy Canfield |
Updated: January 31 2022
| Ansible articles
The ansible_play_hosts magic variable can be used to output the managed hosts the play is being run against.
For example, let's say you have the following playbook.
---
- hosts: all
tasks:
- debug:
msg: "{{ ansible_play_hosts }}"
If you get the following output, the gather_facts module may be set to false. gather_facts must be set to true, or not defined at all in your playbook, as gather_facts is true by default.
TASK [debug]
fatal: [server1.example.com]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible_play_hosts' is undefined\n\nThe error appears to be in 'testing.yml': line 8, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - debug:\n ^ here\n"}
Something like this should be returned.
TASK [debug]
ok: [server1.example.com] => {
"msg": [
"server1.example.com",
"server2.example.com",
"server3.example.com"
]
}
The same could be done with the ansible_play_batch or ansible_play_hosts_all magic variables, which should return the same exact output.
Did you find this article helpful?
If so, consider buying me a coffee over at