Ansible

RHCE Practice Questions: Hands-On EX294 Tasks with Solutions

A few days ago I published a set of RHCSA practice questions for this site, and the first request that followed was for the engineer-level sibling. The Red Hat® Certified Engineer (RHCE) credential rides on one performance-based test these days, EX294, which Red Hat now lists as the Red Hat Certified Advanced System Administrator in Ansible exam. Nothing about that format rewards memorized module flags: you sit at real machines, you build real services, and the grading checks the machines. So I built a small Ansible lab, worked through every task family the certification names, and kept the output from each run. (This guide is not affiliated with or endorsed by Red Hat.)

Original content from computingforgeeks.com - post 186993

What you get here is that run, written up as practice tasks with solutions. Each task states the goal the way a proctor would, shows the playbook or command I used, and shows the real output from the run, failures included. I ran everything in November 2026 on box1.lab.example, a Rocky Linux 9 control node running ansible-core 2.14 with two managed nodes behind it, and every prompt comes from that box.

Setting up the control node

I kept the lab deliberately small, because the certification evaluates configuration work rather than fleet size. My inventory held three names:

  • box1.lab.example: the control node, ansible-core from the AppStream repository
  • box2.lab.example: a managed node carrying the web tier
  • box3.lab.example: a managed node for the database, with a spare 5 GB disk attached

The first file I wrote was ansible.cfg, and it deserves to exist before anything else, because every later command reads it. Mine turns on privilege escalation, points at the local inventory, and leaves host key checking on. Guides love to tell you to switch that last one off, and I don’t, because a controller that silently trusts any key hides exactly the connection errors you need to see while you’re learning. Why keep it on when every tutorial says otherwise? Because the errors it surfaces are the ones the graded machines will hand you, and meeting them in a lab costs nothing. One more thing the file assumes: my lab user’s sudo is passwordless, so become never gets asked for a password. If yours prompts, every privileged task in this set stops cold until you give the account NOPASSWD sudo or set a become password.

vim /home/philip/ansible-lab/ansible.cfg

Add the following configuration:

[defaults]
inventory = ./inventory
remote_user = philip
host_key_checking = True
forks = 5

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

My inventory splits the two managed nodes into a web group and a db group, with a lab parent on top. Grouping looks like bookkeeping until you notice how the rest of the certification leans on it, since every later playbook targets a role rather than a hostname. Write it once, correctly, and the plays stay honest.

vim /home/philip/ansible-lab/inventory

Put the groups in as plain host patterns.

[web]
box2.lab.example

[db]
box3.lab.example

[lab:children]
web
db

To confirm the controller picked the file up, ask it what changed. A fresh project reports everything, because all of it differs from the defaults, and each line names the file it came from.

ansible-config dump --only-changed

The output is compact because a fresh project only differs from the defaults in a handful of places. On the lab it reads like this.

CONFIG_FILE() = /home/philip/ansible-lab/ansible.cfg
DEFAULT_BECOME(/home/philip/ansible-lab/ansible.cfg) = True
DEFAULT_BECOME_ASK_PASS(/home/philip/ansible-lab/ansible.cfg) = False
DEFAULT_BECOME_METHOD(/home/philip/ansible-lab/ansible.cfg) = sudo
DEFAULT_BECOME_USER(/home/philip/ansible-lab/ansible.cfg) = root
DEFAULT_FORKS(/home/philip/ansible-lab/ansible.cfg) = 5
DEFAULT_HOST_LIST(/home/philip/ansible-lab/ansible.cfg) = ['/home/philip/ansible-lab/inventory']
DEFAULT_REMOTE_USER(/home/philip/ansible-lab/ansible.cfg) = philip
HOST_KEY_CHECKING(/home/philip/ansible-lab/ansible.cfg) = True

I keep a capture of this moment, because it shows the file and its effect in one frame. That pairing is the fastest config check I know, so it has become part of the routine. Thirty seconds here saves a longer hunt later.

ansible.cfg inventory and privilege escalation settings plus ansible-config dump output on the Rocky 9 control node

I use that dump as my first checkpoint whenever a setting refuses to apply. If a directive is missing from the output, it either has a typo in the name or it sat in the wrong section, and both mistakes are silent until you look. Thirty seconds with this command replaces an hour of wondering why become never fires.

Fixing the first connection errors

My first ping to the managed nodes failed for a boring reason. The control node had no idea what box2.lab.example meant, so before blaming Ansible I ran the ping anyway to let the error say so.

ansible lab -m ping

Both hosts came back unreachable with the same complaint, and this message always means name resolution, never Ansible.

Error: “Failed to connect to the host via ssh: ssh: Could not resolve hostname”

Both hosts printed the same shape of failure. The msg line is the part to read. The rest of the dict is noise at this stage.

box2.lab.example | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname box2.lab.example: Name or service not known",
    "unreachable": true
}
box3.lab.example | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname box3.lab.example: Name or service not known",
    "unreachable": true
}

Cloud images ship a minimal /etc/hosts, so the names needed real entries. Since the file belongs to the system, the editor call needs sudo.

sudo vim /etc/hosts

One line per node, with a short alias at the end for interactive use.

10.128.0.14     box2.lab.example box2
10.128.0.15     box3.lab.example box3

The next ping got further and failed differently, which is how these things go. Now SSH knew where to go but didn’t trust the host on the other end, and that failure has a fixed recovery order I now run without thinking.

  1. Resolve the names, one /etc/hosts line per node
  2. Accept each host key once through a normal ssh login
  3. Install the controller key with ssh-copy-id
  4. Ping again, expect pong from every host
  5. Run one become command and check for uid=0

The same exchange, this time as a capture. It pairs the command with the root context it produced.

ansible ping showing the could not resolve hostname and host key verification failed errors on the lab nodes

The capture caught both nodes in that broken state, before any key exchange worked. So the ping was not the only thing failing there. Fixing the host entries first and the key check second is the order the errors themselves suggest.

Error: “Failed to connect to the host via ssh: Host key verification failed.”

The second error came from the same ping, one step further along.

box2.lab.example | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Host key verification failed.",
    "unreachable": true
}

Ansible runs SSH non-interactively, so the usual “type yes to accept the key” prompt never appears and the connection dies instead. The fix is to accept each host key once through an interactive login, which also gives me the chance to install my key in the same step. I distribute the key with ssh-copy-id to both managed nodes.

ssh-copy-id [email protected]
ssh-copy-id [email protected]

One key lands on each node, and the output reminds you how to test it by hand.

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/philip/.ssh/id_ed25519.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with: "ssh -i /home/philip/.ssh/id_ed25519 -o 'StrictHostKeyChecking=accept-new' '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

With keys in place and both hostnames resolvable, the same ping finally returns what a connection test should, a plain pong from each node.

box3.lab.example | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
box2.lab.example | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

The capture pairs the key install with the pong that followed it.

ssh-copy-id installing the control node key on both managed hosts followed by a successful ansible ping

The last piece of the wiring is proving that privilege escalation works, because every package and file task later runs through it. A one-liner module call through -b settles it.

ansible web -m command -a id -b

The uid line is the whole answer. Root context with the SELinux labels of an unconfined domain, which is exactly what dnf and useradd will run under later.

box2.lab.example | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

From here on, every task in this set assumes that root path works. The wiring stage is done, so the rest of the article runs plays.

Running the first real playbook

The classic opener task is package plus service: install httpd, then start it and enable it at boot. It looks trivial, and that’s the point, because the recap teaches you what changed versus what merely ran. Here’s web.yml. Two tasks, both fully qualified, which is how I write every module reference.

vim /home/philip/ansible-lab/web.yml

The file ran on box2 as written. What the playbook engine saw looks like this.

---
- name: Install and start the web service
  hosts: web
  tasks:
    - name: Install the httpd package
      ansible.builtin.dnf:
        name: httpd
        state: present

    - name: Start and enable httpd
      ansible.builtin.service:
        name: httpd
        state: started
        enabled: true

Run it against the web group only, since the database node has no business running Apache.

ansible-playbook web.yml

Both tasks report changed on the first run, and the recap counts two changes against three ok results.

PLAY [Install and start the web service] ***************************************

TASK [Gathering Facts] *********************************************************
ok: [box2.lab.example]

TASK [Install the httpd package] ***********************************************
changed: [box2.lab.example]

TASK [Start and enable httpd] **************************************************
changed: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The run as the console showed it. Nothing fancy, just the two changed tasks and the recap.

first web playbook run installing httpd and starting the service on the managed node

Running it a second time is the habit worth building, because the recap that comes back with changed=0 is your proof the playbook is idempotent. Graders read those numbers the same way: a machine that reports no changes on a rerun is a machine configured to converge rather than one that was merely touched. On a graded box the habit costs seconds, and it catches half of the drift problems before anyone checks your work.

Opening the firewall without a lockout

Before I wrote any firewall task, I checked what curl saw from the control node, and the answer surprised me. The test page loaded immediately, so the zone in front of httpd was accepting port 80 traffic from outside. Which zone was the interface in before the move? That I never captured, and cloud images differ here, so check yours with firewall-cmd --get-active-zones before you plan around an assumption. That changed my plan, and I’d keep this order on any machine I couldn’t afford to lose.

  1. Prove the page answers before touching the firewall
  2. Move the interface into the public zone and watch the page stop answering
  3. Open the http service deliberately and watch it come back
  4. Keep console access ready the whole time, because that’s the recovery path

That order matters more than the commands, since it proves the zone actually governs traffic and rehearses the recovery path in a lab instead of on a machine you cannot reach. If you lock yourself out on a remote host, the out-of-band console is the way back in, and having checked it exists before the zone change is the difference between a five-minute incident and a rebuild.

I wrote the firewall task first anyway, and got stopped by something I should have predicted on a RHEL-family controller.

ansible-playbook firewall.yml

The run died before any task executed, because module resolution happens at parse time. The error text points straight at the missing collection. So the playbook itself was never the problem.

Error: “couldn’t resolve module/action ‘ansible.posix.firewalld’”

The error arrived before any task ran, because module resolution happens before the play starts. So the console showed a parser-style failure rather than a red task line. That ordering is worth knowing, since it tells you the problem is in your tooling and not in your hosts.

ansible playbook failing with could not resolve module/action ansible.posix.firewalld error message

The text of that error, exactly as the run printed it.

ERROR! couldn't resolve module/action 'ansible.posix.firewalld'. This often indicates a misspelling, missing collection, or incorrect module path.

The error appears to be in '/home/philip/ansible-lab/firewall.yml': line 5, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
    - name: Allow the http service in the public zone
      ^ here

A RHEL-family ansible-core install ships almost nothing beyond ansible.builtin, and the firewalld module lives in ansible.posix. The module name was never wrong; the collection simply wasn’t installed. Installing it is one command, and the Ansible collections guide documents the whole mechanism.

ansible-galaxy collection install ansible.posix

Galaxy resolves, downloads and unpacks the collection into your user directory, and prints the version it landed on.

Installing 'ansible.posix:2.2.2' to '/home/philip/.ansible/collections/ansible_collections/ansible/posix'
ansible.posix:2.2.2 was installed successfully

The install as it ran on box1. One command, one collection, nothing else to it.

ansible-galaxy collection install ansible.posix installing version 2.2.2 from Ansible Galaxy

The zone change itself deserves its own task on every managed node, because I want the interface assignment consistent lab-wide. Here’s zone.yml. The permanent flag writes the rule to disk and immediate applies it to the running firewall, and you generally want both.

vim /home/philip/ansible-lab/zone.yml

The file that ran is below. It stayed this short all the way through.

---
- name: Move the lab nodes into the public zone
  hosts: lab
  tasks:
    - name: Assign eth0 to the public zone
      ansible.posix.firewalld:
        zone: public
        interface: eth0
        permanent: true
        immediate: true
        state: enabled

After that run, the same curl from the control node stopped working, and the exit code tells you which class of failure it is. Exit 7 means the connection itself was refused or timed out, not that the page was wrong.

curl exit: 7

Only then did I run the firewall playbook for real, opening the http service in the public zone where the interfaces now live.

---
- name: Publish the web service through firewalld
  hosts: web
  tasks:
    - name: Allow the http service in the public zone
      ansible.posix.firewalld:
        service: http
        zone: public
        permanent: true
        immediate: true
        state: enabled

One changed task, one warning about the collection’s declared support range, and the page answered again. The title line at the end of this capture is the curl result proving it.

[WARNING]: Collection ansible.posix does not support Ansible version 2.14.18

PLAY [Publish the web service through firewalld] *******************************

TASK [Gathering Facts] *********************************************************
ok: [box2.lab.example]

TASK [Allow the http service in the public zone] *******************************
changed: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

<title>HTTP Server Test Page powered by: Rocky Linux</title>

The whole sequence, from the curl timeout to the page title, ended up in one capture. I would rather keep that story together than split it, because the timing is the evidence. It shows the zone change taking effect within seconds.

firewalld playbook run moving eth0 to the public zone followed by curl timing out and then succeeding after the http service is opened

If you’re doing this on Ubuntu, the module idea is the same but the backend is ufw, and my firewalld on Ubuntu guide covers the install side of that path. On the RHEL family, keep permanent and immediate together in your head. Writing only one of them is the classic way to end up with a rule that vanishes at reboot, or a rule that never takes effect now, and both look like success while you’re staring at the playbook.

Creating users with hashed passwords

My first attempt at a user task failed before it ran a single line, and the error deserves to be shown in full, because almost everyone hits it once. I had written a Jinja expression with nested double quotes inside a double-quoted YAML value, and the parser couldn’t even read the file.

Error: “Syntax Error while loading YAML. did not find expected key”

The parser stopped before any play loaded, and the console printed both halves of its confusion. Neither half is useful on its own. The full text is below.

ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
  did not find expected key

The error appears to be in '/home/philip/ansible-lab/users.yml': line 22, column 24, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

        shell: /bin/bash
        password: "{{ "redhat" | password_hash("sha512") }}"
                       ^ here

The rule that fixes it is short enough to memorize. Inside a double-quoted YAML value, Jinja filters and their arguments go in single quotes, so the corrected line reads password: "{{ 'redhat' | password_hash('sha512') }}". With that one change the file loaded, and the working version below loops over a variable list so the same two tasks create both accounts.

vim /home/philip/ansible-lab/users.yml

Groups first, then users who belong to them, with the password hashed on the controller so a plaintext value never travels.

---
- name: Create the lab accounts
  hosts: lab
  vars:
    lab_users:
      - name: deploy
        group: webteam
      - name: audit
        group: auditors
  tasks:
    - name: Create the groups
      ansible.builtin.group:
        name: "{{ item.group }}"
        state: present
      loop: "{{ lab_users }}"

    - name: Create the users with a hashed password
      ansible.builtin.user:
        name: "{{ item.name }}"
        group: "{{ item.group }}"
        shell: /bin/bash
        password: "{{ 'redhat' | password_hash('sha512') }}"
        state: present
      loop: "{{ lab_users }}"

The run finished clean on both nodes, but read the warnings before celebrating. The deprecation warning says the controller’s crypt module is going away, and the fix it names is installing passlib on the control node. Hashing happens on the controller, not on the managed nodes, so that’s a box1 problem and not an inventory problem.

TASK [Create the users with a hashed password] *********************************
[DEPRECATION WARNING]: Encryption using the Python crypt module is deprecated.
The Python crypt module is deprecated and will be removed from Python 3.13.
Install the passlib library for continued encryption functionality. This
feature will be removed in version 2.17. Deprecation warnings can be disabled
by setting deprecation_warnings=False in ansible.cfg.
changed: [box3.lab.example] => (item={'name': 'deploy', 'group': 'webteam'})
changed: [box2.lab.example] => (item={'name': 'deploy', 'group': 'webteam'})
changed: [box3.lab.example] => (item={'name': 'audit', 'group': 'auditors'})
changed: [box2.lab.example] => (item={'name': 'audit', 'group': 'auditors'})

PLAY RECAP *********************************************************************
box2.lab.example           : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
box3.lab.example           : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Verification is two read-only commands on a managed node.

id deploy
getent passwd audit

Both accounts exist with the right groups, and the shell matches what the playbook asked for.

uid=1003(deploy) gid=1008(webteam) groups=1008(webteam)
audit:x:1004:1009::/home/audit:/bin/bash

That closes the user task set. Accounts are the cheapest thing to automate, so the next questions move to content. Templating is where the exam leans hardest, because it forces facts, filters and files to cooperate.

Deploying a page from a template

Static file copies are fine, but the certification wants you comfortable with Jinja2 templates that pull live facts. My index page stamps each host with its own name, kernel and address, so one template serves both web nodes differently. Here’s templates/index.html.j2. The fact names come straight from the local facts gathered at the start of every play.

vim /home/philip/ansible-lab/templates/index.html.j2

The executed template reads as follows. Every value in it comes from gathered facts.

<html>
  <head><title>{{ inventory_hostname }}</title></head>
  <body>
    <h1>{{ ansible_facts["fqdn"] }}</h1>
    <p>Deployed by Ansible on the RHCE lab<br>Served by {{ ansible_facts["kernel"] }} {{ ansible_facts["kernel_version"] }}</p>
    <p>Address: {{ ansible_facts["default_ipv4"]["address"] }}</p>
  </body>
</html>

The deploy task is a single ansible.builtin.template with an explicit owner and mode, and that detail matters more than it looks, because a world-writable index page is an easy mark in any configuration review.

---
- name: Deploy the index page from a template
  hosts: web
  tasks:
    - name: Place the index page
      ansible.builtin.template:
        src: templates/index.html.j2
        dest: /var/www/html/index.html
        owner: root
        group: root
        mode: "0644"

The run put the page in place, and the tail of my capture is the curl check, showing the template rendered with this host’s own values. One early mistake of mine doesn’t appear here. My first template run rendered a cloud provider’s internal hostname instead of the lab name, because the managed nodes still carried their provider-assigned hostnames, and facts trust the hostname far more than you’d want them to. Setting the hostname properly on each node fixed the facts at the source, which always beats hiding the wrong value in the template.

PLAY [Deploy the index page from a template] ***********************************

TASK [Gathering Facts] *********************************************************
ok: [box2.lab.example]

TASK [Place the index page] ****************************************************
changed: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

    <h1>box2.lab.example</h1>
    <p>Address: 10.128.0.14</p>

If you want to go deeper on facts than one template, I have a separate walkthrough on generating a host overview from Ansible facts that plays with the same variables from the command line.

Writing conditionals with package facts

Conditions on “is the package installed” need real data, and the module for that is package_facts. It populates a dictionary of every installed package, which your when clauses can then test directly. My conditions.yml reports on httpd across the whole lab, where I already know one node has it and the other doesn’t. Two debug tasks with opposite conditions keep the output readable on both hosts.

vim /home/philip/ansible-lab/conditions.yml

The file that ran looks like this. Both conditions live in the same play so the skips stay visible.

---
- name: Report on the web package across the lab
  hosts: lab
  tasks:
    - name: Collect package facts
      ansible.builtin.package_facts:
        manager: auto

    - name: Show the installed httpd version
      ansible.builtin.debug:
        msg: "httpd {{ ansible_facts['packages']['httpd'][0].version }} is installed"
      when: "'httpd' in ansible_facts.packages"

    - name: Say when httpd is missing
      ansible.builtin.debug:
        msg: "no httpd on this node"
      when: "'httpd' not in ansible_facts.packages"

The interesting lines are the skips. Each node runs one task and skips the other, and the version number comes from the package database rather than anything I typed.

TASK [Show the installed httpd version] ****************************************
ok: [box2.lab.example] => {
    "msg": "httpd 2.4.62 is installed"
}
skipping: [box3.lab.example]

TASK [Say when httpd is missing] ***********************************************
skipping: [box2.lab.example]
ok: [box3.lab.example] => {
    "msg": "no httpd on this node"
}

Now look at the two quoting styles in the conditions, because they differ on purpose. The when line quotes its string inside the expression, since when is already a raw Jinja context, while the msg line quotes its expression inside a YAML string. Mixing those up produces the same parser error as the password task earlier, wearing different clothes, and it costs people real time on graded machines.

Handling failures with block, rescue and always

Error handling is where a lot of candidates lose time, and block is the whole tool. I wrote a play that asks systemd about nginx, a service this lab doesn’t run, purely to walk the failure path on purpose. The rescue task then explains what happened, and the always task proves the tier still serves traffic. Here’s block.yml. The changed_when flag on the check matters, because a read-only command should never claim it changed anything.

vim /home/philip/ansible-lab/block.yml

What ran on box2 is below. The three sections sit side by side in one play.

---
- name: Demonstrate error handling on the web tier
  hosts: web
  tasks:
    - name: Check a service that is not part of the lab
      block:
        - name: Ask systemd about nginx
          ansible.builtin.command: systemctl is-active nginx
          register: nginx_state
          changed_when: false
        - name: Report the nginx state
          ansible.builtin.debug:
            msg: "nginx is {{ nginx_state.stdout }}"
      rescue:
        - name: Say what happened instead
          ansible.builtin.debug:
            msg: "nginx is not on {{ inventory_hostname }}, the tier runs httpd"
      always:
        - name: Confirm the web tier still answers
          ansible.builtin.uri:
            url: "http://{{ inventory_hostname }}/"
            status_code: 200

A non-zero return code from systemctl is-active is what trips the block, exit 3 for a service that exists but is inactive. The rescue runs, the always runs, and the recap records the failure honestly with rescued=1.

TASK [Ask systemd about nginx] *************************************************
fatal: [box2.lab.example]: FAILED! => {"changed": false, "cmd": ["systemctl", "is-active", "nginx"], "delta": "0:00:00.014121", "end": "2026-11-10 09:15:49.829131", "msg": "non-zero return code", "rc": 3, "start": "2026-11-10 09:15:49.815010", "stderr": "", "stderr_lines": [], "stdout": "inactive", "stdout_lines": ["inactive"]}

TASK [Say what happened instead] ***********************************************
ok: [box2.lab.example] => {
    "msg": "nginx is not on box2.lab.example, the tier runs httpd"
}

TASK [Confirm the web tier still answers] **************************************
ok: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=1    ignored=0

The same run, on screen. The recap line at the bottom is the part worth reading.

block rescue and always playbook run showing the nginx failure, the rescue message and the uri check on box2

A rescued failure is a handled failure, but it stays visible in the recap, so anyone reading your machines can see exactly which tasks were expected to fail. That visibility cuts both ways, and I’d argue it should. Rescue paths that quietly swallow real errors are worse than a play failing loudly, because the loud failure at least gets investigated.

Making restarts idempotent with handlers

Handlers are the difference between a service that restarts on every run and one that restarts only when its configuration actually changed. The pattern is one notify line on the task that can change, and one handler keyed by the same name. Here’s handlers.yml. The handler sits at play level, not task level, which is a common placement mistake.

vim /home/philip/ansible-lab/handlers.yml

The executed file follows. One task, one handler, nothing else.

---
- name: Update the index page and restart httpd when it changes
  hosts: web
  tasks:
    - name: Place the index page
      ansible.builtin.template:
        src: templates/index.html.j2
        dest: /var/www/html/index.html
        owner: root
        group: root
        mode: "0644"
      notify: Restart httpd

  handlers:
    - name: Restart httpd
      ansible.builtin.service:
        name: httpd
        state: restarted

I ran it twice with a real template edit in between, and the pair of recaps is the lesson. On the first run the page changed and the handler fired at the end of the play.

== first run (template content changes) ==

TASK [Place the index page] ****************************************************
changed: [box2.lab.example]

RUNNING HANDLER [Restart httpd] ************************************************
changed: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

== second run (nothing changed) ==

TASK [Place the index page] ****************************************************
ok: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

On the second run the page was already correct, so no notification was queued and no handler ran at all. Why didn’t it fire? Because handlers only run when a task that notifies them actually reports a change, and nothing changed. That pairing of a changed recap and an unchanged one is the cleanest demonstration of idempotence you can capture, and it takes two minutes to reproduce in your own lab. If your handler fires on a run where nothing changed, the notify is attached to the wrong task, and the recap will tell you so.

Scheduling cron jobs and archiving configs

Scheduled jobs are a quiet staple of configuration work, and the cron module writes them without you ever touching crontab -e. The name field is the anchor, because it’s how Ansible finds and later updates the entry, so make it specific. Here’s cron.yml. One task, with a special_time instead of five time fields.

vim /home/philip/ansible-lab/cron.yml

The executed task file reads like this. A single cron task carries the whole schedule.

---
- name: Schedule a job on every managed node
  hosts: lab
  tasks:
    - name: Rotate the httpd logs every day
      ansible.builtin.cron:
        name: rotate the lab httpd logs daily
        special_time: daily
        user: root
        job: "/usr/sbin/logrotate /etc/logrotate.d/httpd >/dev/null 2>&1"

Reading root’s crontab on a managed node afterwards shows the entry with the marker comment that identifies it as Ansible-managed.

#Ansible: rotate the lab httpd logs daily
@daily /usr/sbin/logrotate /etc/logrotate.d/httpd >/dev/null 2>&1

Next I wanted a timestamped backup of the web configuration, and community.general.archive does it. This was my second collection lesson of the day, because the same “couldn’t resolve module/action” error came back for the archive module, and the fix was the same idea with a different collection name.

ERROR! couldn't resolve module/action 'community.general.archive'. This often indicates a misspelling, missing collection, or incorrect module path.

The error appears to be in '/home/philip/ansible-lab/archive.yml': line 5, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

Once installed, the playbook ran. Note the destination uses the date_time fact, so every run produces a differently named file instead of silently overwriting yesterday’s backup.

---
- name: Archive the web configuration
  hosts: web
  tasks:
    - name: Bundle /etc/httpd into a timestamped tarball
      community.general.archive:
        path: /etc/httpd
        dest: "/root/httpd-config-{{ ansible_facts['date_time']['date'] }}.tar.gz"
        format: gz

A directory listing on the managed node confirms the tarball landed with a sane size and today’s date in the name.

-rw-r--r--. 1 root root 14K Nov 10 09:17 /root/httpd-config-2026-11-10.tar.gz

That closes the archiving set and wraps up the single-module questions. Storage is next, and it chains more modules than anything else in this article. So the play recap lines matter more there than anywhere else.

Building an LVM stack on a spare disk

Storage tasks chain five modules in a row, and any one of them can stop the play, which makes this the best exercise I know for reading a play recap carefully. On box3 I had a spare 5 GB disk at /dev/sdb, and the goal was a volume group, a full-size logical volume, XFS on it, and a persistent mount. Here’s lvm.yml. Partition, volume group, logical volume, filesystem, mount, in that order, because each step depends on the last.

vim /home/philip/ansible-lab/lvm.yml

The full task chain is below. Five modules run in order, and each one depends on the step before it. So a failure anywhere leaves the rest of the chain unexecuted, which is why the recap matters so much in this section.

---
- name: Put a new logical volume on the spare disk
  hosts: db
  tasks:
    - name: Create a partition on the spare disk
      community.general.parted:
        device: /dev/sdb
        number: 1
        state: present
        part_start: 1MiB
        part_end: 100%

    - name: Create the volume group
      community.general.lvg:
        vg: datavg
        pvs: /dev/sdb1
        state: present

    - name: Create the logical volume
      community.general.lvol:
        vg: datavg
        lv: datalv
        size: 100%FREE
        state: present

    - name: Put XFS on the volume
      community.general.filesystem:
        fstype: xfs
        dev: /dev/datavg/datalv

    - name: Mount the volume at boot
      ansible.posix.mount:
        path: /srv/data
        src: /dev/datavg/datalv
        fstype: xfs
        state: mounted

The first run never made it to the volume group. The failure arrived earlier than I expected, and the message is below. The cause was waiting in the base image the whole time.

Error: “Failed to find required executable \”pvs\” in paths”

The first run got two tasks in and died on the volume group, because the cloud image ships without LVM userland. The error names the missing binary rather than the missing package, so you have to make the small leap from pvs to lvm2 yourself.

TASK [Create the volume group] *************************************************
fatal: [box3.lab.example]: FAILED! => {"changed": false, "msg": "Failed to find required executable \"pvs\" in paths: /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin"}

Installing lvm2 on the managed node is a one-time fix, and in the lab it was a single ad hoc module call: ansible db -m ansible.builtin.dnf -a "name=lvm2 state=present" -b. In a real project I’d make it a dnf task at the top of the playbook rather than a manual step, so the next machine doesn’t trip over the same gap. With the package present, the rerun walked all the way down the chain.

TASK [Create a partition on the spare disk] ************************************
ok: [box3.lab.example]

TASK [Create the volume group] *************************************************
changed: [box3.lab.example]

TASK [Create the logical volume] ***********************************************
changed: [box3.lab.example]

TASK [Put XFS on the volume] ***************************************************
changed: [box3.lab.example]

TASK [Mount the volume at boot] ************************************************
changed: [box3.lab.example]

PLAY RECAP *********************************************************************
box3.lab.example           : ok=6    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The run as it happened, on screen. The four changed tasks line up with the rerun recap.

LVM playbook run creating a partition, datavg volume group, datalv logical volume, XFS filesystem and the /srv/data mount on box3

The partition task reads ok on the rerun rather than changed, which is the idempotence of parted showing up exactly where you want it. Three verification commands tell the whole story, the block device tree, the mounted filesystem, and the volume group.

lsblk
findmnt /srv/data
vgs datavg

The stack lines up the way the playbook drew it, disk to partition to logical volume to mountpoint.

NAME              MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sdb                 8:16   0   5G  0 disk
└─sdb1              8:17   0   5G  0 part
  └─datavg-datalv 253:0    0   5G  0 lvm  /srv/data
TARGET    SOURCE                    FSTYPE OPTIONS
/srv/data /dev/mapper/datavg-datalv xfs    rw,relatime,seclabel,attr2,inode64,logbufs=8,logbsize=32k,noquota
  VG     #PV #LV #SN Attr   VSize VFree
  datavg   1   1   0 wz--n- 5.00g    0g

Disk, volume group, filesystem and mount all read back correctly. That closes the standalone playbooks, and the natural next step is packaging what works. So the role section reuses the exact tasks you just saw, rather than writing new ones.

Packaging the work as a role

By this point the web tier setup existed as four separate playbooks, which is exactly when the certification expects you to know roles. A role is a directory contract: tasks, handlers, templates and defaults each in their own folder, and a play that invokes the whole thing by name. Scaffolding it is one command.

ansible-galaxy init roles/webtier

The skeleton arrives with placeholder files in every directory, and I filled four of them.

  • tasks/main.yml: the dnf, template, firewalld and service tasks, moved over from web.yml and firewall.yml
  • handlers/main.yml: the httpd restart, notified by the template task
  • templates/index.html.j2: the same index page, referenced now by bare filename
  • meta/main.yml: kept minimal, since this role stays private to the lab

My task file after the move keeps its four tasks, and two details changed. Notice the template source lost its directory prefix, because role paths resolve inside the role. The notify survives the move unchanged, which is the point of the naming contract.

vim /home/philip/ansible-lab/roles/webtier/tasks/main.yml

After the move it reads like this. The role path resolution does the rest quietly.

---
- name: Install the httpd package
  ansible.builtin.dnf:
    name: httpd
    state: present

- name: Deploy the index page from the role template
  ansible.builtin.template:
    src: index.html.j2
    dest: /var/www/html/index.html
    owner: root
    group: root
    mode: "0644"
  notify: Restart httpd

- name: Publish the web service through firewalld
  ansible.posix.firewalld:
    service: http
    zone: public
    permanent: true
    immediate: true
    state: enabled

- name: Start and enable httpd
  ansible.builtin.service:
    name: httpd
    state: started
    enabled: true

The calling playbook shrinks to a name and a role, and this is the whole file, site.yml.

---
- name: The web tier role, top to bottom
  hosts: web
  roles:
    - webtier

Running it against a machine that already had everything produced the most satisfying recap of the day, five tasks, zero changes.

PLAY [The web tier role, top to bottom] ****************************************

TASK [Gathering Facts] *********************************************************
ok: [box2.lab.example]

TASK [webtier : Install the httpd package] *************************************
ok: [box2.lab.example]

TASK [webtier : Deploy the index page from the role template] ******************
ok: [box2.lab.example]

TASK [webtier : Publish the web service through firewalld] *********************
ok: [box2.lab.example]

TASK [webtier : Start and enable httpd] ****************************************
ok: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The all-ok run, on screen. Five tasks and a zero in the changed column.

site.yml running the webtier role on box2 with every task returning ok and changed equal to zero

That all-ok recap is also a regression test, and I now run it after every change to the role. If a later edit ever produces a change on a converged machine, something in the role stopped being idempotent, and you want to find that before a grader does rather than after.

Vaulting the secrets

Passwords in plaintext YAML are the one mistake that costs real points, and ansible-vault is the whole fix. I started with the variable in a plain file, encrypting the file itself rather than a single variable, because whole-file encryption is the simpler habit to keep under pressure. Here’s secret.yml before encryption. One variable, holding the password this account will get.

vim /home/philip/ansible-lab/secret.yml

The plain file first. Encryption comes right after.

web_admin_password: V4ulted!pass

Encrypting in place turns the file into a vault blob, and the header line is how you recognize one from across the room. The command needs the password file to exist first, because Vault reads the passphrase from it rather than asking. So mine started as one line, created before the encrypt step and locked down immediately.

echo 'your-vault-password' > ~/.vault-pass
chmod 600 ~/.vault-pass

With the password file in place, the encrypt step runs and the file on disk stops being readable.

ansible-vault encrypt secret.yml --vault-password-file ~/.vault-pass

The encryption run, captured on screen. The header line at the top of the result is the marker to look for.

ansible-vault encrypt protecting secret.yml and the head of the encrypted file showing the vault header

Reading it back through ansible-vault view proves the password file unlocks it, and the plaintext comes back exactly as written.

ansible-vault view secret.yml --vault-password-file ~/.vault-pass

The view command brings the plaintext back exactly as it went in.

web_admin_password: V4ulted!pass

The playbook consumes it like any vars_files member, because Vault only protects how the value is stored, not how plays read it. So nothing in the task changes when the variable arrives encrypted. Here is vault.yml as it ran.

---
- name: Create the admin account from vaulted data
  hosts: web
  vars_files:
    - secret.yml
  tasks:
    - name: Create the web admin user
      ansible.builtin.user:
        name: webadmin
        password: "{{ web_admin_password | password_hash('sha512') }}"
        shell: /bin/bash
        state: present

The playbook reads the vaulted variable like any plain one. So the failure mode when the vault password is missing is worth showing.

Error: “Attempting to decrypt but no vault secrets found”

Running it without telling Ansible where the vault password lives produces the error you’d expect, and I ran it that way on purpose to capture the wording.

ERROR! Attempting to decrypt but no vault secrets found

With --vault-password-file on the command, the same run created the account, and a read of the shadow entry on the managed node shows a salted hash rather than anything readable. I cut the hash short here on purpose, since the real line runs much longer.

TASK [Create the web admin user] ***********************************************
changed: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

webadmin:$6$tR.lPgRsB5RkqM2L$H18H82tr5QZ

The habits around vault files matter as much as the encryption itself, because a leaked password file defeats the whole exercise. So where does mine live? In the home directory with sane permissions, never inside the project. Three habits are now automatic for me.

  • Password file in the home directory, chmod 600, never inside the project
  • Password passed by file or prompt, never on the command line
  • Vaulted files named so nobody mistakes them for plain vars

Never passing the password on the command line is the one I’d underline twice. Shell history keeps everything you type, on every machine you’ll ever paste that command into, and a password file with sane permissions is the version that survives review.

Running playbooks in an execution environment

The tooling story now centers on ansible-navigator and execution environments, so I built one rather than only reading about them. An execution environment is a container image with Ansible and its dependencies baked in, described by an execution-environment.yml file. The three tools this section needs all came from the controller’s own package sources: ansible-navigator and ansible-builder from pip, and podman from dnf. Here’s mine. The Rocky container image as the base, pip-installed Ansible, and two system packages, of which the second took me two build iterations to think of.

vim /home/philip/ee-demo/execution-environment.yml

The file that built the image is below. Most of it is base image and dependencies.

---
version: 3

images:
  base_image:
    name: docker.io/library/rockylinux:9

dependencies:
  system:
    - python3-pip
    - openssh-clients
  ansible_core:
    package_pip: ansible-core
  ansible_runner:
    package_pip: ansible-runner

My first navigator run inside the freshly built image failed in a way that taught me more than the success did. The image had Ansible in it but no SSH client, so the controller inside the container couldn’t even start a connection. Why would an image need an SSH client? Because the whole controller, connection logic included, runs inside that container, and nothing about your host environment leaks in unless you bake it in.

Error: “Unable to execute ssh command line on a controller”

The message comes from inside the container, not from Ansible itself. It is short, and every word of it matters. So read it as a container problem first, and never as a playbook problem.

fatal: [box2.lab.example]: FAILED! => {"msg": "Unable to execute ssh command line on a controller due to: [Errno 2] No such file or directory: b'ssh'"}

Adding openssh-clients to the system dependencies and rebuilding with ansible-builder fixed it. The rebuild prints the podman command it runs, so you can watch the layers go back in.

ansible-builder build -t local-ee:latest

The rebuild output on box1 stayed quiet, which is what you want from a layer build.

File context/_build/bindep.txt had modifications and will be rewritten
Running command:
  podman build -f context/Containerfile -t local-ee:latest context
Complete! The build context can be found at: /home/philip/ee-demo/context

Listing what navigator can see now shows the two stock images it pulled plus mine, built minutes ago. The localhost/local-ee entry at the bottom is the one to run against.

ansible-navigator images --mode stdout

Three images come back on the lab.

- created: 4 years ago
  full_name: quay.io/ansible/ansible-runner:latest
  image_id: bec0dc171168
- created: 2 years ago
  full_name: ghcr.io/ansible/creator-ee:v0.22.0
  image_id: 4405e824c556
- created: 11 minutes ago
  full_name: localhost/local-ee:latest
  image_id: 55c5dbf89e28

The same vault playbook that ran on the host then ran inside the container, pointed at the execution environment by name. The recap is navigator’s own, with the color codes stripped for the page.

ansible-navigator run vault.yml --execution-environment-image local-ee:latest --mode stdout --vault-password-file ~/.vault-pass

The run inside the container, on screen. The recap at the bottom belongs to navigator.

ansible-navigator running the vault playbook inside the locally built local-ee execution environment

The text output follows, with the color codes stripped for the page.

Identity added: /home/philip/.ssh/id_ed25519 ([email protected])

TASK [Gathering Facts] *********************************************************
ok: [box2.lab.example]

TASK [Create the web admin user] ***********************************************
changed: [box2.lab.example]

PLAY RECAP *********************************************************************
box2.lab.example           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Notice what the image had to contain for that to work. The SSH client had to be there so the container could reach the managed nodes, and nothing about my host environment leaked in beyond the mounted project directory. That isolation is exactly why the tooling moved this way, and practicing inside it is worth the build time. The same role-driven pattern reaches beyond Linux hosts too, and my guide on automating Windows Server administration with Ansible shows the far end of that reach.

Proving the work survives a reboot

The certification page says configurations must persist after reboot without intervention, and that sentence is the whole grading philosophy: the machine gets checked, not your transcript. So I closed the lab by rebooting both managed nodes through Ansible itself and re-verifying everything. How do you prove the work survived? You check each subsystem again, which is exactly what the grading does. The reboot module handles the wait for you, and both nodes came back in about a minute.

ansible lab -m ansible.builtin.reboot -b

The elapsed times are measured by the module, which stays connected until the host returns.

box2.lab.example | CHANGED => {
    "changed": true,
    "elapsed": 52,
    "rebooted": true
}
box3.lab.example | CHANGED => {
    "changed": true,
    "elapsed": 51,
    "rebooted": true
}

Then five checks, one per subsystem the lab touched. Every line in the verification run answers a question a grader could ask about the machines.

  1. httpd, active again after the restart
  2. firewalld, the http service still in the public zone
  3. the index page, still the templated one with the kernel string
  4. the mount, datalv back on /srv/data
  5. cron, the Ansible-managed logrotate entry intact
== httpd after reboot ==
box2.lab.example | CHANGED | rc=0 >>
active
== firewall after reboot ==
cockpit dhcpv6-client http ssh
== index page after reboot ==
    <h1>box2.lab.example</h1>
    <p>Deployed by Ansible on the RHCE lab<br>Served by 5.14.0-687.59.1.el9_8.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Oct 21 13:47:53 UTC 2026</p>
== mount after reboot ==
TARGET    SOURCE                    FSTYPE OPTIONS
/srv/data /dev/mapper/datavg-datalv xfs    rw,relatime,seclabel,attr2,inode64,logbufs=8,logbsize=32k,noquota
== cron after reboot ==
@daily /usr/sbin/logrotate /etc/logrotate.d/httpd >/dev/null 2>&1

The five checks as they ran. Each one maps to a subsystem the lab touched.

post reboot verification showing httpd active, firewalld zone list, the index page, the mounted datalv volume and the cron entry on the managed nodes

Two lines in that capture deserve a second look. The firewall listing shows http still present alongside the zone’s defaults, which is the permanent flag doing its job across the restart. And the index page is still the templated one with the kernel string, which tells you the template, its ownership and its mode all survived. Anything you cannot show with a check like that is a configuration you only believe you made.

What I still don’t know

Writing the tasks down surfaced a few questions my lab couldn’t settle, and I’d rather list them than pretend they’re answered.

  • How the real grading weighs partial credit, for example a service that runs but wasn’t enabled, is not something my checks can mirror
  • Whether the grading environment ships passlib for the password_hash filter, since my controller only warned about its absence
  • How the stock execution environment Red Hat provides differs from the one I built, especially in preinstalled collections
  • Whether vault password handling there is file based or prompt based, which changes the muscle memory you practice

If you’re building a study plan around this, pair the tasks with a good book: my roundup of RHCSA and RHCE study books covers the titles I’d keep on the desk. And if the RHCE path is a step too far today, the RHCSA practice questions run the same lab-notes format one level down, with the CCNA practice questions available for readers on the networking side of the house. Whichever you pick, build the machines and type the tasks yourself, because the one thing this format proves is that the output never lies about what you ran.

Keep reading

OpenCode CLI Cheat Sheet: Commands, Sessions and Fixes (PDF) AI OpenCode CLI Cheat Sheet: Commands, Sessions and Fixes (PDF) Best Mini PC for Home Assistant: 4 Picks for HAOS and Proxmox Automation Best Mini PC for Home Assistant: 4 Picks for HAOS and Proxmox Patch PHP2Shell on RHEL, Rocky Linux and AlmaLinux 10 / 9 / 8 AlmaLinux Patch PHP2Shell on RHEL, Rocky Linux and AlmaLinux 10 / 9 / 8 Best Energy-Monitoring Smart Plugs for a Home Assistant Homelab Automation Best Energy-Monitoring Smart Plugs for a Home Assistant Homelab Patch PHP CVE-2026-115560 on RHEL, Rocky Linux and AlmaLinux AlmaLinux Patch PHP CVE-2026-115560 on RHEL, Rocky Linux and AlmaLinux Configure Chrony NTP Server on RHEL/Alma/Rocky 9|8 CentOS Configure Chrony NTP Server on RHEL/Alma/Rocky 9|8

Leave a Comment

Press ESC to close