Bootstrap FreeKB - Ansible - Target servers using the hosts parameter
Ansible - Target servers using the hosts parameter

Updated:   |  Ansible articles

The hosts parameter is used to define the hosts a play in a playbook will run against. Let's say your default hosts file or your own inventory file contains the following.

web:
  hosts:
    www1.example.com
    www2.example.com
db:
  hosts:
    db1.example.com
    db2.example.com

 

In this example, hosts: all is used. This will run the tasks in the play on every host in your inventory.

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

 

In this example, hosts: web is used. This will create the /tmp/foo.txt file on only the web hosts in your invetory (www1.example.com and www2.example.com).

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

 

You can specifiy one or more hosts listed in your default hosts file or your own inventory file in the playbook.

---
- hosts: www1.example.com
  tasks:
  - name: touch /tmp/foo.txt
    file:
      path: /tmp/foo.txt
      state: touch
...

 

Here is how you can run a play against servers using a regular expression. The leading ~ (tilde) is used to tell Ansible to interpret the is a regular expression.

---
- hosts: ~[a-zA-Z]xample.com
  tasks:
  - name: touch /tmp/foo.txt
    file:
      path: /tmp/foo.txt
      state: touch
...

 

A playbook can contain multiple plays. In this example, /tmp/foo.txt will be created on the web hosts and /tmp/bar.txt will be created on the db hosts.

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

- hosts: db
  tasks:
  - name: touch /tmp/bar.txt
    file:
      path: /tmp/bar.txt
      state: touch
...

 




Did you find this article helpful?

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



Comments


Add a Comment


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