Workshop Exercise - Conditionals, Handlers and Loops

Read this in other languages:
uk English, japan日本語, brazil Portugues do Brasil, france Française,Español Español.

Table of Contents


Three foundational Ansible features are:


Step 1 - Conditionals

Ansible can use conditionals to execute tasks or plays when certain conditions are met.

To implement a conditional, the when statement must be used, followed by the condition to test. The condition is expressed using one of the available operators like e.g. for comparison:

== Compares two objects for equality.
!= Compares two objects for inequality.
> true if the left hand side is greater than the right hand side.
>= true if the left hand side is greater or equal to the right hand side.
< true if the left hand side is lower than the right hand side.
<= true if the left hand side is lower or equal to the right hand side.

For more on this, please refer to the documentation:

As an example you would like to install an FTP server, but only on hosts that are in the “ftpserver” inventory group.

To do that, first edit the inventory to add another group, and place node2 in it. Make sure that that IP address of node2 is always the same when node2 is listed. Edit the inventory ~/lab_inventory/hosts to look like the following listing:

node1 ansible_host=
node2 ansible_host=
node3 ansible_host=

node2 ansible_host=

ansible-1 ansible_host=

Next create the file ftpserver.yml on your control host in the ~/ansible-files/ directory:

- name: Install vsftpd on ftpservers
  hosts: all
  become: true
    - name: Install FTP server when host in ftpserver group
        name: vsftpd
        state: latest
      when: inventory_hostname in groups["ftpserver"]


By now you should know how to run Ansible Playbooks, we’ll start to be less verbose in this guide. Go create and run it. :-)

Run it and examine the output. The expected outcome: The task is skipped on node1, node3 and the ansible host (your control host) because they are not in the ftpserver group in your inventory file.

TASK [Install FTP server when host in ftpserver group] *******************************************
skipping: [ansible-1]
skipping: [node1]
skipping: [node3]
changed: [node2]

Step 2 - Handlers

Sometimes when a task does make a change to the system, an additional task or tasks may need to be run. For example, a change to a service’s configuration file may then require that the service be restarted so that the changed configuration takes effect.

Here Ansible’s handlers come into play. Handlers can be seen as inactive tasks that only get triggered when explicitly invoked using the “notify” statement. Read more about them in the Ansible Handlers documentation.

As a an example, let’s write a playbook that:

First we need the file Ansible will deploy, let’s just take the one from node1. Remember to replace the IP address shown in the listing below with the IP address from your individual node1.

[student@ansible-1 ansible-files]$ scp node1:/etc/httpd/conf/httpd.conf ~/ansible-files/files/.

Next, create the Playbook httpd_conf.yml. Make sure that you are in the directory ~/ansible-files.

- name: manage httpd.conf
  hosts: web
  become: true
  - name: Copy Apache configuration file
      src: httpd.conf
      dest: /etc/httpd/conf/
      - restart_apache
    - name: restart_apache
        name: httpd
        state: restarted

So what’s new here?

Run the playbook. We didn’t change anything in the file yet so there should not be any changed lines in the output and of course the handler shouldn’t have fired.

Listen 8080

Apache should now listen on port 8080. Easy enough to verify:

[student@ansible-1 ansible-files]$ curl http://node1
curl: (7) Failed to connect to node1 port 80: Connection refused
[student@ansible-1 ansible-files]$ curl http://node1:8080
<h1>Apache is running fine</h1>

Leave the setting for listen on port 8080. We’ll use this in a later exercise.

Step 3 - Simple Loops

Loops enable us to repeat the same task over and over again. For example, lets say you want to create multiple users. By using an Ansible loop, you can do that in a single task. Loops can also iterate over more than just basic lists. For example, if you have a list of users with their coresponding group, loop can iterate over them as well. Find out more about loops in the Ansible Loops documentation.

To show the loops feature we will generate three new users on node1. For that, create the file loop_users.yml in ~/ansible-files on your control node as your student user. We will use the user module to generate the user accounts.

- name: Ensure users
  hosts: node1
  become: true

    - name: Ensure three users are present
        name: "{{ item }}"
        state: present
         - dev_user
         - qa_user
         - prod_user

Understand the playbook and the output:

Step 4 - Loops over hashes

As mentioned loops can also be over lists of hashes. Imagine that the users should be assigned to different additional groups:

- username: dev_user
  groups: ftp
- username: qa_user
  groups: ftp
- username: prod_user
  groups: apache

The user module has the optional parameter groups to list additional users. To reference items in a hash, the keyword needs to reference the subkey: for example.

Let’s rewrite the playbook to create the users with additional user rights:

- name: Ensure users
  hosts: node1
  become: true

    - name: Ensure three users are present
        name: "{{ item.username }}"
        state: present
        groups: "{{ item.groups }}"
        - { username: 'dev_user', groups: 'ftp' }
        - { username: 'qa_user', groups: 'ftp' }
        - { username: 'prod_user', groups: 'apache' }

Check the output:

Verify that the user dev_user was indeed created on node1 using the following playbook:

- name: Get user ID
  hosts: node1
    myuser: "dev_user"
    - name: Get {{ myuser }} info
        database: passwd
        key: "{{ myuser }}"
    - debug:
          - "{{ myuser }} uid: {{ getent_passwd[myuser].1 }}"
$ ansible-navigator run user_id.yml -m stdout

PLAY [Get user ID] *************************************************************

TASK [Gathering Facts] *********************************************************
ok: [node1]

TASK [Get dev_user info] *******************************************************
ok: [node1]

TASK [debug] *******************************************************************
ok: [node1] => {
    "msg": [
        "dev_user uid: 1002"

PLAY RECAP *********************************************************************
node1                      : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Previous Exercise - Next Exercise

Click here to return to the Ansible for Red Hat Enterprise Linux Workshop