Get started with Ansible Playbooks

Discover the basics of creating Ansible playbooks using practical examples, including key components such as plays, tasks, modules, and more. 

Start your Ansible Automation Platform Trial

Ansible executes automation tasks on managed nodes or “hosts”. We define these hosts or groups of hosts in a file called inventory. In this lesson, we will cover the basics of creating and using Ansible inventories. 

In this lesson, you will:

  • Learn about Ansible inventories.

Ansible inventories are essentially a list of managed nodes that can be grouped together. Inventory files are commonly composed using INI and YAML files.

Let’s use an example to explore Ansible inventory concepts:

---
all:
  children:
    web:
      hosts:
        web1:
          ansible_host: 192.168.0.10
        web2:
          ansible_host: web2.example.com
	

Ansible YAML inventory example.

Code

Definition

web:

This is an inventory group. The web group comprises the web1 and web2 hosts. Inventory groups make it easier to run automation on nodes with common attributes. They can also be nested under other groups.

web1:

This is an inventory host. Hosts are individual nodes managed by Ansible.

ansible_host: 192.168.0.10

This variable sets the host's IP address or domain name. You can also use variables in inventories to reuse in playbooks. Variables can be associated with individual hosts or groups. In this example, we’re setting the ansible_host variable to 192.168.0.10.

Your turn

Expand on the Ansible inventory example above:

  1. Open your editor and create an Ansible inventory file called hosts.yml.
  2. Copy the contents of the Ansible YAML inventory example above into hosts.yml.
  3. Create a new inventory group with the following details:
    1. Add the group name as database.
    2. Add a new host called db1 to the database inventory group.
    3. Add a variable to the db1 host called ansible_user.
    4. Set the ansible_user variable value to rhel.

The updated hosts.yml inventory file should look like this:

---
            all:
             children:
               web:
                 hosts:
                   web1:
                     ansible_host: 192.168.0.10
                   web2:
                     ansible_host: web2.example.com
               database:
                 hosts:
                   db1:
                     ansible_user: rhel
            

Update Ansible YAML inventory example.

For more details, please refer to the Ansible inventory documentation.

Next, we’ll explore more advanced Ansible playbook topics, such as Ansible variables and facts.

Previous resource
Ansible Playbook fundamentals
Next resource
Ansible Playbook variables and facts