Q: "Get the task to run only on the first node."
web_servers:
hosts:
1.2.3.4:
1.2.3.5:
A: Playbook's keyword order controls the sorting of hosts
Quoting from Playbook Keywords
order:
Controls the sorting of hosts as they are used for executing the play. Possible values are inventory (default), sorted, reverse_sorted, reverse_inventory, and shuffle.
By default, the order is inventory, i.e. the first host in the play is the first host in the inventory. Use run_once
Quoting from Task Keywords:
run_once: Boolean that will bypass the host loop, forcing the task to attempt to execute on the first host available and afterward apply any results and facts to all active hosts in the same batch.
For example, the playbook
- hosts: webservers
tasks:
- debug:
msg: "Creates a backup cron on {{ inventory_hostname }}"
run_once: true
gives
msg: Creates a backup cron on 1.2.3.4
Test order of the hosts and see other options. Given the inventory
shell> cat hosts
webservers:
hosts:
1.2.3.4:
1.2.3.5:
1.2.3.3:
the playbook shows the first host in the play for the selected order
- hosts: webservers
order: inventory
tasks:
- debug:
msg: "inventory: {{ inventory_hostname }}"
run_once: true
- hosts: webservers
order: reverse_inventory
tasks:
- debug:
msg: "reverse_inventory: {{ inventory_hostname }}"
run_once: true
- hosts: webservers
order: sorted
tasks:
- debug:
msg: "sorted: {{ inventory_hostname }}"
run_once: true
- hosts: webservers
order: reverse_sorted
tasks:
- debug:
msg: "reverse_sorted: {{ inventory_hostname }}"
run_once: true
- hosts: webservers
order: shuffle
tasks:
- debug:
msg: "shuffle: {{ inventory_hostname }}"
run_once: true
gives (abridged)
msg: 'inventory: 1.2.3.4'
msg: 'reverse_inventory: 1.2.3.3'
msg: 'sorted: 1.2.3.3'
msg: 'reverse_sorted: 1.2.3.5'
msg: 'shuffle: 1.2.3.5'
Q: "For whatever reason it's not working for me."
A: In this case, delegate the task to the first host in the group. See Delegating tasks. For example
- debug:
msg: "Creates a backup cron on {{ inventory_hostname }}"
run_once: true
delegate_to: groups.webservers.0
gives
ok: [1.2.3.4 -> groups.webservers.0] =>
msg: Creates a backup cron on 1.2.3.4