I treat selective Ansible execution as a selector-contract problem, not as a question answered by a green recap. A dynamic include_tasks statement can be displayed during a successful ansible-playbook invocation while none of the child task bodies an operator expected actually execute. The reason is structural: admission of a dynamic include and selection of its children are separate decisions. The ansible-core 2.19 documentation states that tags on include_tasks control the include action but are not automatically inherited by its children; apply is the mechanism that can add task keywords such as tags to those children.
This qualification packet isolates that behavior on one disposable Linux controller, one local inventory alias named owned, and one three-task children.yml. It proposes ansible-core 2.19.3 inside CPython 3.12 and compares dynamic include_tasks, static import_tasks, outer tags, apply.tags, always, and --skip-tags. The ten case outcomes below are EXPECTED / NOT EXECUTED. They are derived from documented selector semantics; they are not laboratory measurements.
I keep three questions separate throughout: what child set the operator intended, what the documented selectors should select, and what retained external evidence establishes after an actual run. A zero process exit status, a displayed include, changed, a task-start callback, or a missing receipt cannot collapse those questions into one.
The boundary is deliberately narrow. This article does not qualify check mode, handlers, run_once, serial batches, delegation, roles, loops, conditions, blocks, retries, failure-expression policy, remote hosts, privilege escalation, application activation, production deployment, rollback, or exactly-once behavior across future invocations.
Define the intended child selection before choosing tags
Before reviewing YAML, I write down the intended leaf set. In this fixture a leaf is a named executable child task: leaf_blue, leaf_red, or leaf_plain. Include admission is a different concept: it answers whether Ansible reaches and loads a dynamic task file. Child-body execution answers whether one of those named command tasks actually runs.
Two selection policies are legitimate here. A blue-only policy requires only leaf_blue. A full-file policy requires all three leaves. Neither is inherently better; the mistake is choosing a selector before declaring which policy it is supposed to satisfy.
That distinction prevents a common review error. Suppose --tags release admits an include tagged release, but the included children have tags blue, red, and no tag. The include can be admitted while none of those children matches release. Conversely, --tags blue can describe the desired child precisely but fail before the file is loaded if the include itself is untagged. The same empty receipt set can therefore arise at two different boundaries.
Ansible's 2.19 reuse guide explicitly separates dynamic inclusion, processed when encountered at runtime, from static import, preprocessed before task execution. The include_tasks reference adds that tags on the include are interpreted for that include action and are not automatically inherited by the included tasks. Static import_tasks, by contrast, applies tags on the import to the imported tasks.
For broader infrastructure context, Terraform and Ansible responsibilities are useful background. This article narrows the problem to selection inside one reusable Ansible task file.
My acceptance statement therefore begins with one sentence such as: “For this invocation, the intended leaf set is {leaf_blue}” or “the intended leaf set is {leaf_blue, leaf_red, leaf_plain}.” Only after that do tags become an implementation choice.
|
Pin the historical runtime and effective invocation
The proposed runtime is ansible-core 2.19.3, not “the latest Ansible.” Ansible announced v2.19.3 on October 6, 2025; the announcement establishes that historical patch release and identifies release artifacts, but an announcement checksum is not evidence that any particular controller downloaded or executed those artifacts.
I would prepare an isolated CPython 3.12 environment and retain the actual outputs rather than publishing sample values as observations:
python3.12 -m venv .venv
.venv/bin/python -m pip install ansible-core==2.19.3
.venv/bin/ansible-playbook --version
.venv/bin/python -m pip freeze
.venv/bin/ansible-doc ansible.builtin.include_tasks
.venv/bin/ansible-doc ansible.builtin.import_tasks
.venv/bin/ansible-doc ansible.builtin.commandInstallation failure is HOLD_EVIDENCE. So is a patch version other than 2.19.3 unless the qualification is intentionally restarted for that different runtime.
ansible-playbook --version is particularly useful because the 2.19 CLI reference says it reports the program version, configuration file, module locations, executable location, and related provenance. I retain that output together with pip freeze, the platform identity, the absolute .venv/bin/python path, and the absolute .venv/bin/ansible-playbook path.
The normal executions in this article are not check-mode runs. Ansible check-mode task coverage addresses a different evidence question.
I also require an explicit absolute configuration path. After creating the fixture directory:
ROOT="$(pwd -P)"
export ANSIBLE_CONFIG="$ROOT/ansible.cfg"
printf '%s\n' "$ANSIBLE_CONFIG"The driver supplied later does not inherit arbitrary ANSIBLE_* variables. It constructs a minimal subprocess environment and sets ANSIBLE_CONFIG itself. That matters because Ansible configuration can come from configuration files, environment variables, and CLI settings, with defined precedence; an unrecorded inherited selector or inventory setting would weaken the case identity.
The rolling ansible.builtin.command documentation is not relabeled as the 2.19.3 manual. It documents the argv list interface and the creates/removes short-circuit parameters; this fixture deliberately uses argv and omits creates and removes, then requires the installed ansible-doc output to be retained before execution.
Build one owned host and an independent ten-case manifest
The inventory has exactly one logical target, owned, connected locally. The playbooks also state gather_facts: false, become: false, connection: local, and strategy: linear; forks = 1 belongs in the owned ansible.cfg.
This is a host-count constraint, not a statement about broader cardinality. run_once and serial batch scope is intentionally outside this selector test.
A generated case-specific inventory.ini has this shape:
[fixture]
owned ansible_connection=local ansible_python_interpreter=/ABS/FIXTURE/.venv/bin/python receipt_python=/ABS/FIXTURE/.venv/bin/python receipt_writer=/ABS/CASE/work/receipt_writer.pyBefore any normal case execution, confirm only that inventory:
.venv/bin/ansible-playbook \
-i /ABS/CASE/work/inventory.ini \
/ABS/CASE/work/T01.yml \
--list-hostsThe 2.19 CLI documents --list-hosts as listing matching hosts without executing anything else. Any implicit-inventory warning, missing owned, or additional host is a qualification failure.
Fix child identities before observing output
The single child file is identical across all ten cases:
# children.yml
- name: leaf_blue
ansible.builtin.command:
argv:
- "{{ receipt_python }}"
- "{{ receipt_writer }}"
- --case
- "{{ case_id }}"
- --leaf
- leaf_blue
- --host
- "{{ inventory_hostname }}"
- --out-dir
- "{{ receipt_dir }}"
expand_argument_vars: false
tags: [blue]
- name: leaf_red
ansible.builtin.command:
argv:
- "{{ receipt_python }}"
- "{{ receipt_writer }}"
- --case
- "{{ case_id }}"
- --leaf
- leaf_red
- --host
- "{{ inventory_hostname }}"
- --out-dir
- "{{ receipt_dir }}"
expand_argument_vars: false
tags: [red]
- name: leaf_plain
ansible.builtin.command:
argv:
- "{{ receipt_python }}"
- "{{ receipt_writer }}"
- --case
- "{{ case_id }}"
- --leaf
- leaf_plain
- --host
- "{{ inventory_hostname }}"
- --out-dir
- "{{ receipt_dir }}"
expand_argument_vars: falseThe command module's documented argv form passes arguments as a list without shell parsing.
The following manifest is authored before output is collected. The proposed include-event counts are hypotheses for this pinned fixture, not observations.
Case | Construct | Outer tags | apply.tags | --tags | --skip-tags | Expected leaf IDs | Proposed include events |
T01 | include_tasks | none | none | default all | none | blue, red, plain | 1 |
T02 | import_tasks | release | n/a | release | none | blue, red, plain | 0 |
T03 | include_tasks | release | none | release | none | none | 1 |
T04 | include_tasks | none | none | blue | none | none | 0 |
T05 | include_tasks | always | none | blue | none | blue | 1 |
T06 | include_tasks | none | release | release | none | none | 0 |
T07 | include_tasks | release | release | release | none | blue, red, plain | 1 |
T08 | include_tasks | release | release | release | red | blue, plain | 1 |
T09 | include_tasks | always | none | blue | always | none | 0 |
T10 | import_tasks | release | n/a | release | release | none | 0 |
In receipt files, blue, red, and plain map to leaf_blue, leaf_red, and leaf_plain. Every row above is EXPECTED / NOT EXECUTED. Zero proposed events for an import means “no dynamic include-load event expected”; it does not mean imported children did not execute.
The external machine-readable manifest can be stored as expected_manifest.json:
{
"T01":{"tags":[],"skip":[],"leaves":["leaf_blue","leaf_red","leaf_plain"],"include_events":1},
"T02":{"tags":["release"],"skip":[],"leaves":["leaf_blue","leaf_red","leaf_plain"],"include_events":0},
"T03":{"tags":["release"],"skip":[],"leaves":[],"include_events":1},
"T04":{"tags":["blue"],"skip":[],"leaves":[],"include_events":0},
"T05":{"tags":["blue"],"skip":[],"leaves":["leaf_blue"],"include_events":1},
"T06":{"tags":["release"],"skip":[],"leaves":[],"include_events":0},
"T07":{"tags":["release"],"skip":[],"leaves":["leaf_blue","leaf_red","leaf_plain"],"include_events":1},
"T08":{"tags":["release"],"skip":["red"],"leaves":["leaf_blue","leaf_plain"],"include_events":1},
"T09":{"tags":["blue"],"skip":["always"],"leaves":[],"include_events":0},
"T10":{"tags":["release"],"skip":["release"],"leaves":[],"include_events":0}
}Capture evidence outside the tag-filtered play
I do not add an Ansible “verification task” to these playbooks, because the same selector being qualified could omit that verifier. Leaf evidence is written externally by a separate Python program.
receipt_writer.py uses exclusive creation: a second execution of the same case/leaf fails instead of overwriting the first receipt.
#!/usr/bin/env python3
import argparse
import json
import os
from pathlib import Path
ALLOWED = {"leaf_blue", "leaf_red", "leaf_plain"}
p = argparse.ArgumentParser()
p.add_argument("--case", required=True)
p.add_argument("--leaf", required=True, choices=sorted(ALLOWED))
p.add_argument("--host", required=True)
p.add_argument("--out-dir", required=True)
a = p.parse_args()
out = Path(a.out_dir).resolve()
out.mkdir(parents=True, exist_ok=True)
path = out / f"{a.leaf}.json"
payload = {
"schema": 1,
"case_id": a.case,
"leaf_id": a.leaf,
"host": a.host
}
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(payload, f, sort_keys=True)
f.write("\n")
f.flush()
os.fsync(f.fileno())The aggregate callback is independent of those leaf files. Ansible's 2.19 callback documentation says aggregate callbacks can run alongside the main stdout callback, while custom callbacks can respond to playbook events. The official Ansible Runner 2.4 callback source shows hook shapes including v2_playbook_on_start, v2_playbook_on_include, v2_playbook_on_stats, failure, unreachable, and no-host hooks. That source confirms a callback protocol shape; it does not prove how this custom plugin dispatches under ansible-core 2.19.3.
Create callback_plugins/selection_trace.py:
import json
import os
from pathlib import Path
from ansible.plugins.callback import CallbackBase
DOCUMENTATION = r'''
name: selection_trace
type: aggregate
short_description: Record qualification lifecycle events
description:
- Writes case-scoped JSONL lifecycle events.
requirements: []
'''
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = "aggregate"
CALLBACK_NAME = "selection_trace"
NEEDS_ENABLED = True
def path(self):
return Path(os.environ["QUALTRACE"]).resolve()
def append(self, event, fields):
record = {"event": event, fields}
with self.path().open("a", encoding="utf-8") as f:
f.write(json.dumps(record, sort_keys=True) + "\n")
f.flush()
os.fsync(f.fileno())
def v2_playbook_on_start(self, playbook):
path = self._path()
path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(json.dumps({"event": "start"}, sort_keys=True) + "\n")
f.flush()
os.fsync(f.fileno())
def v2_playbook_on_include(self, included_file):
self._append("include_load")
def v2_playbook_on_stats(self, stats):
self._append(
"stats",
processed=sorted(str(x) for x in stats.processed.keys()),
failures=dict(stats.failures),
unreachable=dict(stats.dark)
)
def v2_runner_on_failed(self, result, ignore_errors=False):
self._append("failure", ignore_errors=bool(ignore_errors))
def v2_runner_on_unreachable(self, result):
self._append("unreachable")
def v2_playbook_on_no_hosts_matched(self):
self._append("no_hosts_matched")
def v2_playbook_on_no_hosts_remaining(self):
self._append("no_hosts_remaining")The owned ansible.cfg template is:
[defaults]
stdout_callback = default
callbacks_enabled = selection_trace
callback_plugins = /ABS/CASE/work/callback_plugins
forks = 1
retry_files_enabled = False
host_key_checking = FalseThe driver below copies fixed sources into a fresh case directory, generates absolute configuration and inventory, builds an argument vector without a shell, imposes a timeout, captures process artifacts, and never manufactures a PASS record.
#!/usr/bin/env python3
# driver.py
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent
PY = (ROOT / ".venv/bin/python").resolve()
ANSIBLE = (ROOT / ".venv/bin/ansible-playbook").resolve()
TIMEOUT = 60
SELECTORS = {
"T01": [],
"T02": ["--tags", "release"],
"T03": ["--tags", "release"],
"T04": ["--tags", "blue"],
"T05": ["--tags", "blue"],
"T06": ["--tags", "release"],
"T07": ["--tags", "release"],
"T08": ["--tags", "release", "--skip-tags", "red"],
"T09": ["--tags", "blue", "--skip-tags", "always"],
"T10": ["--tags", "release", "--skip-tags", "release"]
}
COPY = [
"children.yml", "receipt_writer.py", "expected_manifest.json"
]
def sha256(path):
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 1024), b""):
h.update(chunk)
return h.hexdigest()
ap = argparse.ArgumentParser()
ap.add_argument("case", choices=sorted(SELECTORS))
ap.add_argument("--out-root", default="cases")
args = ap.parse_args()
case_dir = (ROOT / args.out_root / args.case).resolve()
if case_dir.exists():
raise SystemExit(f"refusing existing case directory: {case_dir}")
work = case_dir / "work"
receipts = case_dir / "receipts"
work.mkdir(parents=True)
receipts.mkdir()
(case_dir / "home").mkdir()
for name in COPY + [f"{args.case}.yml"]:
shutil.copy2(ROOT / name, work / name)
shutil.copytree(ROOT / "callback_plugins", work / "callback_plugins")
inventory = work / "inventory.ini"
inventory.write_text(
"[fixture]\n"
"owned ansible_connection=local "
f"ansible_python_interpreter={PY} "
f"receipt_python={PY} "
f"receipt_writer={work / 'receipt_writer.py'}\n",
encoding="utf-8"
)
cfg = work / "ansible.cfg"
cfg.write_text(
"[defaults]\n"
"stdout_callback = default\n"
"callbacks_enabled = selection_trace\n"
f"callback_plugins = {work / 'callback_plugins'}\n"
"forks = 1\n"
"retry_files_enabled = False\n"
"host_key_checking = False\n",
encoding="utf-8"
)
trace = case_dir / "trace.jsonl"
extra = json.dumps({
"case_id": args.case,
"receipt_dir": str(receipts)
}, separators=(",", ":"))
argv = [
str(ANSIBLE),
"-i", str(inventory),
str(work / f"{args.case}.yml"),
"-e", extra,
SELECTORS[args.case]
]
env = {
"HOME": str(case_dir / "home"),
"PATH": f"{ROOT / '.venv/bin'}:/usr/bin:/bin",
"PYTHONNOUSERSITE": "1",
"ANSIBLE_CONFIG": str(cfg.resolve()),
"QUAL_TRACE": str(trace.resolve())
}
version = subprocess.run(
[str(ANSIBLE), "--version"],
cwd=work,
env=env,
text=True,
capture_output=True,
timeout=TIMEOUT
)
(case_dir / "ansible-version.txt").write_text(
version.stdout + version.stderr, encoding="utf-8"
)
timed_out = False
try:
cp = subprocess.run(
argv,
cwd=work,
env=env,
text=True,
capture_output=True,
timeout=TIMEOUT
)
rc = cp.returncode
stdout = cp.stdout
stderr = cp.stderr
except subprocess.TimeoutExpired as e:
timed_out = True
rc = None
stdout = e.stdout or ""
stderr = e.stderr or ""
(case_dir / "stdout.txt").write_text(stdout, encoding="utf-8")
(case_dir / "stderr.txt").write_text(stderr, encoding="utf-8")
sources = {}
for p in sorted(work.rglob("*")):
if p.is_file() and p.name not in {"ansible.cfg", "inventory.ini"}:
sources[str(p.relative_to(work))] = sha256(p)
record = {
"schema": 1,
"case_id": args.case,
"argv": argv,
"ansible_config": str(cfg.resolve()),
"inventory": str(inventory.resolve()),
"python": str(PY),
"ansible_playbook": str(ANSIBLE),
"platform": platform.platform(),
"returncode": rc,
"timeout": timed_out,
"source_sha256": sources
}
(case_dir / "case.json").write_text(
json.dumps(record, indent=2, sort_keys=True) + "\n",
encoding="utf-8"
)
print(case_dir)Run a case with, for example:
.venv/bin/python driver.py T01The stdout shown by that invocation is not the acceptance evidence; it merely identifies the retained directory.
Qualify include events separately from leaf receipts
I do not use the proposed include-event counts until the collector has positive controls. T01 and T07 are the first candidates because their documented design admits a dynamic include and expects leaf execution. The callback must produce one start record and one terminal stats record, contain no failure/unreachable/no-host signals, avoid callback warnings in stderr, and survive the entire invocation.
Only after actual runs establish that the collector behaves consistently under the pinned runtime would I interpret its include count. The Runner source confirms that v2_playbook_on_include(included_file) exists as a callback hook, but this article has not executed this custom callback on 2.19.3.
A complete include trace and a leaf receipt answer different questions. An include_load event can support “the dynamic include was admitted.” It cannot support “leaf_blue executed.” Conversely, an external leaf_blue.json establishes that the writer command for that leaf ran, but an empty receipt directory alone cannot tell me whether the include gate remained closed or the admitted children failed tag selection.
Establish normal selection and static inheritance
T01 is the normal dynamic baseline:
# T01.yml
- name: T01 dynamic default
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Include children normally
ansible.builtin.include_tasks:
file: children.ymlExact normal invocation generated by the driver is equivalent to:
.venv/bin/ansible-playbook -i inventory.ini T01.yml \
-e '{"case_id":"T01","receipt_dir":"/ABS/CASE/receipts"}'With no explicit --tags, the expected set is all three leaves: {leaf_blue, leaf_red, leaf_plain}. EXPECTED / NOT EXECUTED.
T02 uses static import:
# T02.yml
- name: T02 static release
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Import the release task file
ansible.builtin.import_tasks:
file: children.yml
tags: [release]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T02.yml \
-e '{"case_id":"T02","receipt_dir":"/ABS/CASE/receipts"}' \
--tags releaseThe 2.19 import_tasks reference says tags are applied to imported tasks. Therefore each imported leaf gains release; the existing blue and red tags are not conceptually replaced. T02 expects all three receipts. EXPECTED / NOT EXECUTED.
T02 needs no runtime include_load event because static imports are preprocessed rather than dynamically included at runtime. The 2.19 reuse documentation makes that processing distinction explicit.
Observed columns stay blank until actual artifacts exist. I would never convert the expected {blue, red, plain} set into an “observed” set because the command returned zero.
Reproduce two different empty-child outcomes
T03 admits the file using release but does not propagate that tag to the children:
# T03.yml
- name: T03 admitted include with unmatched children
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Include release entry
ansible.builtin.include_tasks:
file: children.yml
tags: [release]Its selector is:
.venv/bin/ansible-playbook -i inventory.ini T03.yml \
-e '{"case_id":"T03","receipt_dir":"/ABS/CASE/receipts"}' \
--tags releaseThe include itself matches release, but the 2.19 include_tasks documentation says tags on the include are not automatically inherited by included tasks. None of the three original child identities carries release. T03 therefore expects no leaf receipts, with one proposed dynamic include event. EXPECTED / NOT EXECUTED.
T04 moves the empty result to the opposite boundary:
# T04.yml
- name: T04 closed untagged include
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Include children without an admission tag
ansible.builtin.include_tasks:
file: children.ymlInvocation:
.venv/bin/ansible-playbook -i inventory.ini T04.yml \
-e '{"case_id":"T04","receipt_dir":"/ABS/CASE/receipts"}' \
--tags blueThe desired leaf_blue has the blue tag, but the dynamic include itself does not. Under explicit tag selection the include is therefore expected not to be admitted. T04 expects no leaf receipts and zero proposed include events. EXPECTED / NOT EXECUTED.
Distinguish an admitted file from a closed include gate
T03 and T04 intentionally produce the same expected receipt set: {}. That is why receipts alone cannot localize this selector problem.
For T03, a qualified callback should support the sequence “start → include_load → stats,” while leaf receipts remain absent. For T04, a qualified callback should support “start → stats” without include_load. Those event counts remain hypotheses until the callback has been executed and qualified.
The diagnostic rule is therefore:
empty receipts + qualified include event
=> file admission supported; child selection still empty
empty receipts + qualified trace with no include event
=> closed include gate supported
empty receipts + unhealthy/missing trace
=> admission question inconclusiveI do not substitute an Ansible stdout line for the qualified trace. Nor do I interpret process status 0 as proof that the requested child body executed. ansible-playbook documents tag selection and skip options, but process success does not redefine the operator's intended leaf set.
Select the blue child with an explicit admission policy
T05 expresses a blue-only policy by making admission independent of the ordinary selector while leaving child selection narrow:
# T05.yml
- name: T05 blue-only dynamic selection
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Keep the child-selector gate available
ansible.builtin.include_tasks:
file: children.yml
tags: [always]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T05.yml \
-e '{"case_id":"T05","receipt_dir":"/ABS/CASE/receipts"}' \
--tags blueThe expected receipt set is {leaf_blue}. EXPECTED / NOT EXECUTED.
The later 2.21 tags manual describes always as a special tag whose task normally participates even under explicit tag selection, while also documenting that it can be explicitly skipped. The archived 2.14 manual independently shows the long-standing distinction between include tags and child tags; that is historical documentation, not a recommendation to install 2.14.
I use those tag manuals carefully because they are not the 2.19.3 documentation family. The 2.19 include_tasks page nevertheless provides the key runtime-family contract: include tags control the include and do not automatically flow to children.
For a blue-only contract, forcing release onto every child would broaden the child selection vocabulary unnecessarily. T05 is therefore not a weaker form of T07; it represents a different intended policy.
And always must not be described as “unskippable.” T09 exists specifically to exercise the documented explicit exclusion.
Repair apply.tags without leaving the include closed
T06 demonstrates an incomplete repair. apply.tags can add a keyword to included children, but it does not by itself make an untagged include match --tags release.
# T06.yml
- name: T06 apply without admission
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Apply release only to possible children
ansible.builtin.include_tasks:
file: children.yml
apply:
tags: [release]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T06.yml \
-e '{"case_id":"T06","receipt_dir":"/ABS/CASE/receipts"}' \
--tags releaseThe 2.19 module reference defines apply as a hash of task keywords applied to tasks within the include; its documented example adds both an apply tag and an outer tag that admits the include. The same page records apply as introduced in Ansible 2.7.
T06 therefore expects no receipts and no include event: the dynamic include gate is expected to stay closed before inherited child tags can matter. EXPECTED / NOT EXECUTED.
T07 supplies both stages:
# T07.yml
- name: T07 admitted full-file release selection
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Admit the release task file
ansible.builtin.include_tasks:
file: children.yml
apply:
tags: [release]
tags: [release]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T07.yml \
-e '{"case_id":"T07","receipt_dir":"/ABS/CASE/receipts"}' \
--tags releaseThe later 2.21 tags guide shows the same two-part shape: apply.tags adds a tag to included tasks and an outer tags value adds it to the include_tasks statement itself. Again, that source documents tag semantics in a later manual family; it is not relabeled as 2.19.3 evidence.
Add the outer selector and preserve the intended child scope
The repair under test is exactly:
- name: Admit the release task file
ansible.builtin.include_tasks:
file: children.yml
apply:
tags: [release]
tags: [release]Under the full-file policy, T07 expects {leaf_blue, leaf_red, leaf_plain} plus one proposed include event. EXPECTED / NOT EXECUTED.
This does not erase the children’s existing identities. leaf_blue still has blue, leaf_red still has red, and leaf_plain remains the originally untagged leaf to which release is being applied.
I do not accept a repaired candidate merely because its YAML looks like the documentation example. The source must be freshly executed in a new evidence directory and reconciled against the independently authored expected set.
Nor do I offer T07 as a universal repair for T05. T05 is appropriate when the contract is “admit the file so a child-level selector such as blue can choose one leaf.” T07 is appropriate when release is intended to represent the whole included file.
Test exclusions after inheritance and admission
T08 reuses the full-file admission pattern but adds an explicit exclusion:
# T08.yml
- name: T08 inherited release with red excluded
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Admit release and apply release
ansible.builtin.include_tasks:
file: children.yml
apply:
tags: [release]
tags: [release]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T08.yml \
-e '{"case_id":"T08","receipt_dir":"/ABS/CASE/receipts"}' \
--tags release --skip-tags redThe expected leaves are {leaf_blue, leaf_plain}. EXPECTED / NOT EXECUTED. leaf_red has both its original red identity and the applied release tag; exclusion wins over explicit selection.
The 2.21 tags guide states that --skip-tags takes precedence over explicit --tags.
T09 checks the special admission tag:
# T09.yml
- name: T09 always explicitly excluded
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Normally available admission gate
ansible.builtin.include_tasks:
file: children.yml
tags: [always]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T09.yml \
-e '{"case_id":"T09","receipt_dir":"/ABS/CASE/receipts"}' \
--tags blue --skip-tags alwaysThe expected leaf set is empty and the proposed include-event count is zero. EXPECTED / NOT EXECUTED. The later tags guide explicitly documents --skip-tags always as a way to suppress an always-tagged task.
T10 is static:
# T10.yml
- name: T10 static release excluded
hosts: owned
connection: local
gather_facts: false
become: false
strategy: linear
tasks:
- name: Import release task file
ansible.builtin.import_tasks:
file: children.yml
tags: [release]Invocation:
.venv/bin/ansible-playbook -i inventory.ini T10.yml \
-e '{"case_id":"T10","receipt_dir":"/ABS/CASE/receipts"}' \
--tags release --skip-tags releaseStatic import gives the imported children release; explicit skipping of release is therefore expected to remove all of them. T10 expects no receipts. EXPECTED / NOT EXECUTED. The import itself is not a dynamic include, so zero include-load events is not evidence of missing imported execution.
Retain child tags and apply exclusion precedence
The important detail in T08 is that inheritance adds a selectable identity; it does not make the prior red identity irrelevant. The requested release set contains all three children, then the explicit red exclusion removes leaf_red.
T09 and T10 also end with empty expected receipt sets, but through different mechanisms: T09 closes the dynamic include by explicitly skipping its always admission tag; T10 excludes the inherited release tag from statically imported children.
These can be successful negative controls while still being wrong operational selectors. If the declared intent was blue-only, T09's empty result is not ACCEPT merely because the experiment behaved as predicted. If the intent was full-file release, T10's empty result likewise conflicts with policy.
Use previews without treating them as execution inventories
I capture preview commands separately from normal execution and keep their artifacts outside the T01–T10 receipt directories.
For T02:
.venv/bin/ansible-playbook -i inventory.ini T02.yml --tags release --list-hosts
.venv/bin/ansible-playbook -i inventory.ini T02.yml --tags release --list-tasks
.venv/bin/ansible-playbook -i inventory.ini T02.yml --tags release --list-tagsFor T07:
.venv/bin/ansible-playbook -i inventory.ini T07.yml --tags release --list-hosts
.venv/bin/ansible-playbook -i inventory.ini T07.yml --tags release --list-tasks
.venv/bin/ansible-playbook -i inventory.ini T07.yml --tags release --list-tagsThe 2.19 CLI broadly describes --list-tasks as listing tasks that would be executed and --list-tags as listing available tags. Those descriptions must be read with the more specific dynamic-reuse limitation in the 2.19 reuse guide: tags inside dynamic includes are not listed by --list-tags, and tasks within dynamic includes are not listed by --list-tasks; imported children, by contrast, are visible to those static previews.
The later tags guide states the limitation directly as well: preview flags cannot show tasks or tags within dynamically included files or roles.
Therefore I expect T02's static children to be substantially more visible to listing than T07's dynamically included children. That difference is diagnostic of static versus dynamic preprocessing; it is not proof that a normal invocation executed a leaf.
Preview runs must not share the execution receipt directory or qualification trace. --list-hosts expressly performs no task execution, and --list-tasks/--list-tags are previews, not leaf-execution evidence.
No preview invocation becomes an eleventh case. T01–T10 are the normal-mode selector cases; previews are provenance aids.
Reconcile the complete case inventory
After actual execution, I reconcile four independent dimensions: source/runtime identity, exact invocation, callback health, and receipt identity. Process return code is recorded but not promoted into a substitute for any of them.
The external verifier below rejects unknown files, incorrect case IDs, an unexpected host, missing receipt fields, duplicate logical leaves, altered retained source copies, timeout, nonzero process status, callback lifecycle gaps, warning-bearing stderr, and unexpected callback failure signals. The proposed include-event count is enforced only after the operator explicitly says the collector has been qualified.
#!/usr/bin/env python3
# verify.py
import argparse
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent
EXPECTED = json.loads((ROOT / "expected_manifest.json").read_text())
def sha256(path):
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 1024), b""):
h.update(chunk)
return h.hexdigest()
ap = argparse.ArgumentParser()
ap.add_argument("case_dir")
ap.add_argument("--collector-qualified", action="store_true")
a = ap.parse_args()
case_dir = Path(a.case_dir).resolve()
record = json.loads((case_dir / "case.json").read_text())
case = record["case_id"]
if case not in EXPECTED:
raise SystemExit("HOLD_EVIDENCE: unknown case")
if record.get("timeout"):
raise SystemExit("HOLD_EVIDENCE: timeout")
if record.get("returncode") != 0:
raise SystemExit("HOLD_EVIDENCE: nonzero ansible-playbook status")
if Path(record["ansible_config"]).resolve() != (case_dir / "work/ansible.cfg").resolve():
raise SystemExit("HOLD_EVIDENCE: wrong ANSIBLE_CONFIG")
argv = record["argv"]
if not argv or Path(argv[0]).name != "ansible-playbook":
raise SystemExit("HOLD_EVIDENCE: unexpected executable")
if f"{case}.yml" not in {Path(x).name for x in argv}:
raise SystemExit("HOLD_EVIDENCE: wrong playbook argv")
expected_suffix = []
if EXPECTED[case]["tags"]:
expected_suffix += ["--tags", ",".join(EXPECTED[case]["tags"])]
if EXPECTED[case]["skip"]:
expected_suffix += ["--skip-tags", ",".join(EXPECTED[case]["skip"])]
for token in expected_suffix:
if token not in argv:
raise SystemExit(f"HOLD_EVIDENCE: missing argv token {token}")
work = case_dir / "work"
for rel, digest in record["source_sha256"].items():
p = work / rel
if not p.is_file() or sha256(p) != digest:
raise SystemExit(f"HOLD_EVIDENCE: changed source {rel}")
receipts_dir = case_dir / "receipts"
allowed_names = {f"{x}.json" for x in
["leaf_blue", "leaf_red", "leaf_plain"]}
actual_files = {p.name for p in receipts_dir.glob(".json")}
unknown = actual_files - allowed_names
if unknown:
raise SystemExit(f"HOLD_EVIDENCE: unexpected receipt files {sorted(unknown)}")
seen = set()
for p in receipts_dir.glob("*.json"):
obj = json.loads(p.read_text())
required = {"schema", "case_id", "leaf_id", "host"}
if set(obj) != required:
raise SystemExit(f"HOLD_EVIDENCE: wrong fields in {p.name}")
if obj["schema"] != 1 or obj["case_id"] != case:
raise SystemExit(f"HOLD_EVIDENCE: wrong case/schema in {p.name}")
if obj["host"] != "owned":
raise SystemExit(f"HOLD_EVIDENCE: wrong host in {p.name}")
if obj["leaf_id"] in seen:
raise SystemExit("HOLD_EVIDENCE: duplicate logical leaf")
seen.add(obj["leaf_id"])
expected_leaves = set(EXPECTED[case]["leaves"])
if seen != expected_leaves:
raise SystemExit(
f"SELECTION_MISMATCH: expected={sorted(expected_leaves)} "
f"observed={sorted(seen)}"
)
stderr = (case_dir / "stderr.txt").read_text(errors="replace")
if "[WARNING]" in stderr:
raise SystemExit("HOLD_EVIDENCE: warning present")
trace_path = case_dir / "trace.jsonl"
if not trace_path.is_file():
raise SystemExit("HOLD_EVIDENCE: callback trace missing")
events = [json.loads(x) for x in trace_path.read_text().splitlines() if x.strip()]
names = [x.get("event") for x in events]
if names.count("start") != 1 or names.count("stats") != 1:
raise SystemExit("HOLD_EVIDENCE: callback heartbeat incomplete")
bad = {"failure", "unreachable", "no_hosts_matched", "no_hosts_remaining"}
if bad.intersection(names):
raise SystemExit("HOLD_EVIDENCE: callback failure signal present")
stats = [x for x in events if x.get("event") == "stats"][0]
if stats.get("processed") != ["owned"]:
raise SystemExit("HOLD_EVIDENCE: wrong processed host set")
include_count = names.count("include_load")
if a.collector_qualified:
expected_count = EXPECTED[case]["include_events"]
if include_count != expected_count:
raise SystemExit(
f"HOLD_EVIDENCE: include count {include_count}, "
f"expected {expected_count}"
)
print(json.dumps({
"case": case,
"status": "EVIDENCE_MATCHES_EXPECTED_SELECTION",
"leaves": sorted(seen),
"include_events": include_count,
"include_count_enforced": a.collector_qualified
}, sort_keys=True))The verifier's success text is deliberately not “deployment passed.” It says only that the retained evidence matches the expected selector contract.
For failure interpretation beyond this narrow selection layer, Ansible failure-policy classification is a separate topic.
Reject incomplete or circular evidence
I would reject at least these evidence defects:
a missing T01–T10 case;
a receipt whose case_id, host, schema, or leaf ID is wrong;
an unexpected leaf file;
a second execution that attempts to overwrite the same leaf identity;
a source copy whose SHA-256 no longer matches the retained case record;
a missing callback start or terminal stats heartbeat;
callback failure, unreachable, or no-host signals;
a timeout or nonzero process status;
an unexpected selector argv;
an include count interpreted before the collector was qualified.
The expected denominator must come from expected_manifest.json, never from the number of rows that happened to appear. Otherwise “zero observed leaves” could define its own success criterion.
Likewise, a callback failure is not “zero includes.” It is missing instrumentation. That is HOLD_EVIDENCE.
The source hash controls here are evidence-integrity checks, not application-integrity claims. They establish that the retained source copy did not change relative to the case record. They do not prove any external system reached a desired state.
Choose ACCEPT, REPAIR, REVIEW or HOLD
The selector decision should name both the operator's intended set and the evidence state.
Decision | Use when | Example interpretation |
ACCEPT_DECLARED_SELECTION | Complete retained evidence matches the independently declared intended leaf subset | T05 after a qualified real run, if intent is blue only |
REPAIR_GATE | Desired child exists but the dynamic include is not admitted | T04; also T06 when apply.tags exists without an outer admission tag |
REPAIR_CHILD_TAGS | Include is admitted but children do not acquire the tag required by a full-file policy | T03 when intent is all three under release |
REVIEW_SELECTOR | Explicit exclusions or requested tags conflict with the declared operational intent | T08, T09, or T10 depending on intent |
HOLD_EVIDENCE | Runtime, inventory, callback health, receipts, hashes, argv, or case completeness is uncertain | Missing trace heartbeat, timeout, unknown receipt, unqualified collector |
RERUN_AFTER_CHANGE | A relevant input changed after prior qualification | Runtime, child source, playbook, inventory, tags, CLI selector, or instrumentation changed |
A negative control can therefore “pass” experimentally and still fail the operator's requested policy. T09 is expected to execute no children. If I ran it and obtained a complete qualified trace plus no receipts, that would support the experiment's expected omission. It would not satisfy a blue-only production request.
The same distinction applies to T03. If the declared objective is to prove Ansible's include-tag boundary, an admitted include plus no child receipts would be the expected experiment. If the declared objective was “execute the entire release file,” the identical result requires REPAIR_CHILD_TAGS.
The decision sequence I use is:
Declare intended leaf IDs.
Verify runtime/source/inventory identity.
Verify exact --tags and --skip-tags argv.
Verify callback health.
Compare external leaf receipts with intended IDs.
Use include events only to localize a dynamic admission boundary.
ACCEPT only the declared local selector contract.
No outcome from this one-host fixture authorizes a production deployment. The fixture proves, at most, which synthetic command bodies were selected in one retained local invocation.
Preserve evidence and requalify the repaired invocation
I preserve the approved selector pair as source plus invocation, not merely as YAML. The evidence package should include children.yml, the exact Txx playbook, generated inventory, absolute ansible.cfg, expected manifest, callback source, writer source, verifier source, source hashes, ansible-playbook --version, dependency inventory, stdout, stderr, process status, callback trace, leaf receipts, and exact argv.
Repairs belong in new case directories. I do not delete T04 and overwrite it with a repaired T07 result, because that destroys the evidence showing why the original gate was wrong.
For example:
.venv/bin/python driver.py T04 --out-root qualification-original
.venv/bin/python driver.py T07 --out-root qualification-repairAfter the collector has been separately qualified:
.venv/bin/python verify.py qualification-original/T04 --collector-qualified
.venv/bin/python verify.py qualification-repair/T07 --collector-qualifiedThose are instructions for a future real execution; this article does not claim they have run.
I assign ownership for three artifacts: selector policy, expected manifest, and collector/verifier implementation. A change to ansible-core, Python runtime, inventory identity, children.yml, outer tags, apply.tags, CLI --tags, CLI --skip-tags, callback code, writer code, verifier code, or relevant Ansible configuration invalidates the old qualification and leads to RERUN_AFTER_CHANGE.
Restoring an approved source-and-selector pair restores configuration identity for this test. It says nothing about restoring external effects. There is no transactional rollback mechanism in this fixture.
For downstream activation behavior, handler delivery and unchanged reruns mark a separate boundary that is intentionally excluded here.
Temporary material should be removed only after the evidence required by the review has been preserved. The point is reproducibility, not accumulation of scratch directories.
The core review principle remains narrow: selection evidence is leaf identity evidence. A task-start callback, a displayed include, or a zero process exit can support context, but the external exclusive receipts are what establish that these synthetic leaf command bodies actually executed during the retained invocation.
Extend the practice with Refonte Learning’s DevOps Engineering Program
This packet is useful as a review discipline even when the surrounding automation stack changes: declare the intended work set, pin execution context, collect evidence outside the mechanism being tested, and refuse to turn missing instrumentation into a success claim.
Refonte Learning's DevOps Engineering Program currently describes a three-month program at 12–14 hours per week, with curriculum areas including Linux and scripting, Git/GitHub, CI/CD, Docker/Kubernetes, Terraform, AWS/Azure/GCP, monitoring and logging, and a capstone. The page names MSc Oskar Eriksson as an instructor/mentor and describes training and internship certificates on successful completion; its admission language addresses learners working toward a bachelor's degree or higher.
Disciplined Linux, scripting, CI/CD, and infrastructure automation work all benefit from reproducible qualification habits. The cited program page does not establish that this specific include_tasks/import_tasks laboratory, ansible-core 2.19.3, or this ten-case packet is taught in the program.

