← RHCE in Ansible: automation and operations
09 / 23 · 120 MIN

Executable rehearsal: scope, state and limits

Build reproducible evidence without mistaking local aliases for independent systems.

Lab contract

An APS team prepares two reconciliation workers. The change request requires evidence of target selection and modified files. Before rehearsal, write three criteria: each worker has its own identity in the file; an unchanged repeat does not activate configuration again; an invalid proposal preserves previous state.

These criteria make concrete effects observable. Exit code zero without inspecting the destination does not answer all three. This course lab uses two inventory names connected through connection=local to one machine.

Each name has a separate directory. This arrangement studies per-host execution but does not prove machine isolation, SSH access or resilience.

Prepare and execute

The content/labs/rhce-execution directory contains playbooks, template, validator and run.py. Create an isolated Python environment and install ansible-core 2.16.14 to reproduce the recorded execution version. Then invoke run.py with --ansible-bin pointing to ansible-playbook and --output naming the intended report.

The runner creates a temporary inventory, pins the interpreter and supplies lab_root through extra vars. The selection rehearsal uses --list-hosts with --limit worker_a and confirms worker_b is absent. Only then does it execute both targets.

The code below is the runner that generates this inventory; supply the actual ansible-playbook path in your environment.

Identity and observation

Compare the bytes of both worker.conf files: their worker fields should differ. Compare activation logs too, not just the recap. If both wrote to one path, two per-host results could conceal replacement of the same file.

In a real project, also record the mapping between alias, address and role. A task delegated to the controller may still be invoked by several hosts in parallel. For a shared record, choose one aggregation or explicit serialization suited to the requirement; changing delegate_to alone does not prevent concurrency. The lab does not force a random race and claim it has been fixed.

Acceptance and transfer to RHEL

The report identifies the Ansible version, operating system, file hashes and executed checks. Do not use it as reboot or systemd service evidence: neither behavior is exercised here. For the next phase, apply the same contract to disposable RHEL machines with operational access identities.

Add checks of service behavior, persistence and actual permissions. Give the RUN team the command, version and expected results so it can repeat the rehearsal without the author’s laptop or personal account.

Resuming requires reconstructing the entry contract

An APS team interrupted a play after collecting the approved port and wants to save time by starting directly at validation. In the lab, the full run sets approved_port=8443 using set_fact; a fresh process started with --start-at-task="Consume prepared port" skips that preparation and fails because the variable is undefined.

Resuming at a task name does not restore the previous process’s memory. Identify the data and state required at that point, check whether they remain valid and decide whether preparation should run again. Do not introduce persistent caching merely to conceal an undocumented dependency.

Static and dynamic tasks create another boundary: Child marker inside import_tasks was reachable, while inside include_tasks it was not. On this core 2.19.0 runtime, the dynamic attempt exited zero and wrote No matching task to stderr. A pipeline needs evidence of required tasks and effects even when its command exits successfully.

Retain the command, authorized inputs and selection evidence for later investigation.

Controlled interaction without losing acceptance

--step helps observe execution decisions during rehearsal. In the interactive exercise, n at the first task skips the first marker; y at the following tasks runs only the second and third. Final exit zero does not assign an outcome to the omitted task.

In another trial, c at the first prompt ends interaction and allows all three markers to run, subject to normal task rules. Do not confuse c with cancellation or check mode. Before using these commands in a real window, prepare a reentry plan: required prerequisites, checks that cannot be omitted and how to recognize partial effects.

In a fictional middleware case, the port was configured but its consumer test never ran; resumption should confirm actual configuration and perform pending acceptance. Manual terminal confirmation does not replace change authorization. For an unattended pipeline, encode explicit inputs and completion criteria instead of a response sequence designed to conceal unexpected prompts.

Repeat probes with observable bounds

The lab uses a counter program to distinguish actual invocations from recap messages. The first probe returns rc=0 only on its third invocation. until evaluates the registered result and stops retrying once its condition is met. Another probe always returns rc=0, but ready becomes true only on the third run; that contract requires checking JSON because program success does not mean functional readiness.

Combining loop and until gives alpha two invocations and beta three, totaling five. The results list retains each item’s information. The pinned version has an important boundary observation: retries:2 with permanent failure produced three actual invocations, while the final result recorded attempts:2 and failed:true.

Retain the counter rather than inferring effect counts solely from that field. Compare current documentation with runtime evidence at boundaries. On this core, retries also repeated a failure without explicit until, behavior documented from 2.16.

Define interval, success condition, time budget and failure handling; delay:0 makes this experiment quick and is not a recommendation for production probes.

Handle the complete asynchronous job lifecycle

With async:40 and poll:0, Ansible returns an identifier before the program finishes. A runner-controlled gate file prevents premature completion in the experiment. Only after opening that gate and querying async_status are finished:true, rc:0 and the output file observed.

With positive polling, execution waits for the result before the next task. Launch and outcome require separate records: another job launches successfully, writes a file and exits rc=7; later observation retains failure. That file may represent a partial effect.

Clearing the cache with mode:cleanup does not cancel the process: the experiment removes its record while the job is gated, releases it and observes completed; the wrapper even recreates the record. The team should define cancellation using the mechanism appropriate for the process and retain observation until state is known.

In core 2.19.0, started and finished are booleans, making a validator expecting the string "1" incompatible. The runner completes all synthetic jobs and clears their records without touching other operations’ jobs.

Separate observation from submission and argument handling

A second program appends a line before failing. Retrying eventually succeeds, but the file contains two lines. This exercise illustrates the difference between repeating a read and repeating an instruction with effects.

In a fictional financial integration, a timeout after submission does not prove the recipient rejected the operation. Idempotent identity, status queries and reconciliation need an application protocol; increasing retries supplies none of these guarantees.

The exact command also belongs in evidence. The trial uses argv to keep DR label as a single argument despite its space. However, argv does not make every input literal: with DR_EXEC_TOKEN=PUBLIC-DUMMY, argument $DR_EXEC_TOKEN expands by default in the exercised runtime.

With expand_argument_vars:false, the program receives the literal token. This Python expansion does not mean command interprets pipes or redirects like a shell. Prefer clear argument boundaries and declare when expansion is intended.

All lab values are public and synthetic; do not use real tokens to learn command inspection.

Guided exercise and RUN handover

Open content/labs/rhce-playbook-execution/run.py. In an isolated Python environment with ansible-core 2.19.0, run python3 run.py --ansible-bin /path/venv/bin/ansible-playbook --output-dir /path/fresh-trial. The output directory must be new; it retains inventory, configuration, synthetic programs and results.

The runner sets temporary paths, async cache and interpreter and drives --step interaction through a PTY. Before running, predict resumption without set_fact, the retry boundary and cleanup of a still-active job. Then compare predictions with the 28 checks and 28 invocations in each of the two retained runs.

Another measured detail matters: async/poll:0 under --check returned a job and exited zero, but observation showed the command skipped and its counter absent. That result does not establish background execution of the program. In handover, separate pinned runtime, selection, prerequisites, attempts, effects and final state.

This lab executes real modules and processes on one local macOS host; it does not validate SSH, RHEL services, reboot, application availability or the complete practical exam. Reproduce production requirements on appropriate disposable systems before accepting the actual change.

Exercise files

Extract the ZIP into a new directory and read README.en.md before preparation. Includes this exercise’s content/labs files and historical evidence. A separate venv with ansible-core 2.16.14 and compatible Python. Replace the ansible-playbook path; Python must exist in the same bin directory. Only local aliases, owned files and processes are executed. No SSH or privilege escalation is used.

Download rhce-execution lab

SHA-256 (ZIP)

490fb2d81f668e0489896f1583aabf127164c625d9cebc76664938215b4a4498

Extract the ZIP into a new directory and read README.en.md before preparation. Includes this exercise’s content/labs files and historical evidence. A separate venv with ansible-core 2.19.0 and compatible Python. Replace the ansible-playbook path; Python must exist in the same bin directory. Only local aliases, owned files and processes are executed. No SSH or privilege escalation is used.

Download rhce-playbook-execution lab

SHA-256 (ZIP)

d0d92c78e8451de800aed15ad9c655d85385dbb569617b748ec85e5b0a64918b

# Save as run.py. Requires the other five lab files in the same directory.
# Usage: python3 run.py --ansible-bin /absolute/venv/bin/ansible-playbook --output evidence.json
"""Original local-only Ansible lab. No SSH, become, services or real data."""
import argparse,hashlib,json,os,pathlib,platform,re,subprocess,tempfile,zipfile
from datetime import datetime,timezone
p=argparse.ArgumentParser();p.add_argument('--ansible-bin',required=True);p.add_argument('--output',required=True);args=p.parse_args()
source=pathlib.Path(__file__).resolve().parent;binary=pathlib.Path(args.ansible_bin).resolve();checks=[];runs=[]
def require(name,condition):
 assert condition,name
 checks.append({'name':name,'passed':True})
with tempfile.TemporaryDirectory(prefix='dr-rhce-lab-') as temporary:
 root=pathlib.Path(temporary);(root/'home').mkdir();inventory=root/'inventory.ini';inventory.write_text('[workers]\nworker_a ansible_connection=local\nworker_b ansible_connection=local\n[workers:vars]\nansible_python_interpreter='+str(binary.parent/'python')+'\n')
 env={**os.environ,'ANSIBLE_HOME':str(root/'home'),'ANSIBLE_LOCAL_TEMP':str(root/'local'),'ANSIBLE_REMOTE_TEMP':str(root/'remote'),'ANSIBLE_NOCOLOR':'1','ANSIBLE_CONFIG':str(root/'ansible.cfg'),'OBJC_DISABLE_INITIALIZE_FORK_SAFETY':'YES'}
 (root/'ansible.cfg').write_text('[defaults]\nretry_files_enabled=False\nhost_key_checking=True\n')
 version=subprocess.check_output([str(binary),'--version'],env=env,text=True).splitlines()[0]
 def run(label,play,extra=None,flags=(),expected=0):
  variables={'lab_root':str(root/'nodes'),'service_port':8443,'use_marker':False,**(extra or {})}
  command=[str(binary),'-i',str(inventory),str(source/play),'-e',json.dumps(variables),*flags]
  r=subprocess.run(command,env=env,text=True,capture_output=True,timeout=60)
  assert r.returncode==expected,(label,r.returncode,r.stdout,r.stderr)
  recaps={host:{k:int(v) for k,v in re.findall(r'(ok|changed|unreachable|failed|skipped|rescued|ignored)=(\d+)',line)} for line in r.stdout.splitlines() for host in ['worker_a','worker_b'] if line.startswith(host+' ') and 'ok=' in line}
  runs.append({'label':label,'returnCode':r.returncode,'recaps':recaps,'stdoutSha256':hashlib.sha256(r.stdout.encode()).hexdigest()});return r,recaps
 run('syntax','converge.yml',flags=['--syntax-check'])
 listed,_=run('limited-selection','converge.yml',flags=['--list-hosts','--limit','worker_a'])
 require('limit resolves only worker_a','worker_a' in listed.stdout and 'worker_b' not in listed.stdout)
 run('first-convergence','converge.yml')
 def contents(name):return {h:(root/'nodes'/h/name).read_bytes() for h in ['worker_a','worker_b']}
 initial=contents('worker.conf');activation=contents('activation.log')
 require('separate identities have distinct configurations',initial['worker_a']!=initial['worker_b'])
 require('first activation once per worker',all(x==b'activated\n' for x in activation.values()))
 _,recap=run('repeat-convergence','converge.yml');require('second convergence reports no change',all(x['changed']==0 for x in recap.values()) and len(recap)==2)
 require('repeat leaves configuration and activation unchanged',contents('worker.conf')==initial and contents('activation.log')==activation)
 run('invalid-template','converge.yml',{'service_port':70000},expected=2)
 require('invalid candidate preserves destinations',contents('worker.conf')==initial)
 require('invalid candidate never activates',contents('activation.log')==activation)
 run('check-prediction','converge.yml',{'service_port':9443},flags=['--check'])
 require('check leaves actual state unchanged',contents('worker.conf')==initial and contents('activation.log')==activation)
 for h in ['worker_a','worker_b']:
  release=root/'nodes'/h/'release';release.mkdir();(release/'obsolete.txt').write_text('old helper\n')
 bundle=root/'release.zip'
 def pack(text):
  with zipfile.ZipFile(bundle,'w') as z:z.writestr('payload.txt',text)
 pack('release-one\n');run('archive-first','archive.yml',{'bundle_path':str(bundle)})
 require('archive contains first payload',all(x==b'release-one\n' for x in contents('release/payload.txt').values()))
 require('archive does not prune unlisted files',all(x==b'old helper\n' for x in contents('release/obsolete.txt').values()))
 _,recap=run('archive-repeat','archive.yml',{'bundle_path':str(bundle)})
 require('unchanged zip repeat reports no change',len(recap)==2 and all(x['changed']==0 for x in recap.values()))
 for h in ['worker_a','worker_b']:(root/'nodes'/h/'release/ready').write_text('old marker\n')
 pack('release-two\n');run('stale-marker','archive.yml',{'bundle_path':str(bundle),'use_marker':True})
 require('existing marker suppresses new archive',all(x==b'release-one\n' for x in contents('release/payload.txt').values()))
 run('archive-without-marker','archive.yml',{'bundle_path':str(bundle)})
 require('new archive changes intended payload',all(x==b'release-two\n' for x in contents('release/payload.txt').values()))
 require('new archive still preserves extra file',all(x==b'old helper\n' for x in contents('release/obsolete.txt').values()))
 run('failed-release-recovery','recovery.yml',expected=2)
 require('rescue restores exact previous bytes',contents('worker.conf')==initial)
 require('always evidence written after rescue failure',all(x==b'recovery-path-visited\n' for x in contents('recovery.log').values()))
 require('recovery did not claim service activation',contents('activation.log')==activation)
 report={'checkedAt':datetime.now(timezone.utc).isoformat(),'ansible':version,'platform':platform.platform(),'localAliases':2,'actualMachines':1,'runs':runs,'checks':checks,'sourceHashes':{f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(source.iterdir()) if f.suffix in ['.yml','.j2','.py']},'limitations':['Local filesystem execution on macOS; no RHEL managed node or AAP execution environment.','Activation log is a synthetic handler effect, not a service restart or health check.','No SSH, privilege escalation, reboot, storage devices or SELinux validation.'],'cleanup':'Owned temporary target tree removed by TemporaryDirectory.'}
pathlib.Path(args.output).write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({'runs':len(runs),'checks':len(checks),'ansible':version}))
IN PRACTICE

Two local aliases produce different files; this demonstrates selection and path separation, not two machines.

Common pitfalls

Confusing inventory host with physical machine; using recap as sole evidence; delegating shared writes without controlling concurrency.

Related topics: Validated configuration and observable activation · Archives, residual files and markers · Recovery and change outcome

Take this idea with you

Resume with explicit prerequisites and accept the operation from effects and observed outcome.

Create account

References

  • Delegation and local execution · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • EX294 published objectives · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Template module · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Check and diff modes · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Handler execution · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Unarchive module · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Block error handling · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Stat module · Current public documentation checked 2026-10-07; local exercises executed with ansible-core 2.16.14
  • Starting and stepping through playbooks · Current primary documentation inspected; local runtime pinned to ansible-core 2.19.0, with measured boundaries recorded separately
  • Retries and loops · Current primary documentation inspected; local runtime pinned to ansible-core 2.19.0, with measured boundaries recorded separately
  • Asynchronous actions and polling · Current primary documentation inspected; local runtime pinned to ansible-core 2.19.0, with measured boundaries recorded separately
  • Asynchronous task status · Current primary documentation inspected; local runtime pinned to ansible-core 2.19.0, with measured boundaries recorded separately
  • Command execution and arguments · Current primary documentation inspected; local runtime pinned to ansible-core 2.19.0, with measured boundaries recorded separately

Red Hat®, RHCE and Ansible are trademarks or registered trademarks of Red Hat, Inc. bigsavant.com is an independent preparation platform and is not affiliated with, associated with, sponsored, authorised or endorsed by Red Hat. Content and questions are original, are not official exam questions, and completing our tests does not award or guarantee any certification. Names are used only to identify the subject. All other trademarks belong to their respective owners.