From 5da3579d3e2a895b79824ce4d2db23cb327e8da5 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 03:01:19 +0400 Subject: [PATCH] fix: address the review findings on the per-task overhead change - Require ansible-core 2.21: the deploy CLI refuses a venv whose packages differ from the exact pins of the deploy extra, the carrier action names the version it needs instead of failing on an import, and the image installs the pinned ansible from pyproject.toml. - Lint: catch compact == comparisons, scan compose/, inventories/ and both playbooks, flag bare services/packages/getent_* reads, and derive the allowlist from ansible-core's variable map and the plugins' documented options. - Tag the play environment freeze and check with always, and cover a task override, a handler, a delegated task and a tagged run. - Map a failed docker.service query to its fail_msg. - Pin the docker_cached options to the installed stock connection, read the carrier through hostvars in a two-host test, and correct the carrier guard message and the stale README line reference. Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 2 +- cli/administration/deploy/dedicated/runner.py | 18 ++- playbook.yml | 12 +- plugins/action/applications_carrier.py | 18 ++- plugins/connection/docker_cached.py | 12 +- .../tasks/01_assert_requirements.yml | 3 +- .../test_applications_carrier.py | 50 ++++-- .../connection_plugins/test_docker_cached.py | 56 ++++++- .../playbooks/test_play_environment_frozen.py | 79 ++++++++-- .../test_no_deprecated_ansible_patterns.py | 149 ++++++++++++++---- .../deploy/dedicated/test_runner.py | 20 +++ .../action/test_applications_carrier.py | 12 ++ utils/cache/README.md | 2 +- utils/cache/carrier.py | 8 +- 14 files changed, 365 insertions(+), 76 deletions(-) diff --git a/Dockerfile b/Dockerfile index b3ac4fb1be..95c5c4335e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,7 +57,7 @@ RUN set -euo pipefail; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PYTHON_INSTALL_SCRIPT:?}" ensure; \ VENV="${INFINITO_VENV_DIR}" bash "${INFINITO_SRC_DIR}/scripts/install/venv.sh"; \ ${PIP} install --upgrade pip setuptools wheel; \ - ${PIP} install ansible PyYAML; \ + ${PIP} install "$(grep -oE '"ansible==[^"]+"' "${INFINITO_SRC_DIR}/pyproject.toml" | tr -d '"')" PyYAML; \ ANSIBLE_COLLECTIONS_DIR="${HOME}/.ansible/collections" \ bash "${INFINITO_SRC_DIR}/scripts/install/ansible.sh" diff --git a/cli/administration/deploy/dedicated/runner.py b/cli/administration/deploy/dedicated/runner.py index 7dcd8e144d..d30eb87256 100644 --- a/cli/administration/deploy/dedicated/runner.py +++ b/cli/administration/deploy/dedicated/runner.py @@ -24,28 +24,37 @@ from utils.cache.files import read_text from .proc import run, run_make _REQUIREMENT_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") +_EXACT_PIN = re.compile(r"([A-Za-z0-9][A-Za-z0-9._-]*)\s*==\s*([^\s;,]+)\s*$") def deploy_ansible_playbook(repo_root: str) -> str: """ Return the ansible-playbook of the running interpreter once that - interpreter carries every distribution of the `deploy` extra. + interpreter carries every distribution of the `deploy` extra, each + exact `==` pin at its pinned version. Args: repo_root: checkout whose pyproject.toml declares the `deploy` extra Returns: absolute path of the ansible-playbook next to sys.executable Exits: - 1 when a `deploy` distribution or that ansible-playbook is missing + 1 when a `deploy` distribution is missing or off its `==` pin, or that + ansible-playbook is missing """ pyproject = tomllib.loads(read_text(str(Path(repo_root) / "pyproject.toml"))) missing: list[str] = [] + stale: list[str] = [] for requirement in pyproject["project"]["optional-dependencies"]["deploy"]: name = _REQUIREMENT_NAME.match(requirement) try: - importlib.metadata.distribution(name.group(0)) + installed = importlib.metadata.distribution(name.group(0)).version except importlib.metadata.PackageNotFoundError: missing.append(requirement) + continue + pin = _EXACT_PIN.match(requirement) + if pin and installed != pin.group(2): + missing.append(requirement) + stale.append(f"{requirement} (installed: {installed})") ansible_playbook = Path(sys.executable).parent / "ansible-playbook" if missing: @@ -54,7 +63,8 @@ def deploy_ansible_playbook(repo_root: str) -> str: f"\n[ERROR] The deploy interpreter {sys.executable} lacks " f"{', '.join(missing)} from the `deploy` extra of " f"{repo_root}/pyproject.toml.\n" - f" Install them with: {sys.executable} -m pip install {quoted}\n" + + (f" Pinned but different: {', '.join(stale)}\n" if stale else "") + + f" Install them with: {sys.executable} -m pip install {quoted}\n" " or launch the CLI from the venv `make install` provisions.\n", file=sys.stderr, ) diff --git a/playbook.yml b/playbook.yml index b445f627fd..ad6b08a3b7 100644 --- a/playbook.yml +++ b/playbook.yml @@ -21,7 +21,11 @@ gather_facts: false pre_tasks: - name: "🧊 Render the play environment once for this host" - ansible.builtin.include_tasks: tasks/utils/play/environment/freeze.yml + ansible.builtin.include_tasks: + file: tasks/utils/play/environment/freeze.yml + apply: + tags: [always] + tags: [always] - name: "🐍 Link the managed Python interpreter before any module needs it" ansible.builtin.script: scripts/system/python/managed_interpreter.sh @@ -45,5 +49,9 @@ include_tasks: "tasks/stages/03_destructor.yml" post_tasks: - name: "✅ Check the play environment against its sources" - ansible.builtin.include_tasks: tasks/utils/play/environment/check.yml + ansible.builtin.include_tasks: + file: tasks/utils/play/environment/check.yml + apply: + tags: [always] + tags: [always] become: true diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index 51bbf87770..5c95648413 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -8,7 +8,9 @@ as non-persistent host variables, the layer ``set_fact`` writes; every later worker inherits them at fork time and ``get_merged_applications`` / ``get_merged_users`` serve them instead of rendering. They stay out of the fact cache on purpose: ``get_vars`` deep-copies every fact before every task, -and these are the whole rendered trees. The users carrier is keyed like the applications carrier plus +and these are the whole rendered trees. The action also registers an empty +cacheable layer, as ``set_fact`` does, so ansible-core never copies a result's +``ansible_facts`` into the fact cache. The users carrier is keyed like the applications carrier plus the token store digest and ``inventory_hostname``:: - name: 🧊 Render the applications SPOT once and carry it into every task's worker @@ -53,9 +55,10 @@ from __future__ import annotations from typing import Any +from ansible import release from ansible.errors import AnsibleActionFail from ansible.module_utils.parsing.convert_bool import boolean -from ansible.plugins.action import ActionBase, VariableLayer +from ansible.plugins.action import ActionBase from ansible.plugins.loader import lookup_loader from plugins.lookup.email import provider_view_carrier @@ -67,6 +70,11 @@ from utils.cache.carrier import ( revalidate_tokens_file, ) +try: + from ansible.plugins.action import VariableLayer +except ImportError: + VariableLayer = None + class ActionModule(ActionBase): TRANSFERS_FILES = False @@ -74,6 +82,12 @@ class ActionModule(ActionBase): def run( self, tmp: Any = None, task_vars: dict[str, Any] | None = None ) -> dict[str, Any]: + if VariableLayer is None: + raise AnsibleActionFail( + "applications_carrier needs ansible-core 2.21 or newer, found " + f"{release.__version__}; install the `deploy` extra of " + "pyproject.toml (make install-python)" + ) result = super().run(tmp, task_vars) task_vars = task_vars or {} args = self._task.args or {} diff --git a/plugins/connection/docker_cached.py b/plugins/connection/docker_cached.py index 63676db22a..0f8a04f4b6 100644 --- a/plugins/connection/docker_cached.py +++ b/plugins/connection/docker_cached.py @@ -1,12 +1,14 @@ -"""The community.docker docker connection, asking the Docker CLI for its version once per run. +"""The community.docker docker connection, asking the Docker CLI for its version at the start of a run. The stock plugin builds a fresh connection in every forked worker, and with a remote user set it runs ``docker version`` twice before every module run (the first probe never matches a current Docker). This subclass keeps the answer in a file under the run's ``DEFAULT_LOCAL_TMP``, which every worker inherits from the ``ansible-playbook`` process and which Ansible removes when the run ends, -so only the first task-host of a run pays for the version query. Everything -else (user, become, file transfer, timeouts, environment) is the stock plugin's. +so only the workers that start before the first answer is written pay for the +version query. The file is replaced atomically, so a concurrent writer never +leaves a partial answer. Everything else (user, become, file transfer, +timeouts, environment) is the stock plugin's. """ from __future__ import annotations @@ -24,8 +26,8 @@ DOCUMENTATION = r""" name: docker_cached short_description: Run tasks in docker containers, with the Docker version cached per run description: - - The community.docker docker connection, except that the Docker CLI version is queried once per - ansible-playbook run and shared by every forked worker. + - The community.docker docker connection, except that the Docker CLI version is queried at the start + of an ansible-playbook run and shared by every forked worker that starts after the first answer. options: remote_addr: description: diff --git a/roles/sys-svc-container/tasks/01_assert_requirements.yml b/roles/sys-svc-container/tasks/01_assert_requirements.yml index dc5c78b9e1..9cc6b4550a 100644 --- a/roles/sys-svc-container/tasks/01_assert_requirements.yml +++ b/roles/sys-svc-container/tasks/01_assert_requirements.yml @@ -13,8 +13,7 @@ - name: ✅ Assert docker service exists ansible.builtin.assert: that: - - sys_svc_container_docker_unit.status is defined - - sys_svc_container_docker_unit.status.LoadState != 'not-found' + - sys_svc_container_docker_unit.status.LoadState | default('not-found') != 'not-found' fail_msg: > docker.service is not registered in systemd. Docker engine does not appear to be installed. diff --git a/tests/integration/ansible/action_plugins/test_applications_carrier.py b/tests/integration/ansible/action_plugins/test_applications_carrier.py index cc1fe173aa..8cca57fc74 100644 --- a/tests/integration/ansible/action_plugins/test_applications_carrier.py +++ b/tests/integration/ansible/action_plugins/test_applications_carrier.py @@ -8,8 +8,9 @@ readers consult, and every lookup renders the payload again. These cases run real Ansible with fake ``applications`` and ``users`` lookups in front of the real ``applications_carrier`` action: the carrier must be -visible to a later task's worker with injection on and off and never sit in -``ansible_facts``. The hazard case parks a carrier the old way, as a fact, so +visible to a later task's worker with injection on and off, never sit in +``ansible_facts``, and reach another host through ``hostvars``, the path the +mail provider view reads. The hazard case parks a carrier the old way, as a fact, so the reader guard is shown to turn the invisible carrier into a failed task. """ @@ -136,13 +137,33 @@ HAZARD_PLAY = """--- """ -def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None]: +CROSS_HOST_PLAY = f"""--- +- name: Park the carrier on two hosts and read the other host's through hostvars + hosts: all + gather_facts: false + tasks: + - name: Park the carrier + applications_carrier: {{}} + + - name: Read node2's carrier on node1, the way the provider view does + ansible.builtin.copy: + dest: "{{{{ probe_out }}}}" + content: "{{{{ hostvars['node2'][{APPLICATIONS_RENDERED_FACT!r}].key | to_json }}}}" + mode: "0644" + when: inventory_hostname == 'node1' +""" + + +def _run( + workdir: Path, play: str, inject: bool, inventory: str +) -> tuple[int, str, dict | list | None]: """Run *play* once with fact injection set to *inject*. Args: workdir: an empty directory to build the plugins and the play in. play: the playbook text. inject: the value of ``ANSIBLE_INJECT_FACT_VARS``. + inventory: the comma-separated host list passed to ``-i``. Returns: ``(exit code, combined output, probe report or None)``. @@ -175,7 +196,7 @@ def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None] [ "ansible-playbook", "-i", - "localhost,", + inventory, "-c", "local", str(workdir / "play.yml"), @@ -194,14 +215,25 @@ def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None] @unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): - def _play(self, play: str, inject: bool) -> tuple[int, str, dict | None]: + def _play( + self, play: str, inject: bool, inventory: str + ) -> tuple[int, str, dict | list | None]: with tempfile.TemporaryDirectory() as tmp: - return _run(Path(tmp), play, inject) + return _run(Path(tmp), play, inject, inventory) + + def test_another_host_reads_the_carrier_through_hostvars(self): + for inject in (True, False): + with self.subTest(inject=inject): + code, output, report = self._play( + CROSS_HOST_PLAY, inject, inventory="node1,node2," + ) + self.assertEqual(code, 0, output) + self.assertEqual(report, APPLICATIONS_KEY) def test_the_carrier_reaches_later_workers_outside_the_fact_cache(self): for inject in (True, False): with self.subTest(inject=inject): - code, output, report = self._play(CARRIER_PLAY, inject) + code, output, report = self._play(CARRIER_PLAY, inject, "localhost,") self.assertEqual(code, 0, output) self.assertNotIn("template error", output) self.assertEqual( @@ -214,7 +246,7 @@ class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): ) def test_a_fact_parked_carrier_is_visible_only_while_facts_are_injected(self): - code, output, report = self._play(HAZARD_PLAY, True) + code, output, report = self._play(HAZARD_PLAY, True, "localhost,") self.assertEqual(code, 0, output) self.assertEqual( report, @@ -228,7 +260,7 @@ class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): ) def test_the_reader_fails_on_a_fact_parked_carrier_without_injection(self): - code, output, report = self._play(HAZARD_PLAY, False) + code, output, report = self._play(HAZARD_PLAY, False, "localhost,") self.assertNotEqual(code, 0, output) self.assertIsNone(report) self.assertIn("not visible as a variable", output) diff --git a/tests/integration/ansible/connection_plugins/test_docker_cached.py b/tests/integration/ansible/connection_plugins/test_docker_cached.py index 4a59ee58f1..393a3e8e00 100644 --- a/tests/integration/ansible/connection_plugins/test_docker_cached.py +++ b/tests/integration/ansible/connection_plugins/test_docker_cached.py @@ -6,9 +6,12 @@ gets a fresh connection in a fresh worker. ``docker_cached`` keeps the answer for the run. These cases run the same play through both plugins against a stand-in ``docker`` executable that logs every call and runs the exec payload locally: the cached plugin must make the same exec calls with the same -results, and only the first task-host may query the version. +results, and only the first task-host may query the version. A static case +checks that the options the plugin copies still resolve like those of the +installed stock connection. """ +import ast import json import os import shutil @@ -19,10 +22,15 @@ import unittest from pathlib import Path from typing import ClassVar +from ansible_collections.community.docker.plugins.connection import docker + from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_str from . import PROJECT_ROOT +PLUGIN = PROJECT_ROOT / "plugins" / "connection" / "docker_cached.py" + SHIM = f"""#!{sys.executable} import json import os @@ -215,5 +223,51 @@ class TestDockerCachedConnection(unittest.TestCase): self.assertEqual(files["templated.txt"], "templated node1\n") +def _behaviour(options: dict) -> dict: + """Reduce plugin options to the fields that change how they resolve. + + Args: + options: the ``options`` mapping of a connection plugin's DOCUMENTATION. + + Returns: + Per option its type, default, choices, aliases and the env, ini and + vars sources it reads, without descriptions or ``version_added``. + """ + return { + name: { + "type": spec.get("type"), + "default": spec.get("default"), + "choices": spec.get("choices"), + "aliases": spec.get("aliases"), + "env": [entry["name"] for entry in spec.get("env") or []], + "ini": [ + (entry["section"], entry["key"]) for entry in spec.get("ini") or [] + ], + "vars": [entry["name"] for entry in spec.get("vars") or []], + } + for name, spec in options.items() + } + + +class TestDocumentationMatchesTheStockPlugin(unittest.TestCase): + def test_every_option_resolves_like_the_installed_stock_option(self): + module = ast.parse(read_text(str(PLUGIN))) + ours = next( + node.value.value + for node in module.body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "DOCUMENTATION" + for target in node.targets + ) + ) + self.assertEqual( + _behaviour(load_yaml_str(ours)["options"]), + _behaviour(load_yaml_str(docker.DOCUMENTATION)["options"]), + "docker_cached copies the stock connection's options; after a " + "community.docker bump, copy the changed options again", + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/integration/ansible/playbooks/test_play_environment_frozen.py b/tests/integration/ansible/playbooks/test_play_environment_frozen.py index 90de1f4279..604a2deb9c 100644 --- a/tests/integration/ansible/playbooks/test_play_environment_frozen.py +++ b/tests/integration/ansible/playbooks/test_play_environment_frozen.py @@ -7,7 +7,9 @@ end of the play and fails when a source changed after the freeze, because every task after the change ran with the stale value. These cases run real Ansible with the two shared task files: the frozen value -reaches a module's environment, and a source changed mid-play fails the check. +reaches a task, a handler and a delegated task while a task's own +``environment:`` still wins, a source changed mid-play fails the check, and a +``--tags`` run still freezes and checks. """ import shutil @@ -36,35 +38,65 @@ PLAY = f"""--- environment: "{{{{ PLAY_ENVIRONMENT }}}}" pre_tasks: - name: Freeze - ansible.builtin.include_tasks: {FREEZE} + ansible.builtin.include_tasks: + file: {FREEZE} + apply: + tags: [always] + tags: [always] tasks: - name: Report the value a module sees - ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_out }}}}" + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/task" + changed_when: true + notify: Report the value a handler sees + tags: [probe] + + - name: Report the value a task with its own environment sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/override" + environment: + PROBE_VALUE: own changed_when: false + tags: [probe] + + - name: Report the value a delegated task sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/delegated" + delegate_to: localhost + changed_when: false + tags: [probe] - name: Change the source mid-play ansible.builtin.set_fact: probe_source: changed when: change_source | bool + tags: [probe] + handlers: + - name: Report the value a handler sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/handler" + changed_when: false post_tasks: - name: Check - ansible.builtin.include_tasks: {CHECK} + ansible.builtin.include_tasks: + file: {CHECK} + apply: + tags: [always] + tags: [always] """ +PROBES = ("task", "override", "delegated", "handler") -def _run(change_source: bool) -> tuple[int, str, str]: + +def _run(change_source: bool, tags: list[str]) -> tuple[int, str, dict[str, str]]: """Run the play once. Args: change_source: whether the play changes the source after the freeze. + tags: the ``--tags`` to pass, none for a full run. Returns: - ``(exit code, combined output, value the module saw)``. + ``(exit code, combined output, value each probe saw)``. """ with tempfile.TemporaryDirectory() as tmp: workdir = Path(tmp) (workdir / "play.yml").write_text(PLAY, encoding="utf-8") - probe_out = workdir / "probe.txt" result = subprocess.run( [ "ansible-playbook", @@ -74,30 +106,49 @@ def _run(change_source: bool) -> tuple[int, str, str]: "local", str(workdir / "play.yml"), "-e", - f"probe_out={probe_out}", + f"probe_dir={workdir}", "-e", f"change_source={change_source}", + *[f"--tags={tag}" for tag in tags], ], cwd=str(workdir), capture_output=True, text=True, check=False, ) - seen = read_text(str(probe_out)) if probe_out.exists() else "" + seen = { + probe: read_text(str(workdir / probe)) + for probe in PROBES + if (workdir / probe).exists() + } return result.returncode, result.stdout + result.stderr, seen @unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") class TestPlayEnvironmentFrozen(unittest.TestCase): - def test_a_module_sees_the_frozen_value_and_the_check_passes(self): - code, output, seen = _run(change_source=False) + def test_tasks_handlers_and_delegates_see_the_frozen_value(self): + code, output, seen = _run(change_source=False, tags=[]) self.assertEqual(code, 0, output) - self.assertEqual(seen, "frozen") + self.assertEqual( + seen, + { + "task": "frozen", + "override": "own", + "delegated": "frozen", + "handler": "frozen", + }, + ) def test_a_source_changed_mid_play_fails_the_check(self): - code, output, seen = _run(change_source=True) + code, output, seen = _run(change_source=True, tags=[]) self.assertNotEqual(code, 0, output) - self.assertEqual(seen, "frozen") + self.assertEqual(seen["task"], "frozen") + self.assertIn("A source of the play environment changed", output) + + def test_a_tagged_run_still_freezes_and_checks(self): + code, output, seen = _run(change_source=True, tags=["probe"]) + self.assertNotEqual(code, 0, output) + self.assertEqual(seen["task"], "frozen") self.assertIn("A source of the play environment changed", output) diff --git a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py index efaf737124..68030a690e 100644 --- a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py +++ b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py @@ -18,36 +18,96 @@ Forbidden (with fix): * top-level injected facts (``ansible_os_family``, ``ansible_eth0`` and every other ``ansible_``) -- ``ansible.cfg`` turns fact injection off, so a top-level fact is undefined. Use ``ansible_facts['']``. Every - ``ansible_`` that is not a magic or connection variable - (``ALLOWED_NAMES``, ``ALLOWED_PREFIXES``) counts as a fact. The ``(?!=)`` + ``ansible_`` that is not a magic variable (``MAGIC_NAMES``) or a + variable a connection, become or shell plugin declares for its options (read + from the plugins' ``DOCUMENTATION``) counts as a fact. The facts that + ``service_facts``, ``package_facts`` and ``getent`` set without the prefix + (``services``, ``packages``, ``getent_``) are flagged when read bare + inside a Jinja expression or a condition line. The ``(?!=(?!=))`` guard skips a literal log label such as ``ansible_virtualization_type={{ ... - }}`` (name glued to ``=``) while still flagging a comparison like - ``ansible_os_family == 'X'`` (space before ``==``). In Python the rule reads + }}`` (name glued to a single ``=``) while still flagging a comparison like + ``ansible_os_family == 'X'`` or ``ansible_os_family=='X'``. In Python the rule reads only subscript and ``.get`` keys, the shape of a variable read. Scans ``.yml`` / ``.yaml`` / ``.j2`` under roles/, tasks/, group_vars/, -playbooks/ and the playbook, and ``.py`` outside tests/ and role ``files/``. Mark a genuine +playbooks/, compose/, inventories/ and both playbooks, and ``.py`` outside +tests/ and role ``files/``. Mark a genuine exception with ``# nocheck: deprecated-ansible`` same-or-above the line. """ from __future__ import annotations +import ast import re import unittest from pathlib import Path +from ansible import constants + from utils.annotations.suppress import is_suppressed_at from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_str from . import PROJECT_ROOT _RULE = "deprecated-ansible" SCAN_SUFFIXES = (".yml", ".yaml", ".j2", ".py") -_YAML_PREFIXES = ("roles/", "tasks/", "group_vars/", "playbooks/", "playbook.yml") +_YAML_PREFIXES = ( + "roles/", + "tasks/", + "group_vars/", + "playbooks/", + "compose/", + "inventories/", + "playbook.yml", + "playbook-sync.yml", +) _PY_EXCLUDED_PREFIXES = ("tests/",) _PY_EXCLUDED_PARTS = ("/files/",) +_ANSIBLE_PLUGINS = Path(constants.__file__).parent / "plugins" +_PLUGIN_DOC_DIRS = ( + _ANSIBLE_PLUGINS / "connection", + _ANSIBLE_PLUGINS / "become", + _ANSIBLE_PLUGINS / "shell", + _ANSIBLE_PLUGINS / "doc_fragments", + PROJECT_ROOT / "plugins" / "connection", +) -ALLOWED_NAMES = frozenset( + +def declared_plugin_vars(directories: tuple[Path, ...]) -> frozenset[str]: + """Return every ``ansible_*`` variable a plugin option declares under ``vars:``. + + Args: + directories: plugin directories whose ``.py`` files carry a + ``DOCUMENTATION`` string, at module or class level. + + Returns: + The declared variable names. + """ + names: set[str] = set() + for directory in directories: + for path in sorted(directory.glob("*.py")): + for node in ast.walk(ast.parse(read_text(str(path)))): + if not ( + isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "DOCUMENTATION" + for target in node.targets + ) + and isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str) + ): + continue + options = (load_yaml_str(node.value.value) or {}).get("options") or {} + for option in options.values(): + for var in (option or {}).get("vars") or []: + name = var.get("name", "") if isinstance(var, dict) else "" + if name.startswith("ansible_"): + names.add(name) + return frozenset(names) + + +MAGIC_NAMES = frozenset( { "ansible_facts", "ansible_local", @@ -80,29 +140,27 @@ ALLOWED_NAMES = frozenset( "ansible_failed_task", "ansible_failed_result", "ansible_job_id", - "ansible_host", - "ansible_port", - "ansible_user", - "ansible_password", - "ansible_connection", - "ansible_private_key_file", - "ansible_pipelining", - "ansible_timeout", - "ansible_remote_tmp", - "ansible_docker_extra_args", } ) -ALLOWED_PREFIXES = ( - "ansible_become", - "ansible_ssh_", - "ansible_shell_", - "ansible_winrm_", - "ansible_paramiko_", +ALLOWED_NAMES = ( + MAGIC_NAMES + | declared_plugin_vars(_PLUGIN_DOC_DIRS) + | frozenset( + name for names in constants.MAGIC_VARIABLE_MAPPING.values() for name in names + ) ) ALLOWED_SUFFIXES = ("_interpreter",) -_YAML_NAME = re.compile(r"\bansible_[A-Za-z0-9_]+\b(?!=)") +_YAML_NAME = re.compile(r"\bansible_[A-Za-z0-9_]+\b(?!=(?!=))") _PY_NAME = re.compile(r"(?:\[\s*|\.get\(\s*)[\"'](ansible_[A-Za-z0-9_]+)[\"']") +_BARE_FACT = re.compile( + r"(?.*)$" +) _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( ( @@ -117,6 +175,10 @@ _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( ), ) _FACT_FIX = "top-level injected fact, undefined with fact injection off -> use ansible_facts['']" +_BARE_FACT_FIX = ( + "fact without the ansible_ prefix (service_facts, package_facts, getent), " + "undefined with fact injection off -> use ansible_facts['']" +) def is_fact_name(name: str) -> bool: @@ -126,22 +188,20 @@ def is_fact_name(name: str) -> bool: name: an ``ansible_`` identifier. Returns: - ``True`` when the name is neither allowed explicitly nor by prefix or suffix. + ``True`` when the name is neither allowed explicitly nor by suffix. """ - return not ( - name in ALLOWED_NAMES - or name.startswith(ALLOWED_PREFIXES) - or name.endswith(ALLOWED_SUFFIXES) - ) + return not (name in ALLOWED_NAMES or name.endswith(ALLOWED_SUFFIXES)) -def scan_text(text: str, python: bool) -> list[str]: +def scan_text(text: str, python: bool, template: bool = False) -> list[str]: """Return one issue line per forbidden construct in *text*. Args: text: the file content. python: read *text* as Python (subscript and ``.get`` keys only) instead of YAML or Jinja. + template: read *text* as a Jinja template, whose list items are output, + not conditions. """ lines = text.splitlines() out: list[str] = [] @@ -159,6 +219,16 @@ def scan_text(text: str, python: bool) -> list[str]: out.append( f"line {idx}: [injected-fact] {line.strip()} -> {_FACT_FIX}" ) + if python or line.lstrip().startswith("#"): + continue + expressions = _JINJA_EXPR.findall(line) + condition = None if template else _CONDITION.match(line) + if condition: + expressions.append(condition.group("expr")) + if any(_BARE_FACT.search(expression) for expression in expressions): + out.append( + f"line {idx}: [injected-bare-fact] {line.strip()} -> {_BARE_FACT_FIX}" + ) return out @@ -181,7 +251,9 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): text = read_text(str(abs_path)) except (OSError, UnicodeDecodeError): continue - issues = scan_text(text, python=rel.endswith(".py")) + issues = scan_text( + text, python=rel.endswith(".py"), template=rel.endswith(".j2") + ) if issues: offenders[Path(abs_path)] = issues @@ -197,15 +269,25 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): def test_a_planted_top_level_fact_read_is_caught(self) -> None: planted = { "when: ansible_os_family == 'Debian'": False, + "when: ansible_os_family=='Debian'": False, "{{ ansible_eth0.ipv4.address }}": False, "{{ hostvars[h]['ansible_default_ipv4'] }}": False, 'distro = task_vars.get("ansible_distribution")': True, 'facts = task_vars["ansible_mounts"]': True, + "when: services['docker.service'] is defined": False, + "- packages['nfs-ganesha'] | first": False, + "- getent_group is defined": False, + "{{ getent_passwd.nixbld1[1] }}": False, } for line, python in planted.items(): with self.subTest(line=line): self.assertTrue(scan_text(line, python=python), line) + def test_every_option_var_of_the_lab_connection_is_allowed(self) -> None: + for name in ("ansible_docker_extra_env", "ansible_docker_working_dir"): + with self.subTest(name=name): + self.assertEqual(scan_text(f"{name}: x", python=False), [], name) + def test_magic_connection_and_namespaced_reads_pass(self) -> None: clean = { "when: ansible_facts['os_family'] == 'Debian'": False, @@ -215,6 +297,9 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): 'facts = task_vars.get("ansible_facts") or {}': True, 'host = hostvars[h].get("ansible_host")': True, "ansible_playbook = shutil.which('ansible-playbook')": True, + "when: ansible_facts.services['docker.service'] is defined": False, + "{{ lookup('config', application_id, 'services.sso.enabled') }}": False, + "- name: install language packages": False, } for line, python in clean.items(): with self.subTest(line=line): diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py b/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py index c328f9b9fa..f2366423ef 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py @@ -1,5 +1,6 @@ from __future__ import annotations +import importlib.metadata import io import json import subprocess @@ -365,6 +366,25 @@ class TestDeployAnsiblePlaybook(unittest.TestCase): self.assertIn(absent, stderr.getvalue()) self.assertNotIn("PyYAML", stderr.getvalue()) + def test_exits_naming_a_deploy_pin_the_interpreter_carries_at_another_version( + self, + ): + installed = importlib.metadata.version("PyYAML") + pinned = f"PyYAML=={installed}.post999" + repo_root, bindir = self._checkout( + [pinned, f"ruamel.yaml=={importlib.metadata.version('ruamel.yaml')}"], + with_playbook=True, + ) + stderr = io.StringIO() + with ( + unittest.mock.patch.object(runner.sys, "stderr", stderr), + self.assertRaises(SystemExit) as ctx, + ): + self._resolve(repo_root, bindir) + self.assertEqual(ctx.exception.code, 1) + self.assertIn(f"{pinned} (installed: {installed})", stderr.getvalue()) + self.assertNotIn("ruamel.yaml", stderr.getvalue()) + def test_exits_when_no_ansible_playbook_sits_beside_the_interpreter(self): repo_root, bindir = self._checkout(["PyYAML"], with_playbook=False) with ( diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index ea555f9af3..cfd2560f3f 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -235,6 +235,18 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ): action.run(task_vars={}) + def test_an_ansible_core_without_variable_layers_fails_with_its_version(self): + action = _make_action(_FakeTask(args={"clear": True})) + with ( + patch("plugins.action.applications_carrier.VariableLayer", None), + patch("plugins.action.applications_carrier.release.__version__", "2.20.9"), + self.assertRaisesRegex( + AnsibleActionFail, r"2\.21 or newer, found 2\.20\.9" + ), + ): + action.run(task_vars={}) + self.assertEqual(action.registered, {}) + def test_clear_drops_every_carrier_without_rendering(self): applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": True})) diff --git a/utils/cache/README.md b/utils/cache/README.md index eda1e48f4d..2049c28142 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -86,7 +86,7 @@ flowchart TD proc -.->|"TRIP-WIRE: read BEFORE the
host's own carrier, so an inherited
entry outranks it"| fact render -.->|"TRIP-WIRE: main process renders
task names for one host; forked
workers inherit that entry"| proc - key -.->|"TRIP-WIRE: carrier.py:121 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact + key -.->|"TRIP-WIRE: carrier.py:136 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact ``` The key covers `group_names`. `domains.py` derives from the applications view and shares that dependency; `users` reads `group_names` nowhere. diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index 7090bb85b4..41c168c7d5 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -116,9 +116,11 @@ def _carried( carrier = variables.get(fact) if fact not in variables and fact in (variables.get("ansible_facts") or {}): raise CarrierInvisibleError( - f"{fact} is parked in the fact cache but not visible as a variable; " - "park it with applications_carrier, which registers it outside the " - "fact cache, or every lookup renders the payload again" + f"{fact} is parked in the fact cache but not visible as a variable, " + "so every lookup would render the payload again; remove the task " + "that returns it as ansible_facts, or run " + "'applications_carrier: {clear: true}' before parking it again with " + "applications_carrier, which registers it outside the fact cache" ) if not isinstance(carrier, Mapping): return None