Task delegation is an important feature of Ansible since
there might be use cases where we would
want to perform a task on one host with reference to other hosts.
We can do this using the delegate_to keyword.
For example, if we want to manage nodes in a load balancer pool we can do:
1- hosts: webservers
2 serial: 5
3
4 tasks:
5- name: Take machine out of ELB pool
6 ansible.builtin.command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
7 delegate_to: 127.0.0.1
8
9- name: Actual steps would go here
10 ansible.builtin.yum:
11 name: acme-web-stack
12 state: latest
13
14- name: Add machine back to ELB pool
15 ansible.builtin.command: /usr/bin/add_back_to_pool
{{ inventory_hostname }}
16 delegate_to: 127.0.0.1
We are also defining serial to control the number of
hosts executing at one time.
There is another shorthand syntax called local_action
which can be used instead of delegate_to.
1...
2tasks:
3 - name: Take machine out of ELB pool
4 local_action: ansible.builtin.command
/usr/bin/take_out_of_pool {{ inventory_hostname }}
5...
But there are few exceptions also such as include, add_host,
and debug tasks that cannot be delegated.