Bootstrap FreeKB - Ansible - Run task on specific server using connection
Ansible - Run task on specific server using connection

Updated:   |  Ansible articles

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 Buy Me A Coffee



Comments


June 02 2025 by Jai
Superb postings Regards! web site Nicely put. Many thanks. casino en ligne Nicely put. Cheers! casino en ligne Incredible lots of helpful tips! casino en ligne Nicely put. Appreciate it. casino en ligne Seriously many of helpful data. casino en ligne You definitely made your point. casino en ligne Really a lot of helpful information! casino en ligne Cheers! Awesome stuff! casino en ligne Regards. I enjoy this. casino en ligne

Add a Comment


Please enter e9f974 in the box below so that we can be sure you are a human.