TExcelTAD
Home › Configuration Management: Ansible › Ansible Exercises

Ansible Exercises

Each exercise starts from a real session that shows a problem. Change the code (copy the session into your own terminal, or edit it in the playground and compare with the saved output) until it produces the expected output, then compare with the solution. Every solution below is a verified session.

Exercise 1: A command that never stops changing

Topics: command & shell, Handlers

The installer task reports changed on every run, so the "Restart app" handler fires every time too. Make the second run report changed=0 and keep the handler silent, without removing the command task.

bash · try it yourself
cat > install.yml <<'YML'
- name: Install the tool
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Run the installer
      ansible.builtin.command: sh -c 'mkdir -p /home/learner/opt/tool && echo 1.4 > /home/learner/opt/tool/VERSION'
      notify: Restart app
  handlers:
    - name: Restart app
      ansible.builtin.debug:
        msg: restarting
YML
for run in 1 2; do ansible-playbook install.yml | grep -E '^RUNNING|^localhost'; done
RUNNING HANDLER [Restart app] **************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
RUNNING HANDLER [Restart app] **************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Expected output of your fixed version:

text
RUNNING HANDLER [Restart app] **************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Show solution

creates tells Ansible which file the command produces; when it exists, the task is ok and doesn't notify.

bash · try it yourself
cat > install.yml <<'YML'
- name: Install the tool
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Run the installer
      ansible.builtin.command:
        cmd: sh -c 'mkdir -p /home/learner/opt/tool && echo 1.4 > /home/learner/opt/tool/VERSION'
        creates: /home/learner/opt/tool/VERSION
      notify: Restart app
  handlers:
    - name: Restart app
      ansible.builtin.debug:
        msg: restarting
YML
for run in 1 2; do ansible-playbook install.yml | grep -E '^RUNNING|^localhost'; done
RUNNING HANDLER [Restart app] **************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Exercise 2: The override that is ignored

Topics: Variable Precedence, Role Defaults

The team sets nginx_port: 8080 in group_vars/web.yml, but the role keeps rendering port 80. Fix the role (not the inventory) so the group variable wins, while hosts without an override still get 80.

bash · try it yourself
mkdir -p roles/nginx_site/{vars,tasks} group_vars
printf '[web]\nweb1 ansible_connection=local\n' > hosts.ini
echo 'nginx_port: 8080' > group_vars/web.yml
echo 'nginx_port: 80' > roles/nginx_site/vars/main.yml
cat > roles/nginx_site/tasks/main.yml <<'YML'
- name: Show the port
  ansible.builtin.debug:
    msg: "listen {{ nginx_port }}"
YML
printf -- '- name: Web\n  hosts: web\n  gather_facts: false\n  roles: [nginx_site]\n' > site.yml
ansible-playbook -i hosts.ini site.yml | grep '"msg"'
    "msg": "listen 80"

Expected: "msg": "listen 8080".

Show solution

Role vars/ outrank inventory variables. Tunables belong in defaults/, the weakest level:

bash · try it yourself
mkdir -p roles/nginx_site/{defaults,tasks} group_vars
printf '[web]\nweb1 ansible_connection=local\n' > hosts.ini
echo 'nginx_port: 8080' > group_vars/web.yml
echo 'nginx_port: 80' > roles/nginx_site/defaults/main.yml
cat > roles/nginx_site/tasks/main.yml <<'YML'
- name: Show the port
  ansible.builtin.debug:
    msg: "listen {{ nginx_port }}"
YML
printf -- '- name: Web\n  hosts: web\n  gather_facts: false\n  roles: [nginx_site]\n' > site.yml
ansible-playbook -i hosts.ini site.yml | grep '"msg"'
rm group_vars/web.yml
ansible-playbook -i hosts.ini site.yml | grep '"msg"'
    "msg": "listen 8080"
    "msg": "listen 80"

Exercise 3: A hosts file from the inventory

Topics: Jinja2 Templates, Groups & hostvars, Loops

Write cluster-hosts with one line <private_ip> <name> for every host in the app group, sorted by name, between # BEGIN / # END markers, so the file can be included in /etc/hosts. Start from this inventory:

bash · try it yourself
cat > hosts.ini <<'INI'
[app]
app-c ansible_connection=local private_ip=10.0.1.12
app-a ansible_connection=local private_ip=10.0.1.10
app-b ansible_connection=local private_ip=10.0.1.11
INI
ansible-inventory -i hosts.ini --graph
@all:
  |--@ungrouped:
  |--@app:
  |  |--app-c
  |  |--app-a
  |  |--app-b

Expected file content:

text
# BEGIN app cluster (managed by Ansible)
10.0.1.10 app-a
10.0.1.11 app-b
10.0.1.12 app-c
# END app cluster
Show solution

run_once: true writes the file once, not once per host (they all write the same local file here; on real servers you would drop run_once so each host gets its copy).

bash · try it yourself
cat > hosts.ini <<'INI'
[app]
app-c ansible_connection=local private_ip=10.0.1.12
app-a ansible_connection=local private_ip=10.0.1.10
app-b ansible_connection=local private_ip=10.0.1.11
INI
mkdir templates
cat > templates/cluster-hosts.j2 <<'J2'
# BEGIN app cluster (managed by Ansible)
{% for h in groups['app'] | sort %}
{{ hostvars[h].private_ip }} {{ h }}
{% endfor %}
# END app cluster
J2
cat > hosts.yml <<'YML'
- name: Cluster hosts file
  hosts: app
  gather_facts: false
  tasks:
    - name: Render it
      ansible.builtin.template:
        src: cluster-hosts.j2
        dest: /home/learner/cluster-hosts
        mode: "0644"
      run_once: true
YML
printf '[defaults]\ninterpreter_python = auto_silent\n' > ansible.cfg
ansible-playbook -i hosts.ini hosts.yml | grep -E '^(changed|ok)'
cat /home/learner/cluster-hosts
changed: [app-c]
# BEGIN app cluster (managed by Ansible)
10.0.1.10 app-a
10.0.1.11 app-b
10.0.1.12 app-c
# END app cluster

Exercise 4: Lint to production profile

Topics: ansible-lint, Collections & FQCNs, Conditionals

Make this playbook pass ansible-lint with exit code 0, and make it still print debug enabled when run with -e app_debug=true:

bash · try it yourself
cat > debug.yml <<'YML'
- hosts: localhost
  gather_facts: false
  tasks:
    - debug: msg="debug enabled"
      when: app_debug
YML
ansible-lint debug.yml 2>&1 | grep -E '^[a-z-]+(\[[a-z-]+\])?:'
name[play]: All plays should be named.
fqcn[action-core]: Use FQCN for builtin module actions (debug).
name[missing]: All tasks should be named.
no-free-form: Avoid using free-form when calling module actions. (debug)
Show solution

Name the play and task, use the FQCN and YAML arguments, and turn the (string) extra var into a real boolean with a default:

bash · try it yourself
cat > debug.yml <<'YML'
---
- name: Debug switch
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Report debug mode
      ansible.builtin.debug:
        msg: debug enabled
      when: app_debug | default(false) | bool
YML
ansible-lint debug.yml >/dev/null 2>&1; echo "ansible-lint exit code: $?"
ansible-playbook debug.yml -e app_debug=true | grep '"msg"'
ansible-playbook debug.yml | grep -c '"msg"'
ansible-lint exit code: 0
    "msg": "debug enabled"
0

Test yourself

Which change made Exercise 1's handler stop firing on the second run?

  1. ignore_errors: true
  2. creates: on the command
  3. Removing notify
  4. --check

In Exercise 2, why did moving the variable to defaults/ fix it?

  1. defaults are encrypted
  2. Role defaults have the lowest precedence, so group_vars override them
  3. defaults run first
  4. vars/ is ignored