By default, most tasks are run the target systems and some are run on the control node (that's your Ansible server). Refer to these articles for a better understanding of how tasks are run against the control node or target systems.
delegate_to and connection (this article) can be used to run certain tasks on a certain system, most often, to run certain tasks on your Ansible system.
In this example, the connection plugin is used to run every task in the playbook on the control node.
---
- hosts: all
connection: local
tasks:
- name: remove foo.txt on control node
ansible.builtin.file:
path: /tmp/foo.txt
state: absent
...
Or the --connection command line flag could be used.
ansible-playbook foo.yml --connection="local 127.0.0.1"
Often, run_once parameter is used so that each task in the playbook is only ran one time on the control node.
---
- hosts: all
connection: local
tasks:
- name: remove foo.txt on control node
ansible.builtin.file:
path: /tmp/foo.txt
state: absent
run_once: true
...
In this example, connection: local is used to create /tmp/foo.txt on the control node and then the next task creates /tmp/bar.txt on each target system.
---
- hosts: all
tasks:
- name: create foo.txt on control node
ansible.builtin.file:
path: /tmp/foo.txt
state: touch
run_once: true
connection: local
- name: remove foo.txt on each target system
ansible.builtin.file:
path: /tmp/bar.txt
state: touch
...
All of the tasks in a particular role can be performed on the control node. In this example, every task in the "foo" role will be performed on the control node.
---
- hosts: all
roles:
- role: foo
connection: local
...
Did you find this article helpful?
If so, consider buying me a coffee over at