diff --git a/plugins/lookup/subnet_address_regex.py b/plugins/lookup/subnet_address_regex.py index c35818ff0b..6a21990d3b 100644 --- a/plugins/lookup/subnet_address_regex.py +++ b/plugins/lookup/subnet_address_regex.py @@ -16,7 +16,6 @@ to the wrong network. from __future__ import annotations -import contextlib from typing import Any from ansible.errors import AnsibleError @@ -24,13 +23,7 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.networks.address import subnet_address_regex - - -def _resolve_var(templar: Any, value: Any) -> Any: - if templar is not None and value is not None: - with contextlib.suppress(Exception): - return templar.template(value) - return value +from utils.templating.vars import resolve_var class LookupModule(LookupBase): @@ -46,7 +39,7 @@ class LookupModule(LookupBase): vars_ = variables or getattr(self._templar, "available_variables", {}) or {} templar = getattr(self, "_templar", None) - application_id = _resolve_var(templar, vars_.get("application_id")) + application_id = resolve_var(templar, vars_.get("application_id")) if not application_id: raise AnsibleError( "subnet_address_regex lookup: application_id is required in variables" diff --git a/plugins/lookup/subnet_gateway.py b/plugins/lookup/subnet_gateway.py index f723dbff62..95e4d31f61 100644 --- a/plugins/lookup/subnet_gateway.py +++ b/plugins/lookup/subnet_gateway.py @@ -13,7 +13,6 @@ fails at render time instead of reaching Docker as a malformed address. from __future__ import annotations -import contextlib from typing import Any from ansible.errors import AnsibleError @@ -21,13 +20,7 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from utils.networks.address import subnet_gateway - - -def _resolve_var(templar: Any, value: Any) -> Any: - if templar is not None and value is not None: - with contextlib.suppress(Exception): - return templar.template(value) - return value +from utils.templating.vars import resolve_var class LookupModule(LookupBase): @@ -43,7 +36,7 @@ class LookupModule(LookupBase): vars_ = variables or getattr(self._templar, "available_variables", {}) or {} templar = getattr(self, "_templar", None) - application_id = _resolve_var(templar, vars_.get("application_id")) + application_id = resolve_var(templar, vars_.get("application_id")) if not application_id: raise AnsibleError( "subnet_gateway lookup: application_id is required in variables" diff --git a/plugins/lookup/webserver_resource.py b/plugins/lookup/webserver_resource.py index 2d49a7c3f3..76d8309077 100644 --- a/plugins/lookup/webserver_resource.py +++ b/plugins/lookup/webserver_resource.py @@ -19,6 +19,7 @@ from ansible.plugins.lookup import LookupBase from plugins.filter.resource_filter import resource_filter from plugins.lookup.applications import LookupModule as ApplicationsLookup from plugins.lookup.resource import LookupModule as ResourceLookup +from utils.templating.vars import resolve_var PROXY_ROLE = "svc-prx-openresty" @@ -26,24 +27,6 @@ _CAST = {"cpus": float, "pids_limit": int} class LookupModule(LookupBase): - def _rendered(self, value: Any) -> str: - """Return *value* as text, resolving it when it is still a template. - - A variable read out of the play's variables is raw, so a role whose - ``application_id`` is itself a template (``sys-stk-full`` sets it from - ``sys_stk_full_application_id``) hands back the unrendered string. An - expression that names the same variable is templated before the lookup - ever sees it, which is why the inline form this replaced never hit it. - - Args: - value: the variable as the play holds it. - """ - text = str(value or "") - templar = getattr(self, "_templar", None) - if templar is None or "{{" not in text: - return text - return str(templar.template(text)) - def run( self, terms: list[Any], @@ -64,8 +47,9 @@ class LookupModule(LookupBase): ) vars_ = variables or getattr(self._templar, "available_variables", {}) or {} - application_id = self._rendered(vars_.get("application_id")) - service_name = self._rendered(vars_.get("service_name")) + templar = getattr(self, "_templar", None) + application_id = str(resolve_var(templar, vars_.get("application_id")) or "") + service_name = str(resolve_var(templar, vars_.get("service_name")) or "") applications = ApplicationsLookup().run([], variables=vars_, **kwargs)[0] resource = ResourceLookup() diff --git a/tests/unit/python/utils/templating/test_vars.py b/tests/unit/python/utils/templating/test_vars.py new file mode 100644 index 0000000000..53b26ba079 --- /dev/null +++ b/tests/unit/python/utils/templating/test_vars.py @@ -0,0 +1,44 @@ +import unittest + +from utils.templating.vars import resolve_var + + +class _Templar: + def __init__(self, resolved=None, raises=False): + self._resolved = resolved or {} + self._raises = raises + + def template(self, value): + if self._raises: + raise RuntimeError("undefined variable") + return self._resolved.get(value, value) + + +class TestResolveVar(unittest.TestCase): + def test_a_template_is_resolved(self): + templar = _Templar({"{{ stack_app }}": "web-app-docs"}) + self.assertEqual(resolve_var(templar, "{{ stack_app }}"), "web-app-docs") + + def test_a_plain_value_survives(self): + self.assertEqual(resolve_var(_Templar(), "web-app-docs"), "web-app-docs") + + def test_without_a_templar_the_value_is_returned_as_is(self): + self.assertEqual(resolve_var(None, "{{ stack_app }}"), "{{ stack_app }}") + + def test_none_is_returned_as_is(self): + self.assertIsNone(resolve_var(_Templar(), None)) + + def test_a_raising_templar_leaves_the_value_alone(self): + """A lookup asks before the variable is necessarily defined, so a + failure to render must not take the play down here.""" + self.assertEqual( + resolve_var(_Templar(raises=True), "{{ stack_app }}"), "{{ stack_app }}" + ) + + def test_a_non_string_is_passed_through_the_templar(self): + templar = _Templar() + self.assertEqual(resolve_var(templar, {"a": 1}), {"a": 1}) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/networks/lookup_context.py b/utils/networks/lookup_context.py index 910eaa35e4..af766f1d1a 100644 --- a/utils/networks/lookup_context.py +++ b/utils/networks/lookup_context.py @@ -12,7 +12,6 @@ Args of :func:`build_context` are documented on the function. from __future__ import annotations -import contextlib from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -21,25 +20,12 @@ from ansible.plugins.loader import lookup_loader from utils.roles.applications.services.registry import ( build_service_registry_from_applications, ) +from utils.templating.vars import resolve_var as resolve_var if TYPE_CHECKING: from collections.abc import Callable -def resolve_var(templar: Any, value: Any) -> Any: - """Template ``value`` when a templar is available, else pass it through. - - Args: - templar: the plugin's templar, or None. - value: raw variable value. - """ - if templar is None: - return value - with contextlib.suppress(Exception): - return templar.template(value) - return value - - @dataclass(frozen=True) class NetworkLookupContext: """What a network lookup needs to call the renderers.""" diff --git a/utils/templating/vars.py b/utils/templating/vars.py new file mode 100644 index 0000000000..d355238060 --- /dev/null +++ b/utils/templating/vars.py @@ -0,0 +1,27 @@ +"""Resolve a play variable that may still be a template. + +A value taken out of the play's variables is raw. A role whose +``application_id`` is itself a template, as ``sys-stk-full`` sets it from +``sys_stk_full_application_id``, therefore hands back the unrendered string, +while the same variable named inside an expression arrives resolved. Every +lookup that reads such a variable resolves it through here. +""" + +from __future__ import annotations + +import contextlib +from typing import Any + + +def resolve_var(templar: Any, value: Any) -> Any: + """Template ``value`` when a templar is available, else pass it through. + + Args: + templar: the plugin's templar, or None. + value: the variable as the play holds it. + """ + if templar is None or value is None: + return value + with contextlib.suppress(Exception): + return templar.template(value) + return value