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 contain 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 touch (create) the /tmp/foo.txt file on every hosts 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
...
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
...