ci(lint): resolve the Collection's own roles and drop mock_roles
Build / build (pull_request) Failing after 11s
Lint / lint (pull_request) Successful in 20s
Molecule / molecule (pull_request) Successful in 1s

Step 5 of #118. The scenarios' converge plays call the roles by FQCN (mortis.kamino.<role>), which only resolves from an ansible_collections/<namespace>/<name> directory, and a checkout is not one, so .ansible-lint listed the five roles in mock_roles and ansible-lint never checked those plays against the real roles.

scripts/ansible-lint.sh, which the ansible-lint hook runs in CI and locally, now links the checkout as ansible_collections/<namespace>/<name> in a temporary root (namespace and name read from galaxy.yml), puts that root first on ANSIBLE_COLLECTIONS_PATH and removes it on exit, so ansible-lint reads the checkout itself. Removing mock_roles reproduced five syntax-check[specific] role-not-found errors; with the link the run passes with no warnings, locally and with CI's preset path. A bare ansible-lint, outside the hook, does not get the link; .ansible-lint says so.

No image input changes: .pre-commit-config.yaml, requirements and images/** are untouched, so no version bump or second pull request. Closes the last open item of #118.

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 15:38:34 +00:00
1 parent 8c743c125a
commit 3289c0d430
3 files changed
+103 -20

No files matched your search

+4 -11
View File
@@ -11,16 +11,9 @@ exclude_paths:
- changelogs
- images
# The Collection is checked out outside an ansible_collections/mortis/kamino path (CI clones it
# into the workspace), so ansible-lint cannot resolve a role of this Collection by its FQCN in
# a scenario's converge play. List the roles the scenarios call by FQCN.
mock_roles:
- mortis.kamino.docker
- mortis.kamino.fail2ban
- mortis.kamino.network_interfaces
- mortis.kamino.system_baseline
- mortis.kamino.systemd_hardening
# The collections of the Collection's dependencies (galaxy.yml) are pinned in requirements.yml and
# resolved offline: the ci image bakes them into /opt/collections and scripts/dev-setup.sh installs
# them into .ansible/collections, so their modules are linted, not mocked.
# them into .ansible/collections, so their modules are linted, not mocked. The Collection's own role
# names (mortis.kamino.<role>, used by the scenarios) resolve the same way: scripts/ansible-lint.sh,
# which the hook runs, links the checkout as ansible_collections/mortis/kamino. A bare `ansible-lint`
# does not do that and reports the role names as not found; run it through the hook.
+22 -1
View File
@@ -7,6 +7,12 @@
# ones CI tests against (#118, #80). So when the variable is unset, this script uses the collections
# scripts/dev-setup.sh installed into .ansible/collections of this clone, and fails with the fix
# when they are missing. That covers `git commit` and a bare `pre-commit run` alike.
#
# The Collection's own role names (mortis.kamino.<role>, which the molecule scenarios' converge
# plays use) only resolve from an <namespace>/<name> directory under an ansible_collections root,
# and a checkout is not one. So the checkout is linked into a temporary root, put first on the
# collections path, and ansible-lint reads the checkout itself through it (#118 step 5). The link
# is removed on exit.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -21,4 +27,19 @@ if [ -z "${ANSIBLE_COLLECTIONS_PATH:-}" ]; then
export ANSIBLE_COLLECTIONS_PATH="$root/.ansible/collections"
fi
exec ansible-lint --offline --nocolor
# The Collection's own name, from galaxy.yml, so a rename needs no edit here.
namespace="$(sed -n 's/^namespace: *//p' galaxy.yml)"
name="$(sed -n 's/^name: *//p' galaxy.yml)"
if [ -z "$namespace" ] || [ -z "$name" ]; then
echo "error: no namespace and name in $root/galaxy.yml" >&2
exit 1
fi
link_root="$(mktemp -d)"
trap 'rm -rf "$link_root"' EXIT
mkdir -p "$link_root/ansible_collections/$namespace"
ln -s "$root" "$link_root/ansible_collections/$namespace/$name"
export ANSIBLE_COLLECTIONS_PATH="$link_root:$ANSIBLE_COLLECTIONS_PATH"
# Not exec: the trap above has to run when ansible-lint ends.
ansible-lint --offline --nocolor
+77 -8
View File
@@ -14,15 +14,34 @@ import unittest
SCRIPT = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "ansible-lint.sh"
# Prints what the wrapper hands to ansible-lint: its arguments, directory and the two variables.
# Prints what the wrapper hands to ansible-lint: its arguments, directory, the two variables and
# the temporary collections root (the first element of the path) with every link inside it.
STUB = """#!/bin/sh
first="${ANSIBLE_COLLECTIONS_PATH%%:*}"
echo "args=$*"
echo "cwd=$(pwd -P)"
echo "home=${ANSIBLE_HOME-unset}"
echo "path=${ANSIBLE_COLLECTIONS_PATH-unset}"
echo "first=$first"
for link in "$first"/ansible_collections/*/*; do
echo "link=${link#"$first"/ansible_collections/} -> $(readlink "$link")"
done
exit "${STUB_EXIT:-0}"
"""
def parsed(stdout):
"""{key: value} of the stub's output; `link` may repeat, so it is collected in a list."""
out = {"link": []}
for line in stdout.splitlines():
key, _, value = line.partition("=")
if key == "link":
out["link"].append(value)
else:
out[key] = value
return out
@unittest.skipUnless(shutil.which("bash"), "bash is required")
class AnsibleLintWrapperTest(unittest.TestCase):
def setUp(self):
@@ -31,12 +50,18 @@ class AnsibleLintWrapperTest(unittest.TestCase):
self.repo = self.tmp / "repo"
(self.repo / "scripts").mkdir(parents=True)
shutil.copy(SCRIPT, self.repo / "scripts" / "ansible-lint.sh")
self.galaxy("mortis", "kamino")
self.bin = self.tmp / "bin"
self.bin.mkdir()
stub = self.bin / "ansible-lint"
stub.write_text(STUB)
stub.chmod(0o755)
def galaxy(self, namespace, name):
(self.repo / "galaxy.yml").write_text(
f"---\nnamespace: {namespace}\nname: {name}\nversion: 1.0.0\n"
)
def run_wrapper(self, cwd=None, **env):
base = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.tmp)}
return subprocess.run(
@@ -57,16 +82,60 @@ class AnsibleLintWrapperTest(unittest.TestCase):
self.install_collections()
result = self.run_wrapper()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("args=--offline --nocolor", result.stdout)
self.assertIn(f"home={self.repo / '.ansible'}", result.stdout)
self.assertIn(f"path={self.repo / '.ansible' / 'collections'}", result.stdout)
seen = parsed(result.stdout)
self.assertEqual(seen["args"], "--offline --nocolor")
self.assertEqual(seen["home"], str(self.repo / ".ansible"))
# The temporary link root comes first, then the clone's pinned collections.
self.assertEqual(
seen["path"], f"{seen['first']}:{self.repo / '.ansible' / 'collections'}"
)
def test_leaves_a_preset_collections_path_alone(self):
def test_leaves_a_preset_collections_path_after_the_link_root(self):
# CI sets it (the ci image bakes the collections into /opt/collections), even with none in the clone.
result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("path=/opt/collections", result.stdout)
self.assertIn("home=unset", result.stdout)
seen = parsed(result.stdout)
self.assertEqual(seen["path"], f"{seen['first']}:/opt/collections")
self.assertEqual(seen["home"], "unset")
def test_links_the_checkout_as_the_collection(self):
result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
parsed(result.stdout)["link"], [f"mortis/kamino -> {self.repo}"]
)
def test_takes_the_collection_name_from_galaxy_yml(self):
self.galaxy("acme", "widgets")
result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
parsed(result.stdout)["link"], [f"acme/widgets -> {self.repo}"]
)
def test_fails_without_a_namespace_and_name(self):
(self.repo / "galaxy.yml").write_text("---\nversion: 1.0.0\n")
result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections")
self.assertNotEqual(result.returncode, 0)
self.assertIn("galaxy.yml", result.stderr)
self.assertNotIn("args=", result.stdout)
def test_removes_the_link_root_afterwards(self):
result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections")
first = pathlib.Path(parsed(result.stdout)["first"])
self.assertNotEqual(first, pathlib.Path("/opt/collections"))
self.assertFalse(first.exists())
# The checkout itself is untouched: only the link went.
self.assertTrue((self.repo / "galaxy.yml").is_file())
def test_removes_the_link_root_and_keeps_the_exit_code_when_ansible_lint_fails(
self,
):
result = self.run_wrapper(
ANSIBLE_COLLECTIONS_PATH="/opt/collections", STUB_EXIT="3"
)
self.assertEqual(result.returncode, 3)
self.assertFalse(pathlib.Path(parsed(result.stdout)["first"]).exists())
def test_fails_with_the_fix_when_the_collections_are_not_installed(self):
result = self.run_wrapper()
@@ -80,7 +149,7 @@ class AnsibleLintWrapperTest(unittest.TestCase):
elsewhere.mkdir()
result = self.run_wrapper(cwd=elsewhere)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(f"cwd={self.repo}", result.stdout)
self.assertEqual(parsed(result.stdout)["cwd"], str(self.repo))
if __name__ == "__main__":