ci(molecule): run only the scenarios of the roles a pull request changes
Build / build (pull_request) Failing after 12s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 6m53s

A pull request now runs the scenarios of the roles it touches, none when it
touches only paths no scenario reads, and everything for any other file, for
every push to main and for manual dispatch. The job stays unconditional so
Molecule can remain a required check.

scripts/select_molecule_scenarios.py makes the choice and is run from the base
branch's copy, so a pull request cannot edit its own rules. A changed role
that exists but has no scenario fails instead of passing with nothing tested.

The scenario loop no longer gives molecule the list as stdin, which a child
could have drained, and fails when it ran fewer scenarios than were selected.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
This commit is contained in:
Defame1297andClaude Sonnet 5.5 committed 2026-11-14 11:05:46 +00:00
1 parent 2721509cde
commit 4d330d41c7
5 files changed
+480 -20

No files matched your search

+40 -17
View File
@@ -98,9 +98,15 @@ jobs:
git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; }
echo "Checked out $(git rev-parse HEAD)"
# A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py
# explains the rules); a push to main and a manual dispatch run all of them.
# molecule test destroys its instance on success and on failure.
- name: Run the scenarios
working-directory: ac/ansible_collections/mortis/kamino
env:
EVENT_NAME: ${{ github.event_name }}
# The workflow only runs for pull requests to main; lint.yml uses the same constant.
BASE_REF: origin/main
run: |
# molecule calls ansible-config and ansible-playbook by name
export PATH="$MOLECULE_VENV/bin:$PATH"
@@ -113,26 +119,43 @@ jobs:
export ANSIBLE_HOME="$ac_root/.ansible"
export ANSIBLE_COLLECTIONS_PATH="$ac_root:$MOLECULE_COLLECTIONS"
rm -rf "$HOME/.ansible/collections/ansible_collections/mortis"
# The selector comes from the base branch, so a pull request cannot edit the rules it is
# judged by (lint.yml does the same for check_bot_pr_diff.py); the first pull request that
# adds it has no base copy yet and uses its own.
sel=scripts/select_molecule_scenarios.py
if git cat-file -e "$BASE_REF:$sel" 2>/dev/null; then
sel_dir="$(mktemp -d)"
trap 'rm -rf "$sel_dir"' EXIT
git show "$BASE_REF:$sel" > "$sel_dir/select.py"
sel="$sel_dir/select.py"
else
echo "::notice::no base copy of $sel; running this checkout's copy"
fi
selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1
failed=""
ran=0
for cfg in extensions/molecule/*/molecule.yml; do
[ -e "$cfg" ] || continue
name="$(basename "$(dirname "$cfg")")"
echo "::group::molecule test: $name"
molecule test -s "$name" || failed="$failed $name"
while IFS= read -r dir; do
[ -n "$dir" ] || continue
name="$(basename "$dir")"
case "$dir" in
extensions/*)
label="$name"
echo "::group::molecule test: $label"
molecule test -s "$name" </dev/null || failed="$failed $label"
;;
*)
role="${dir#roles/}"
role="${role%%/*}"
label="$role/$name"
echo "::group::molecule test: $label"
(cd "roles/$role" && molecule test -s "$name" </dev/null) || failed="$failed $label"
;;
esac
ran=$((ran + 1))
echo "::endgroup::"
done
for cfg in roles/*/molecule/*/molecule.yml; do
[ -e "$cfg" ] || continue
role="${cfg#roles/}"
role="${role%%/*}"
name="$(basename "$(dirname "$cfg")")"
echo "::group::molecule test: $role/$name"
(cd "roles/$role" && molecule test -s "$name") || failed="$failed $role/$name"
ran=$((ran + 1))
echo "::endgroup::"
done
done <<< "$selected"
echo "Scenarios run: $ran"
test "$ran" -gt 0 || { echo "::error::no molecule scenario found"; exit 1; }
# A scenario that swallowed the rest of the list must not pass quietly.
want="$(grep -c . <<< "$selected" || true)"
test "$ran" -eq "$want" || { echo "::error::ran $ran of $want selected scenarios"; exit 1; }
test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
+6 -1
View File
@@ -59,7 +59,12 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
checksums baked into the image: a PR that changes `requirements-dev.txt` or
`.pre-commit-config.yaml` takes the slower path that installs the pinned tools.
- Molecule runs on every same-repo pull request, Renovate's included (a new image is tested by its own pin
pull request), with no path filter, so that it can be a required check. Fork pull requests are skipped.
pull request), with no workflow path filter, so that it can be a required check. Fork pull requests are skipped.
What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`, run from the base branch's copy
(a pull request cannot edit its own rules): only the scenarios of the roles it changes, none for a diff of
only its IGNORED paths, a failure for a changed role with no scenario, and every scenario for any other file,
for every push to `main` and for manual dispatch. A new file outside `roles/<role>/` runs everything until it
is added to IGNORED, which is right only when no scenario reads it.
- Molecule discovers `extensions/molecule/*/` and `roles/*/molecule/*/`. The `image-smoke`
and `image-smoke-2604` scenarios test the molecule images themselves (24.04 and 26.04); a role scenario that
must pass on both takes `image: ${MOLECULE_IMAGE}` or `${MOLECULE_IMAGE_2604}` per platform.
+3 -2
View File
@@ -53,8 +53,9 @@ outside contributions:
- Protect the `v*` tags so only maintainers can create them. A tag run uses the
workflow files of the tagged commit and may receive organisation secrets.
- Protect `main`: pull request required, with the `Lint` and `Build` checks. Molecule is not a required
check: its path filter would leave the check pending forever on a pull request that touches no role.
- Protect `main`: pull request required, with the `Lint` and `Build` checks. Molecule has no path filter
on pull requests (the job always starts and chooses its scenarios itself), so it can be made a required
check as well; that is the operator's decision.
- The image workflow (`.gitea/workflows/image.yml`) tries the Actions job token first;
Gitea 28 refuses it for an organisation's packages, so it pushes with the organisation secrets
`PACKAGE_PUSH_USER` and `PACKAGE_PUSH_TOKEN` (a bot user with write access to the
+183
View File
@@ -0,0 +1,183 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the molecule scenarios a run needs.
python3 -I scripts/select_molecule_scenarios.py [<base-ref>]
Prints one scenario directory per line (`extensions/molecule/<name>` or
`roles/<role>/molecule/<name>`), extensions first, then roles, each sorted. The molecule
workflow runs `molecule test` in each.
Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAME is
`pull_request`. Then the diff of <base-ref>...HEAD decides:
* a file under roles/<role>/ selects that role's scenarios, and nothing else;
* a file on the IGNORED list (documentation, changelog, repository tooling that no
scenario reads) selects nothing;
* any other file selects every scenario.
The roles do not depend on one another, so a change inside one role cannot alter another
role's result. If one ever does (a role calling another, a shared plugin), the shared file
sits outside roles/<role>/ and so already selects everything; only an explicit role-to-role
dependency would need a rule here.
Every other case runs everything: a push, a manual dispatch, a scheduled run, no <base-ref>, a git
failure.
Narrowing is an optimisation, so any doubt resolves to the full set. The scenarios the
selection skips are not skipped on `main`: the push run after the merge runs them all.
A changed role that exists but has no scenario is an error, not an empty selection: a new role
without a molecule scenario, or a deleted or renamed scenario, must not pass Molecule with
nothing tested. A role whose directory is gone (the role was deleted) selects nothing.
The workflow runs this script from the base branch's copy, not the pull request's, so a pull
request cannot edit the rules it is judged by (the same reason lint.yml runs
check_bot_pr_diff.py from origin/main). A change to this file therefore selects everything
under the base copy's rules, because the file is not on the IGNORED list.
Exit codes: 0 ok (an empty selection from an all-ignored diff is ok), 1 no scenario exists at
all, or a changed role has none, 2 bad usage. Notices go to stderr as `::notice::` lines, with
control characters in paths escaped so a crafted file name cannot inject a log command.
"""
import fnmatch
import os
import subprocess
import sys
# Paths no scenario reads. A match is by fnmatch on the repository-relative path, where `*`
# also crosses `/`. Keep this list short and literal: anything not listed runs everything.
IGNORED = (
"docs/*",
"changelogs/*",
"LICENSES/*",
"README.md",
"CONTRIBUTING.md",
"SECURITY.md",
"GLOSSARY.md",
"CLAUDE.md",
"CHANGELOG.rst",
"COPYING",
"NOTICE",
"REUSE.toml",
"renovate.json",
".gitignore",
".yamllint",
".ansible-lint",
".pre-commit-config.yaml",
"requirements-dev.txt",
"apm.yml",
"apm.lock.yaml",
"tests/sanity/*",
"tests/scripts/*",
"images/*",
".gitea/actionlint.yaml",
".gitea/workflows/lint.yml",
".gitea/workflows/build.yml",
".gitea/workflows/image.yml",
".gitea/workflows/renovate.yml",
"scripts/bump_image_versions.py",
"scripts/check_bot_pr_diff.py",
"scripts/check_image_versions.py",
"scripts/check_tarball.py",
"scripts/dev-setup.sh",
"scripts/reuse_lint.py",
)
def printable(text):
"""`text` with control characters (a newline in a file name) escaped, for a log line."""
return "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in text)
def discover(root="."):
"""Every scenario directory, extensions first, each group sorted."""
found = []
ext = os.path.join(root, "extensions", "molecule")
if os.path.isdir(ext):
for name in sorted(os.listdir(ext)):
if name.isprintable() and os.path.isfile(os.path.join(ext, name, "molecule.yml")):
found.append(f"extensions/molecule/{name}")
roles = os.path.join(root, "roles")
if os.path.isdir(roles):
for role in sorted(os.listdir(roles)):
mol = os.path.join(roles, role, "molecule")
if not os.path.isdir(mol):
continue
for name in sorted(os.listdir(mol)):
if role.isprintable() and name.isprintable() and os.path.isfile(os.path.join(mol, name, "molecule.yml")):
found.append(f"roles/{role}/molecule/{name}")
return found
def is_ignored(path):
return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED)
def select(all_scenarios, changed, root="."):
"""The scenarios `changed` (repository-relative paths) needs, and a one-line reason.
Raises ValueError when a changed role still exists but has no scenario.
"""
roles = set()
for path in changed:
if is_ignored(path):
continue
parts = path.split("/")
if len(parts) > 2 and parts[0] == "roles":
roles.add(parts[1])
continue
return list(all_scenarios), f"{printable(path)} can affect every scenario"
chosen = [s for s in all_scenarios if s.startswith("roles/") and s.split("/")[1] in roles]
covered = {s.split("/")[1] for s in chosen}
bare = sorted(r for r in roles - covered if os.path.isdir(os.path.join(root, "roles", r)))
if bare:
raise ValueError("changed role without a molecule scenario: " + ", ".join(printable(r) for r in bare))
if roles:
reason = "only roles changed: " + ", ".join(printable(r) for r in sorted(roles))
else:
reason = "no change that a scenario reads"
return chosen, reason
def changed_paths(base_ref):
"""Paths changed in base_ref...HEAD; a rename counts as a delete plus an add."""
out = subprocess.run(
["git", "diff", "--name-only", "--no-renames", "-z", f"{base_ref}...HEAD", "--"],
check=True, capture_output=True,
).stdout
return [os.fsdecode(p) for p in out.split(b"\0") if p]
def main(argv, environ=os.environ):
if len(argv) > 2:
print("usage: select_molecule_scenarios.py [<base-ref>]", file=sys.stderr)
return 2
base_ref = argv[1] if len(argv) == 2 else ""
scenarios = discover()
if not scenarios:
print("::error::no molecule scenario found", file=sys.stderr)
return 1
if environ.get("EVENT_NAME") != "pull_request" or not base_ref:
print(f"::notice::Running all {len(scenarios)} scenarios (not a pull request)", file=sys.stderr)
chosen = scenarios
else:
try:
changed = changed_paths(base_ref)
except (subprocess.CalledProcessError, OSError, UnicodeError) as exc:
print(f"::warning::cannot diff against {printable(base_ref)} ({printable(str(exc))}); running all scenarios",
file=sys.stderr)
chosen = scenarios
else:
try:
chosen, reason = select(scenarios, changed)
except ValueError as exc:
print(f"::error::{exc}", file=sys.stderr)
return 1
print(f"::notice::Running {len(chosen)} of {len(scenarios)} scenarios: {reason}", file=sys.stderr)
for scenario in chosen:
print(scenario)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -0,0 +1,248 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import contextlib
import io
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / "scripts"))
import select_molecule_scenarios as sel # noqa: E402
ALL = [
"extensions/molecule/image-smoke",
"extensions/molecule/image-smoke-2604",
"roles/docker/molecule/default",
"roles/fail2ban/molecule/default",
"roles/system_baseline/molecule/default",
]
class SelectTest(unittest.TestCase):
def test_role_change_selects_only_that_role(self):
chosen, _ = sel.select(ALL, ["roles/docker/tasks/main.yml", "roles/docker/molecule/default/verify.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_two_roles(self):
chosen, _ = sel.select(ALL, ["roles/fail2ban/defaults/main.yml", "roles/docker/meta/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default", "roles/fail2ban/molecule/default"])
def test_ignored_only_selects_nothing(self):
chosen, _ = sel.select(ALL, ["docs/x.md", "changelogs/fragments/a.yml", "README.md", "images/ci/Dockerfile"])
self.assertEqual(chosen, [])
def test_ignored_does_not_mask_a_role(self):
chosen, _ = sel.select(ALL, ["docs/x.md", "roles/docker/tasks/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_anything_else_selects_everything(self):
for path in ("galaxy.yml", "meta/runtime.yml", "plugins/modules/x.py", "extensions/molecule/image-smoke/molecule.yml",
".gitea/workflows/molecule.yml", "scripts/select_molecule_scenarios.py",
"tests/unit/x.py",
"new_top_level_file", "roles/README.md"):
chosen, _ = sel.select(ALL, ["roles/docker/tasks/main.yml", path])
self.assertEqual(chosen, ALL, path)
def test_deleted_role_selects_nothing_of_its_own(self):
chosen, _ = sel.select(ALL, ["roles/gone/tasks/main.yml"])
self.assertEqual(chosen, [])
def test_ignored_patterns_are_not_prefix_tricks(self):
chosen, _ = sel.select(ALL, ["docsx/y"])
self.assertEqual(chosen, ALL)
class MainTest(unittest.TestCase):
def setUp(self):
# main() runs git in the current directory: a hook's GIT_DIR must not redirect it.
patcher = mock.patch.dict(os.environ)
patcher.start()
self.addCleanup(patcher.stop)
for key in [k for k in os.environ if k.startswith("GIT_")]:
del os.environ[key]
def run_main(self, argv, env):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = sel.main(["x"] + argv, env)
return code, out.getvalue().split(), err.getvalue()
def make_repo(self, root):
for rel in ("extensions/molecule/image-smoke", "roles/docker/molecule/default", "roles/fail2ban/molecule/default"):
d = pathlib.Path(root, rel)
d.mkdir(parents=True)
(d / "molecule.yml").write_text("---\n")
def git(self, root, *args):
# No GIT_* from the caller (a hook exports GIT_DIR), no user or system config.
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env.update(GIT_CONFIG_GLOBAL="/dev/null", GIT_CONFIG_NOSYSTEM="1")
subprocess.run(["git", "-C", root, "-c", "user.name=t", "-c", "[email protected]",
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True, env=env)
def topic_repo(self, root, files):
"""A repo on `topic` whose one commit over `main` adds `files` (relative path -> text)."""
self.make_repo(root)
self.git(root, "init", "-q", "-b", "main")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "base")
self.git(root, "switch", "-qc", "topic")
for rel, text in files.items():
f = pathlib.Path(root, rel)
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(text)
self.git(root, "add", "-A")
self.git(root, "commit", "-q", "--allow-empty", "-m", "change")
def in_dir(self, root):
cwd = os.getcwd()
os.chdir(root)
self.addCleanup(os.chdir, cwd)
def test_pull_request_is_narrowed_and_push_is_not(self):
with tempfile.TemporaryDirectory() as root:
self.make_repo(root)
self.git(root, "init", "-q", "-b", "main")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "base")
self.git(root, "switch", "-qc", "topic")
pathlib.Path(root, "roles/docker/tasks").mkdir()
pathlib.Path(root, "roles/docker/tasks/main.yml").write_text("---\n")
self.git(root, "add", "-A")
self.git(root, "commit", "-q", "--allow-empty", "-m", "change")
cwd = os.getcwd()
os.chdir(root)
try:
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, ["roles/docker/molecule/default"]))
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "push"})
self.assertEqual(len(out), 3)
code, out, _ = self.run_main([], {"EVENT_NAME": "pull_request"})
self.assertEqual(len(out), 3)
code, out, err = self.run_main(["no-such-ref"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3))
self.assertIn("::warning::", err)
finally:
os.chdir(cwd)
def test_empty_base_ref_argument_runs_all(self):
with tempfile.TemporaryDirectory() as root:
self.make_repo(root)
self.in_dir(root)
code, out, _ = self.run_main([""], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3))
def test_changed_role_without_a_scenario_fails(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {"roles/newrole/tasks/main.yml": "---\n"})
self.in_dir(root)
code, out, err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (1, []))
self.assertIn("::error::changed role without a molecule scenario: newrole", err)
def test_deleted_role_is_not_an_error(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {})
self.git(root, "rm", "-rq", "roles/fail2ban")
self.git(root, "commit", "-qm", "drop")
self.in_dir(root)
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, []))
def test_ignored_only_diff_passes_empty(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {"docs/a.md": "x\n"})
self.in_dir(root)
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, []))
def test_non_utf8_path_does_not_crash(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {})
broot = os.fsencode(root)
os.makedirs(os.path.join(broot, b"docs"))
with open(os.path.join(broot, b"docs", b"\xff.md"), "wb") as f:
f.write(b"x\n")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "odd")
self.in_dir(root)
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, [])) # docs/* is ignored whatever the bytes
with open(os.path.join(broot, b"top\xff"), "wb") as f:
f.write(b"x")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "odd2")
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3)) # not ignored: everything
def test_too_many_arguments_is_usage(self):
code, out, err = self.run_main(["a", "b"], {})
self.assertEqual((code, out), (2, []))
self.assertIn("usage:", err)
def test_control_characters_are_escaped_in_notices(self):
self.assertEqual(sel.printable("a\n::add-mask::b"), "a\\n::add-mask::b")
_, reason = sel.select(ALL, ["zz\n::add-mask::foo"])
self.assertNotIn("\n", reason)
def test_no_scenario_at_all_fails(self):
with tempfile.TemporaryDirectory() as root:
cwd = os.getcwd()
os.chdir(root)
try:
code, out, _ = self.run_main([], {})
self.assertEqual((code, out), (1, []))
finally:
os.chdir(cwd)
def test_every_tracked_file_is_ignored_or_selects_everything_or_is_a_role_file(self):
tracked = subprocess.run(["git", "-C", str(REPO), "ls-files", "-z"], capture_output=True, check=True,
env={k: v for k, v in os.environ.items() if not k.startswith("GIT_")}).stdout
scenarios = sel.discover(str(REPO))
for raw in tracked.split(b"\0"):
if not raw:
continue
path = os.fsdecode(raw)
if sel.is_ignored(path) or path.startswith("roles/"):
continue
chosen, _ = sel.select(scenarios, [path], str(REPO))
self.assertEqual(chosen, scenarios, path)
def test_no_role_refers_to_another_role(self):
# The selection assumes roles are independent: a role that includes another would need a
# dependency rule in select(). Fail here instead of silently skipping the other's scenario.
roles = sorted(p.name for p in (REPO / "roles").iterdir() if p.is_dir())
for role in roles:
others = [r for r in roles if r != role]
for path in (REPO / "roles" / role).rglob("*"):
if not path.is_file():
continue
text = path.read_text(errors="ignore")
for other in others:
self.assertNotIn(f"mortis.kamino.{other}", text, f"{path.relative_to(REPO)} refers to {other}")
meta = REPO / "roles" / role / "meta" / "main.yml"
if meta.is_file():
data = yaml.safe_load(meta.read_text()) or {}
self.assertEqual(data.get("dependencies") or [], [], f"{role} declares role dependencies")
def test_literal_ignored_entries_exist(self):
for pattern in sel.IGNORED:
if "*" not in pattern:
self.assertTrue((REPO / pattern).exists(), f"{pattern} is on IGNORED but is not in the repository")
def test_discover_matches_the_repository(self):
found = sel.discover(str(REPO))
self.assertIn("extensions/molecule/image-smoke", found)
self.assertTrue(all((REPO / d / "molecule.yml").is_file() for d in found))
if __name__ == "__main__":
unittest.main()