Ansible - Run tasks against certain managed nodes using the hosts parameter

There are a few ways to run an ansible ad hoc command or the ansible-playbook command against certain managed nodes. 

 


Let's say your default hosts file or your own inventory file contains the following. Refer to Ansible - Inventory groups (all | ungrouped | other).

all:
  children:
    windows:
      hosts:
        server1.example.com:
        server2.example.com:
    linux:
      hosts:
        server3.example.com:
        server4.example.com:

 

In this example, the playbook has hosts: all, meaning the playbook would be run against every managed host (e.g. target systems) in your default hosts file or your own inventory file.

If you were to instead use hosts: windows, the playbook would only be run against server1 and server2. Or, if hosts: linux were used, the playbook would only be run against server3 and server4.

---
- hosts: all
  tasks:
    - name: create /tmp/foo.txt
      file:
        path: /tmp/foo.txt
        state: touch
...

 

Let's say you want to run the playbook against only the first host. In this scenario you can use - hosts: all[0] to target only the first host.

---
- hosts: all[0]
  tasks:
    - name: create /tmp/foo.txt
      file:
        path: /tmp/foo.txt
        state: touch
...

 

The ~ character can be used to use a regular expression to match one or more hosts. In this example, the regular expression should match server2.example.com.

---
- hosts: ~.*2.*
  tasks:
    - name: create /tmp/foo.txt
      file:
        path: /tmp/foo.txt
        state: touch
...

 

In this example, the regular expression should match each host that does not contain "2".

---
- hosts: !~.*2.*
  tasks:
    - name: create /tmp/foo.txt
      file:
        path: /tmp/foo.txt
        state: touch
...



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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




Comments


January 9th, 2022 by Prince Kumar
Is there a way to select a host at runtime, out of multiple hosts, to run our playbook.

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |