Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 29 ยท Practice and Review

Exercises with Solutions

Practice Ansible with 12 graded exercises on inventory, host patterns, ad-hoc commands, playbooks, templates, handlers, roles, vault and rolling updates, with full solutions.

You learn Ansible by writing Ansible. Reading about idempotence is one thing; deciding on your own whether a task needs creates, changed_when or a handler is another. This page has twelve exercises that cover the whole course, from a first inventory to a rolling update. They are graded: 1 to 4 are beginner, 5 to 9 intermediate, 10 to 12 advanced.

Ansible cannot run on this site, so each exercise has a read-only solution written in real YAML or shell, hidden under a "Show solution" button. For three of the exercises you also get a runnable self-check: a short JavaScript program that tests your answer and prints PASS or FAIL. The self-checks are stand-ins that model the idea (parsing an inventory, linting tasks, resolving variables). They are not Ansible, and a passing check does not replace running your playbook against a lab machine. A virtual machine or a container with SSH is enough; see Installing Ansible and Your First Ping.

A few ground rules:

  • Try first, peek later. Spend a few minutes on every exercise before you open the solution. Being stuck is where the learning happens.
  • Compare, don't copy. Your solution may differ from ours and still be right. Check that it is idempotent: run it twice and make sure the second run reports changed=0.
  • Use full module names such as ansible.builtin.copy, as the rest of this course does.
  • Never practise on production machines. Use a lab, and use --check --diff first.

Beginner

Exercise 1: Write an inventory

Write an INI inventory with two web servers (web1, web2, at 10.0.0.11 and 10.0.0.12) and one database server (db1, 10.0.0.21). Put the web servers in a group web and the database in db. Add a group prod that contains both groups, and set http_port=8080 for the web group. Related lesson: Inventory: Hosts and Groups.

Exercise 2: Host patterns

Given this inventory, which hosts does each pattern select? Write your answers before you check them.

INI
[web]
web1
web2
web3

[db]
db1
db2

[staging]
web3
db2
  1. web:&staging
  2. all:!db
  3. db:web:!web2

Self-check for exercises 1 and 2

The program below parses your inventory text and evaluates host patterns. The starter has one mistake in the prod group and wrong or empty answers for patterns 1 and 2. Fix them until you see only PASS lines. The third pattern is filled in as an example.

JS Self-check: inventory and host patterns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution for exercises 1 and 2
INI
[web]
web1 ansible_host=10.0.0.11
web2 ansible_host=10.0.0.12

[db]
db1 ansible_host=10.0.0.21

[prod:children]
web
db

[web:vars]
http_port=8080

Without :children, the lines web and db under [prod] are read as host names. Ansible would happily create two hosts called web and db, and nothing would warn you. Check your work with ansible-inventory -i inventory.ini --graph.

For the patterns: web:&staging means "in web and in staging", which is web3. all:!db is everyone except the db group: web1, web2, web3. db:web:!web2 is the union of both groups minus web2: db1, db2, web1, web3.

Exercise 3: Ad-hoc commands

Using the inventory from exercise 1, write four ad-hoc commands: (a) ping every host, (b) run uptime on the web group, (c) copy the local file ./motd to /etc/motd on the web group as root, and (d) restart nginx on web1 only. Related lesson: Ad-Hoc Commands.

Show solution
Terminal
ansible all -i inventory.ini -m ansible.builtin.ping

ansible web -i inventory.ini -m ansible.builtin.command -a "uptime"

ansible web -i inventory.ini -b -m ansible.builtin.copy \
  -a "src=./motd dest=/etc/motd owner=root group=root mode=0644"

ansible web -i inventory.ini -b -l web1 \
  -m ansible.builtin.service -a "name=nginx state=restarted"

-b (become) is needed whenever the task touches system files or services. -l web1 limits the run to one host inside the group. Notice that the copy command is idempotent: run it twice and the second run reports SUCCESS with "changed": false.

Exercise 4: Your first playbook

Write a playbook for the web group that installs git and curl, and creates a user deploy with /bin/bash as the shell that belongs to the extra group sudo. It must run as root through become. Related lesson: Playbooks and YAML Essentials.

Show solution
YAML
- name: Base setup for web servers
  hosts: web
  become: true
  tasks:
    - name: Install git and curl
      ansible.builtin.package:
        name:
          - git
          - curl
        state: present

    - name: Create the deploy user
      ansible.builtin.user:
        name: deploy
        shell: /bin/bash
        groups: sudo
        append: true

Passing a list to name installs both packages in one transaction, which is faster than a loop. append: true matters: without it, the user would be removed from every other supplementary group. The group sudo exists on Debian and Ubuntu; on Red Hat systems the equivalent is wheel.

Intermediate

Exercise 5: Make commands honest

The task list in the editor below is the JavaScript twin of a YAML play. It has four problems: two commands that would report changed on every run, one restart that belongs in a handler, and one task with no name. Fix them, then write the YAML version of the database initialisation (it must run only once). Related lesson: Modules and Idempotence.

JS Self-check: lint the task list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
YAML
- name: Initialise the database only once
  ansible.builtin.command: /opt/app/bin/init-db
  args:
    creates: /var/lib/app/.db-initialised

- name: Read the app version (never a change)
  ansible.builtin.command: /opt/app/bin/app --version
  register: version
  changed_when: false

- name: Create the app directory
  ansible.builtin.file:
    path: /srv/app
    state: directory
    mode: "0755"

The init command only creates the marker file if the program itself writes it; make sure /opt/app/bin/init-db really creates that path, or add a second task that does. The version query is read-only, so changed_when: false keeps the recap honest. The restart moves to a handlers: section and is triggered with notify: from whichever task changes the configuration.

Exercise 6: Variable precedence

A variable workers is defined in four places: the role default (2), group_vars/web (4), host_vars/web2 (8) and the play's vars: section (3). What value does each of these cases get? Related lesson: Variables, Facts and Precedence.

  1. web1
  2. web2
  3. web1, run with -e workers=1
  4. web2, after you delete the vars: line from the play
JS Self-check: predict the winner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
  1. 3. Play vars outrank anything from the inventory, so group_vars loses.
  2. 3. Surprise: even the more specific host_vars/web2 loses to play vars.
  3. 1. Extra vars beat everything.
  4. 8. With the play vars gone, the host variable beats its group and the role default.

The lesson: if a value must be overridable from the inventory, never also define it in the play's vars:. Put defaults in defaults/main.yml and overrides in group_vars or host_vars.

Exercise 7: Loops and conditions

Create the users alice and bob with one task, but only on Debian-family systems. Print a message with debug on every other family. Related lesson: Conditionals and Loops.

Show solution
YAML
- name: Create the team users
  ansible.builtin.user:
    name: "{{ item }}"
    state: present
  loop:
    - alice
    - bob
  when: ansible_facts['os_family'] == 'Debian'

- name: Explain why nothing happened
  ansible.builtin.debug:
    msg: "Skipping users on {{ ansible_facts['os_family'] }}"
  when: ansible_facts['os_family'] != 'Debian'

when is evaluated for each item, but because the condition does not use item, it gives the same answer every time. Quotes around "{{ item }}" are required whenever a YAML value starts with a brace. The condition reads a fact, so fact gathering must be on (it is by default).

Exercise 8: A template with a loop

Generate /etc/app-hosts on the web group from a template. It must contain one line per host in the web group, in the form 10.0.0.11 web1, using each host's ansible_host. Related lesson: Jinja2 Templates and Filters.

Show solution

templates/app-hosts.j2:

JINJA
# Managed by Ansible. Do not edit by hand.
{% for host in groups['web'] %}
{{ hostvars[host]['ansible_host'] }} {{ host }}
{% endfor %}

The task:

YAML
- name: Write the hosts list
  ansible.builtin.template:
    src: app-hosts.j2
    dest: /etc/app-hosts
    mode: "0644"

groups is a special variable holding the host names of every group, and hostvars gives access to another host's variables. The template module removes the newline after a {% ... %} line by default, so the output has no blank lines. Rendering the same template twice gives identical bytes, so the second run reports ok.

Exercise 9: Reload only when needed

Deploy /etc/nginx/nginx.conf from a template, validate it with nginx -t before it goes live, and reload nginx only when the file changed. Related lesson: Handlers, Tags and Task Control.

Show solution
YAML
- name: Configure nginx
  hosts: web
  become: true
  tasks:
    - name: Deploy nginx.conf
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: "0644"
        validate: nginx -t -c %s
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

validate runs the command against a temporary copy of the new file, replacing %s, and the real file is only replaced when the command succeeds, so a typo cannot break a running server. The handler runs once, at the end of the play, and only on hosts where the template task reported changed.

Advanced

Exercise 10: Extract a role

Turn the nginx play from exercise 9 into a role called nginx. The port must default to 80 and be overridable from the inventory. Show the directory layout and the playbook that uses the role. Related lesson: Roles and Project Layout.

Show solution
TEXT
roles/
  nginx/
    defaults/main.yml
    tasks/main.yml
    handlers/main.yml
    templates/nginx.conf.j2
site.yml

roles/nginx/defaults/main.yml:

YAML
nginx_port: 80

roles/nginx/tasks/main.yml:

YAML
- name: Deploy nginx.conf
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    mode: "0644"
    validate: nginx -t -c %s
  notify: Reload nginx

roles/nginx/handlers/main.yml:

YAML
- name: Reload nginx
  ansible.builtin.service:
    name: nginx
    state: reloaded

site.yml:

YAML
- name: Web servers
  hosts: web
  become: true
  roles:
    - role: nginx

In the template, write listen {{ nginx_port }};. Because the port lives in defaults, which has the lowest precedence, group_vars/web.yml containing nginx_port: 8080 overrides it without touching the role. Prefix every role variable with the role name (nginx_port) so roles do not collide.

Exercise 11: Protect a secret

The database role needs a password. Store it encrypted in the repository, make it available as db_password, run the playbook with a password prompt, and make sure the password never appears in task output. Related lesson: Ansible Vault and Secrets.

Show solution
Terminal
ansible-vault create group_vars/db/vault.yml

Inside the editor, write the secret under a prefixed name:

YAML
vault_db_password: "correct-horse-battery-staple"

group_vars/db/vars.yml (plain text, readable in code review):

YAML
db_password: "{{ vault_db_password }}"

A task that uses it:

YAML
- name: Create the application database user
  community.postgresql.postgresql_user:
    name: app
    password: "{{ db_password }}"
  no_log: true

Run it with:

Terminal
ansible-playbook site.yml --ask-vault-pass

The vault_ prefix trick lets people search for db_password in plain files and see where it comes from, while the value stays encrypted. no_log: true hides the task's arguments and results from the output and logs. The task assumes the community.postgresql collection is installed.

Exercise 12: A safe rolling update

Update the web group one host at a time. For each host: take it out of the load balancer, upgrade the application package, wait until its /health URL returns 200 (up to ten tries, three seconds apart), then put it back. If any host fails, the rollout must stop so the remaining hosts keep serving traffic. Related lessons: Handlers, Tags and Task Control and Ansible with Docker, Terraform and CI/CD.

Show solution
YAML
- name: Rolling update of the web tier
  hosts: web
  become: true
  serial: 1
  max_fail_percentage: 0

  pre_tasks:
    - name: Take the host out of the load balancer
      ansible.builtin.command: /usr/local/bin/lb-ctl disable {{ inventory_hostname }}
      delegate_to: lb1
      changed_when: true

  tasks:
    - name: Upgrade the application package
      ansible.builtin.package:
        name: myapp
        state: latest

    - name: Wait for the health check
      ansible.builtin.uri:
        url: "http://{{ ansible_host }}:8080/health"
        status_code: 200
      register: health
      until: health.status == 200
      retries: 10
      delay: 3

  post_tasks:
    - name: Put the host back
      ansible.builtin.command: /usr/local/bin/lb-ctl enable {{ inventory_hostname }}
      delegate_to: lb1
      changed_when: true

serial: 1 makes the whole play, including pre_tasks and post_tasks, run on one host at a time. max_fail_percentage: 0 aborts the play if any host in a batch fails, so a bad release stops at the first host. The lb-ctl command is a placeholder for your load balancer's real interface (a module from a collection, or an API call). It is not idempotent, which is why the tasks say changed_when: true explicitly.

What next

If you struggled with a particular exercise, go back to its lesson and then try it again from a blank file. If you breezed through, extend them: add a --check --diff run to every playbook, put your roles under version control and let a CI pipeline lint them with Testing, Linting and Debugging. When you are ready for a bigger build, Project: Build a Mini Ansible in JavaScript shows how the engine behind all of this works.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In an INI inventory, what does the section header [prod:children] do?

    With :children, each line is a group name. Without it, the lines are read as hosts. [prod:vars] is the section for variables.
  2. 2. A role default says workers: 2, group_vars/web says workers: 4 and the play has vars: workers: 3. What does a host in the web group get?

    Play vars rank above inventory group_vars, which rank above role defaults. Only extra vars (-e) would beat the play's value.
  3. 3. Why is a task ansible.builtin.command: /opt/app/bin/init-db a problem on its own?

    Command-style tasks are treated as changed by default. creates, removes and changed_when let you say when work is really needed.
  4. 4. What does serial: 1 with max_fail_percentage: 0 give you in a rolling update?

    serial limits each batch to one host, and a failure above the allowed percentage aborts the rest of the play.

Summary

  • Twelve exercises cover inventory, host patterns, ad-hoc commands, playbooks, idempotent commands, precedence, loops, templates, handlers, roles, vault and rolling updates.
  • Always check idempotence by running a playbook twice; the second recap should show changed=0.
  • Use [group:children] for groups of groups, -l to limit a run, validate before replacing config files and handlers for restarts and reloads.
  • Play vars beat inventory variables; keep overridable values in role defaults and in group_vars.
  • Keep secrets in vault files, expose them through prefixed variables and add no_log: true to tasks that use them.
  • For safe deployments, combine serial, health checks with until and retries, and max_fail_percentage.

Next: Common Mistakes and Troubleshooting