diff --git a/.ansible-lint b/.ansible-lint index 3184737..2665ca0 100644 --- a/.ansible-lint +++ b/.ansible-lint @@ -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., 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. diff --git a/scripts/ansible-lint.sh b/scripts/ansible-lint.sh index ebdf8e9..9cbfc34 100755 --- a/scripts/ansible-lint.sh +++ b/scripts/ansible-lint.sh @@ -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., which the molecule scenarios' converge +# plays use) only resolve from an / 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 diff --git a/tests/scripts/test_ansible_lint_wrapper.py b/tests/scripts/test_ansible_lint_wrapper.py index b8300bb..136e7d2 100644 --- a/tests/scripts/test_ansible_lint_wrapper.py +++ b/tests/scripts/test_ansible_lint_wrapper.py @@ -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__":