@ansible-flow/assets 0.0.0-stage → 0.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,170 @@
1
+ """Inventory lens (M8): host patterns counted against the inventory, the variables that decide
2
+ access per pattern with their origin, and the names of vaulted variables.
3
+
4
+ Vaulted values are never decrypted: ansible-core 2.19+ keeps them as ``EncryptedString`` until
5
+ something reads them, and this module only checks their type. Origins come from the data tags
6
+ ansible-core 2.19+ attaches to strings and numbers (booleans and nulls carry none).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from typing import Any
13
+
14
+ ACCESS_VARS = ("ansible_user", "ansible_become", "ansible_become_user", "ansible_connection")
15
+ HOST_LIMIT = 5000
16
+ SAMPLE = 3
17
+ ORIGINS = 5
18
+ STATIC_SUFFIXES = (".ini", ".cfg", ".yml", ".yaml", ".json", ".toml")
19
+
20
+
21
+ def _encrypted_types() -> tuple[type, ...]:
22
+ found: list[type] = []
23
+ try:
24
+ from ansible.parsing.vault import EncryptedString
25
+
26
+ found.append(EncryptedString)
27
+ except ImportError:
28
+ pass
29
+ try:
30
+ from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
31
+
32
+ found.append(AnsibleVaultEncryptedUnicode)
33
+ except ImportError:
34
+ pass
35
+ return tuple(found)
36
+
37
+
38
+ def _origin_of(root: str):
39
+ try:
40
+ from ansible._internal._datatag._tags import Origin
41
+ except ImportError:
42
+ return lambda _value: None
43
+
44
+ def origin(value: Any) -> str | None:
45
+ tag = Origin.get_tag(value)
46
+ if tag is None or not tag.path:
47
+ return None
48
+ path = tag.path
49
+ if os.path.isabs(path) and path.startswith(root + os.sep):
50
+ path = os.path.relpath(path, root)
51
+ return f"{path}:{tag.line_num}" if tag.line_num else path
52
+
53
+ return origin
54
+
55
+
56
+ def _text(value: Any) -> str:
57
+ if isinstance(value, bool):
58
+ return "true" if value else "false"
59
+ return str(value)
60
+
61
+
62
+ def _dynamic(root: str, sources: list[str]) -> list[str]:
63
+ """Sources that run code to produce hosts: inventory plugin configs and scripts."""
64
+ out: list[str] = []
65
+ for source in sources:
66
+ path = source if os.path.isabs(source) else os.path.join(root, source)
67
+ files = (
68
+ [os.path.join(path, f) for f in sorted(os.listdir(path))]
69
+ if os.path.isdir(path)
70
+ else [path]
71
+ )
72
+ for f in files:
73
+ if not os.path.isfile(f):
74
+ continue
75
+ name = os.path.relpath(f, root) if f.startswith(root + os.sep) else f
76
+ if f.endswith((".yml", ".yaml")):
77
+ try:
78
+ with open(f, encoding="utf-8", errors="ignore") as fh:
79
+ head = fh.read(4096)
80
+ except OSError:
81
+ continue
82
+ if any(line.startswith("plugin:") for line in head.splitlines()):
83
+ out.append(name)
84
+ elif not f.endswith(STATIC_SUFFIXES) and os.access(f, os.X_OK):
85
+ out.append(name)
86
+ return out
87
+
88
+
89
+ def inventory_lens(
90
+ root: str,
91
+ inventory: str | None = None,
92
+ targets: str = "",
93
+ patterns: list[str] | None = None,
94
+ ) -> dict[str, Any]:
95
+ from ansible import constants as C
96
+ from ansible.inventory.manager import InventoryManager
97
+ from ansible.parsing.dataloader import DataLoader
98
+ from ansible.vars.manager import VariableManager
99
+
100
+ from afd_probe.methods import PROD
101
+
102
+ loader = DataLoader()
103
+ sources = [inventory] if inventory else C.DEFAULT_HOST_LIST
104
+ source_list = [str(s) for s in (sources if isinstance(sources, list) else [sources])]
105
+ inv = InventoryManager(loader=loader, sources=source_list)
106
+ variables = VariableManager(loader=loader, inventory=inv)
107
+ encrypted = _encrypted_types()
108
+ origin = _origin_of(os.path.abspath(root))
109
+
110
+ target_names = {h.name for h in inv.get_hosts(targets)} if targets.strip() else set()
111
+ resolved: dict[str, list[Any]] = {}
112
+ out_patterns: dict[str, dict[str, Any]] = {}
113
+ scope: dict[str, Any] = {}
114
+ for pattern in patterns or []:
115
+ hosts = inv.get_hosts(pattern)
116
+ resolved[pattern] = hosts
117
+ outside = [h.name for h in hosts if h.name not in target_names]
118
+ out_patterns[pattern] = {
119
+ "count": len(hosts),
120
+ "outside": len(outside),
121
+ "sample": outside[:SAMPLE],
122
+ }
123
+ for h in hosts:
124
+ scope.setdefault(h.name, h)
125
+
126
+ groups: dict[str, int] = {}
127
+ for h in scope.values():
128
+ for g in h.get_groups():
129
+ if g.name not in ("all", "ungrouped"):
130
+ groups[g.name] = groups.get(g.name, 0) + 1
131
+
132
+ # Per host: the access variables (value, origin, vaulted), and every vaulted variable's name.
133
+ per_host: dict[str, dict[str, tuple[str | None, str | None, bool]]] = {}
134
+ vaulted: dict[str, str] = {}
135
+ for name, host in list(scope.items())[:HOST_LIMIT]:
136
+ hv = variables.get_vars(host=host, include_hostvars=False, stage="task")
137
+ picked: dict[str, tuple[str | None, str | None, bool]] = {}
138
+ for key, value in hv.items():
139
+ secret = bool(encrypted) and isinstance(value, encrypted)
140
+ if secret and key not in vaulted:
141
+ vaulted[key] = origin(value) or "inventory"
142
+ if key in ACCESS_VARS:
143
+ picked[key] = (None if secret else _text(value), origin(value), secret)
144
+ per_host[name] = picked
145
+
146
+ access: dict[str, dict[str, Any]] = {}
147
+ for pattern, hosts in resolved.items():
148
+ agg: dict[str, Any] = {}
149
+ for h in hosts:
150
+ for key, (value, where, secret) in per_host.get(h.name, {}).items():
151
+ entry = agg.setdefault(key, {"values": {}, "origins": []})
152
+ if secret:
153
+ entry["vault"] = True
154
+ continue
155
+ entry["values"][value] = entry["values"].get(value, 0) + 1
156
+ if where and where not in entry["origins"] and len(entry["origins"]) < ORIGINS:
157
+ entry["origins"].append(where)
158
+ access[pattern] = agg
159
+
160
+ return {
161
+ "sources": source_list,
162
+ "dynamic": _dynamic(os.path.abspath(root), source_list),
163
+ "total": len(inv.get_hosts("all")),
164
+ "targets": targets,
165
+ "patterns": out_patterns,
166
+ "scope": {"count": len(scope), "groups": dict(sorted(groups.items()))},
167
+ "prod_groups": sorted(g for g in groups if PROD.search(g)),
168
+ "access": access,
169
+ "vaulted": dict(sorted(vaulted.items())),
170
+ }
@@ -0,0 +1,220 @@
1
+ """Probe methods. Each takes the repository root plus keyword params and returns JSON data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from typing import Any
12
+
13
+ PROD = re.compile(r"(^|[_.\-])(prod|production|prd|live)([_.\-0-9]|$)", re.IGNORECASE)
14
+ ORIGIN = re.compile(r"Origin: (?P<path>.+?):(?P<line>\d+)(?::(?P<col>\d+))?\s*$")
15
+ VAULT_MARKERS = ("$ANSIBLE_VAULT;", "!vault")
16
+ OUTPUT_LIMIT = 6000
17
+ SYNTAX_TIMEOUT = 120
18
+
19
+
20
+ def ping(root: str) -> dict[str, Any]:
21
+ return {"ok": True}
22
+
23
+
24
+ def run_config(root: str) -> dict[str, Any]:
25
+ """What a run keeps of the repository's config (AFD-141).
26
+
27
+ A run enables our event callback through ANSIBLE_CALLBACKS_ENABLED and
28
+ ANSIBLE_CALLBACK_PLUGINS, which replace ansible.cfg's values. So the run adds ours to the
29
+ callbacks and plugin folders this config gives, and audit callbacks an organisation
30
+ requires keep running.
31
+ """
32
+ from ansible import constants as C
33
+
34
+ return {
35
+ "callbacks_enabled": [str(c) for c in (C.CALLBACKS_ENABLED or [])],
36
+ "callback_plugins": [str(p) for p in (C.DEFAULT_CALLBACK_PLUGIN_PATH or [])],
37
+ }
38
+
39
+
40
+ def _playbook_command() -> list[str]:
41
+ exe = shutil.which("ansible-playbook")
42
+ return [exe] if exe else [sys.executable, "-m", "ansible.cli.playbook"]
43
+
44
+
45
+ def syntax_check(
46
+ root: str,
47
+ playbook: str,
48
+ inventory: str | None = None,
49
+ extra_vars: dict[str, Any] | None = None,
50
+ ) -> dict[str, Any]:
51
+ """`ansible-playbook --syntax-check` inside this environment (modules must exist here)."""
52
+ cmd = [*_playbook_command(), "--syntax-check", playbook]
53
+ if inventory:
54
+ cmd += ["-i", inventory]
55
+ if extra_vars:
56
+ cmd += ["-e", json.dumps(extra_vars)]
57
+ proc = subprocess.run(
58
+ cmd, cwd=root, capture_output=True, text=True, timeout=SYNTAX_TIMEOUT, check=False
59
+ )
60
+ output = (proc.stdout + proc.stderr).strip()
61
+ errors: list[dict[str, Any]] = []
62
+ message: list[str] = []
63
+ for line in output.splitlines():
64
+ if line.startswith(("[ERROR]", "ERROR!")):
65
+ message = [
66
+ line.split(":", 1)[-1].strip() if line.startswith("[ERROR]") else line[6:].strip()
67
+ ]
68
+ continue
69
+ match = ORIGIN.search(line)
70
+ if match and message:
71
+ errors.append(
72
+ {
73
+ "message": " ".join(message),
74
+ "path": match["path"],
75
+ "line": int(match["line"]),
76
+ "column": int(match["col"] or 1),
77
+ }
78
+ )
79
+ message = []
80
+ if proc.returncode != 0 and not errors:
81
+ errors.append({"message": output.splitlines()[-1] if output else "syntax check failed"})
82
+ return {
83
+ "ok": proc.returncode == 0,
84
+ "rc": proc.returncode,
85
+ "errors": errors,
86
+ "output": output[-OUTPUT_LIMIT:],
87
+ }
88
+
89
+
90
+ def inventory(
91
+ root: str,
92
+ inventory: str | None = None,
93
+ targets: list[str] | None = None,
94
+ ) -> dict[str, Any]:
95
+ """Hosts the flow's targets resolve to, their groups, and what looks like production."""
96
+ from ansible import constants as C
97
+ from ansible.inventory.manager import InventoryManager
98
+ from ansible.parsing.dataloader import DataLoader
99
+
100
+ sources = [inventory] if inventory else C.DEFAULT_HOST_LIST
101
+ inv = InventoryManager(loader=DataLoader(), sources=sources)
102
+ names = [str(t) for t in (targets or []) if str(t).strip()]
103
+ hosts = inv.get_hosts(",".join(names)) if names else []
104
+ unknown = [n for n in names if not inv.get_hosts(n)]
105
+ groups: dict[str, int] = {}
106
+ for host in hosts:
107
+ for group in host.get_groups():
108
+ if group.name not in ("all", "ungrouped"):
109
+ groups[group.name] = groups.get(group.name, 0) + 1
110
+ source_list = sources if isinstance(sources, list) else [sources]
111
+ return {
112
+ "sources": [str(s) for s in source_list],
113
+ "count": len(hosts),
114
+ "hosts": [h.name for h in hosts[:50]],
115
+ "unknown": unknown,
116
+ "groups": dict(sorted(groups.items())),
117
+ "prod_groups": sorted(g for g in groups if PROD.search(g)),
118
+ "prod_hosts": sorted(h.name for h in hosts if PROD.search(h.name))[:50],
119
+ "vault": _vault_present(root, source_list),
120
+ }
121
+
122
+
123
+ TREE_HOSTS = 500
124
+
125
+
126
+ def inventory_tree(root: str, inventory: str | None = None) -> dict[str, Any]:
127
+ """The inventory's groups, each with its own hosts and child groups (AFD-83: Inventory view)."""
128
+ from ansible import constants as C
129
+ from ansible.inventory.manager import InventoryManager
130
+ from ansible.parsing.dataloader import DataLoader
131
+
132
+ sources = [inventory] if inventory else C.DEFAULT_HOST_LIST
133
+ inv = InventoryManager(loader=DataLoader(), sources=sources)
134
+ groups = [
135
+ {
136
+ "name": name,
137
+ "hosts": sorted(h.name for h in group.hosts)[:TREE_HOSTS],
138
+ "children": sorted(c.name for c in group.child_groups),
139
+ "count": len(group.get_hosts()),
140
+ }
141
+ for name, group in sorted(inv.groups.items())
142
+ ]
143
+ source_list = sources if isinstance(sources, list) else [sources]
144
+ return {
145
+ "sources": [str(s) for s in source_list],
146
+ "total": len(inv.get_hosts()),
147
+ "groups": groups,
148
+ }
149
+
150
+
151
+ def _vault_present(root: str, sources: list[Any]) -> bool:
152
+ """Vault-encrypted files or inline !vault values near the inventory or in the repo vars."""
153
+ places = [os.path.join(root, "group_vars"), os.path.join(root, "host_vars")]
154
+ for source in sources:
155
+ path = os.path.join(root, str(source)) if not os.path.isabs(str(source)) else str(source)
156
+ places.append(path if os.path.isdir(path) else os.path.dirname(path))
157
+ seen: set[str] = set()
158
+ for place in places:
159
+ if not os.path.isdir(place) or place in seen:
160
+ continue
161
+ seen.add(place)
162
+ for folder, _dirs, files in os.walk(place):
163
+ for name in files:
164
+ try:
165
+ with open(os.path.join(folder, name), encoding="utf-8", errors="ignore") as fh:
166
+ head = fh.read(65536)
167
+ except OSError:
168
+ continue
169
+ if any(marker in head for marker in VAULT_MARKERS):
170
+ return True
171
+ return False
172
+
173
+
174
+ def catalog(root: str, cache: str, jobs: int = 8, only: list[str] | None = None) -> dict[str, Any]:
175
+ """Dumps the environment's plugin docs into `cache` (M5); see catalog.py."""
176
+ from afd_probe import catalog as cat
177
+
178
+ return cat.catalog(root, cache, jobs, only)
179
+
180
+
181
+ def roles(root: str) -> list[dict[str, Any]]:
182
+ """The repository's roles with their argument specs (M5)."""
183
+ from afd_probe import catalog as cat
184
+
185
+ return cat.roles(root)
186
+
187
+
188
+ def compile( # noqa: A001 - the protocol method name
189
+ root: str,
190
+ playbooks: list[str] | None = None,
191
+ roles: list[dict[str, Any]] | None = None,
192
+ ) -> dict[str, Any]:
193
+ """Plays and tasks Ansible compiles from playbooks and bound roles (M6); see code.py."""
194
+ from afd_probe import code
195
+
196
+ return code.compile_code(root, playbooks, roles)
197
+
198
+
199
+ def inventory_lens(
200
+ root: str,
201
+ inventory: str | None = None,
202
+ targets: str = "",
203
+ patterns: list[str] | None = None,
204
+ ) -> dict[str, Any]:
205
+ from afd_probe.lens import inventory_lens as lens
206
+
207
+ return lens(root, inventory=inventory, targets=targets, patterns=patterns)
208
+
209
+
210
+ HANDLERS = {
211
+ "ping": ping,
212
+ "run_config": run_config,
213
+ "syntax_check": syntax_check,
214
+ "inventory": inventory,
215
+ "inventory_tree": inventory_tree,
216
+ "inventory_lens": inventory_lens,
217
+ "catalog": catalog,
218
+ "roles": roles,
219
+ "compile": compile,
220
+ }
@@ -0,0 +1,86 @@
1
+ """JSON-lines session: one request per stdin line, one response per stdout line.
2
+
3
+ Request: {"id": 1, "method": "inventory", "params": {...}}
4
+ Response: {"id": 1, "result": {...}} or {"id": 1, "error": {"type": "...", "message": "..."}}
5
+ The first line is {"kind": "ready", ...}. A failing request never ends the session.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import platform
13
+ import sys
14
+ import traceback
15
+ from collections.abc import Callable
16
+ from typing import Any, TextIO
17
+
18
+
19
+ def _prepare_environment(root: str) -> None:
20
+ # Docker Desktop mounts are world-writable, so Ansible ignores ./ansible.cfg there; naming it
21
+ # explicitly must happen before ansible is imported (lessons 07 §1).
22
+ cfg = os.path.join(root, "ansible.cfg")
23
+ if "ANSIBLE_CONFIG" not in os.environ and os.path.isfile(cfg):
24
+ os.environ["ANSIBLE_CONFIG"] = cfg
25
+ os.environ.setdefault("ANSIBLE_HOST_PATTERN_MISMATCH", "ignore")
26
+ os.environ.setdefault("ANSIBLE_DEPRECATION_WARNINGS", "False")
27
+ os.environ.setdefault("ANSIBLE_LOCALHOST_WARNING", "False")
28
+ os.environ.setdefault("ANSIBLE_NOCOLOR", "True")
29
+
30
+
31
+ def serve(root: str, stdin: TextIO | None = None, stdout: TextIO | None = None) -> int:
32
+ root = os.path.abspath(root)
33
+ _prepare_environment(root)
34
+ # The protocol owns stdout: Ansible's Display and plugins print, so they get stderr.
35
+ out = stdout or sys.stdout
36
+ sys.stdout = sys.stderr
37
+ os.chdir(root)
38
+
39
+ from afd_probe import __version__, methods
40
+
41
+ try:
42
+ from ansible.release import __version__ as core_version
43
+ except Exception as exc: # no ansible-core here: say so and stop
44
+ _write(out, {"kind": "error", "message": f"ansible-core is not importable: {exc}"})
45
+ return 1
46
+ try:
47
+ from ansible.plugins.loader import init_plugin_loader
48
+
49
+ init_plugin_loader()
50
+ except ImportError: # older cores initialise lazily
51
+ pass
52
+
53
+ _write(
54
+ out,
55
+ {
56
+ "kind": "ready",
57
+ "probe": __version__,
58
+ "ansible_core": core_version,
59
+ "python": platform.python_version(),
60
+ "root": root,
61
+ },
62
+ )
63
+ handlers: dict[str, Callable[..., Any]] = methods.HANDLERS
64
+ for line in stdin or sys.stdin:
65
+ line = line.strip()
66
+ if not line:
67
+ continue
68
+ req_id: Any = None
69
+ try:
70
+ request = json.loads(line)
71
+ req_id = request.get("id")
72
+ method = request.get("method")
73
+ handler = handlers.get(method)
74
+ if handler is None:
75
+ raise LookupError(f"unknown method: {method}")
76
+ result = handler(root, **(request.get("params") or {}))
77
+ _write(out, {"id": req_id, "result": result})
78
+ except Exception as exc: # report and keep serving
79
+ traceback.print_exc(file=sys.stderr)
80
+ _write(out, {"id": req_id, "error": {"type": type(exc).__name__, "message": str(exc)}})
81
+ return 0
82
+
83
+
84
+ def _write(out: TextIO, message: dict[str, Any]) -> None:
85
+ out.write(json.dumps(message, default=str) + "\n")
86
+ out.flush()
@@ -0,0 +1,198 @@
1
+ # Ansible Flow Designer run events: one JSON object per line in the file named by AFD_EVENTS.
2
+ # Stdlib only; enabled with ANSIBLE_CALLBACKS_ENABLED=afd_events next to the normal stdout callback.
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+
9
+ from ansible.plugins.callback import CallbackBase
10
+
11
+ DOCUMENTATION = """
12
+ name: afd_events
13
+ type: notification
14
+ short_description: Ansible Flow Designer run events (JSON lines)
15
+ description:
16
+ - Writes play starts, task results with routing groups, and final stats to the file named
17
+ by the AFD_EVENTS environment variable, so the designer can map a run back to flow nodes.
18
+ - Task results also carry changed, rc and the task's output (stdout, stderr, msg; cut), read
19
+ while the run goes and shown per host (AFD-81). A no_log result says only censored.
20
+ requirements: []
21
+ """
22
+
23
+ MSG_LIMIT = 500
24
+ OUT_LIMIT = 2000
25
+ # The generated routing tasks: their results are the routes, not output worth showing.
26
+ ROUTING = {
27
+ "add_host",
28
+ "group_by",
29
+ "meta",
30
+ "ansible.builtin.add_host",
31
+ "ansible.builtin.group_by",
32
+ "ansible.builtin.meta",
33
+ }
34
+
35
+
36
+ REDACTED = "********"
37
+
38
+
39
+ def _leaves(value: object, out: set[str]) -> None:
40
+ """Every string and number inside a secret input (AFD-139): a list or dict secret is matched
41
+ by its parts, since tasks print those, not the whole JSON."""
42
+ if isinstance(value, bool) or value is None:
43
+ return
44
+ if isinstance(value, (str, int, float)):
45
+ text = str(value)
46
+ if text:
47
+ out.add(text)
48
+ elif isinstance(value, dict):
49
+ out.add(json.dumps(value, separators=(",", ":")))
50
+ for v in value.values():
51
+ _leaves(v, out)
52
+ elif isinstance(value, list):
53
+ out.add(json.dumps(value, separators=(",", ":")))
54
+ for v in value:
55
+ _leaves(v, out)
56
+
57
+
58
+ def _secrets() -> list[str]:
59
+ """The run's secret values, from the files the run's shell names (AFD-139): the secret
60
+ inputs (AFD_SECRETS_FILE, JSON) and the vault password (AFD_VAULT_FILE). Longest first, so a
61
+ secret that contains another is replaced whole."""
62
+ found: set[str] = set()
63
+ path = os.environ.get("AFD_SECRETS_FILE")
64
+ if path:
65
+ try:
66
+ with open(path, encoding="utf-8") as f:
67
+ data = json.load(f)
68
+ for v in data.values() if isinstance(data, dict) else []:
69
+ _leaves(v, found)
70
+ except (OSError, ValueError):
71
+ pass
72
+ path = os.environ.get("AFD_VAULT_FILE")
73
+ if path:
74
+ try:
75
+ with open(path, encoding="utf-8") as f:
76
+ password = f.read().rstrip("\r\n")
77
+ if password:
78
+ found.add(password)
79
+ except OSError:
80
+ pass
81
+ return sorted(found, key=len, reverse=True)
82
+
83
+
84
+ def _scrub(value: object, secrets: list[str]) -> object:
85
+ if isinstance(value, str):
86
+ for s in secrets:
87
+ if s in value:
88
+ value = value.replace(s, REDACTED)
89
+ return value
90
+ if isinstance(value, list):
91
+ return [_scrub(v, secrets) for v in value]
92
+ if isinstance(value, dict):
93
+ return {k: _scrub(v, secrets) for k, v in value.items()}
94
+ return value
95
+
96
+
97
+ def _text(value: object) -> str | None:
98
+ """Output as text, cut at OUT_LIMIT; None when empty."""
99
+ if value is None or value == "" or value == []:
100
+ return None
101
+ if isinstance(value, list):
102
+ value = "\n".join(str(v) for v in value)
103
+ elif not isinstance(value, str):
104
+ value = json.dumps(value, default=str)
105
+ return value[:OUT_LIMIT]
106
+
107
+
108
+ class CallbackModule(CallbackBase):
109
+ CALLBACK_VERSION = 2.0
110
+ CALLBACK_TYPE = "notification"
111
+ CALLBACK_NAME = "afd_events"
112
+ CALLBACK_NEEDS_ENABLED = True
113
+
114
+ def __init__(self) -> None:
115
+ super().__init__()
116
+ path = os.environ.get("AFD_EVENTS")
117
+ self._out = open(path, "a", encoding="utf-8") if path else None # noqa: SIM115
118
+ self._node: str | None = None
119
+ # AFD-139: secret values never reach the file, also when the run stops before the
120
+ # extension's own redaction pass at its end.
121
+ self._secrets = _secrets()
122
+
123
+ def _emit(self, **event: object) -> None:
124
+ if self._out is None:
125
+ return
126
+ event["ts"] = round(time.time(), 3)
127
+ if self._secrets:
128
+ event = _scrub(json.loads(json.dumps(event, default=str)), self._secrets)
129
+ self._out.write(json.dumps(event, default=str) + "\n")
130
+ self._out.flush()
131
+
132
+ def v2_playbook_on_start(self, playbook) -> None:
133
+ self._emit(event="start", playbook=os.path.basename(playbook._file_name))
134
+
135
+ def v2_playbook_on_play_start(self, play) -> None:
136
+ node = (play.vars or {}).get("flow_node_id")
137
+ self._node = str(node) if node else None
138
+ self._emit(event="play", name=play.get_name(), node=self._node)
139
+
140
+ def _result(self, status: str, result, **extra: object) -> None:
141
+ data = result._result
142
+ event: dict[str, object] = {
143
+ "event": "result",
144
+ "status": status,
145
+ "host": result._host.get_name(),
146
+ "task": result._task.get_name(),
147
+ "action": result._task.action,
148
+ "node": self._node,
149
+ }
150
+ if data.get("add_group"):
151
+ event["group"] = data["add_group"]
152
+ added = data.get("add_host")
153
+ if isinstance(added, dict):
154
+ event["added"] = {"host": added.get("host_name"), "groups": added.get("groups")}
155
+ if "censored" in data or data.get("_ansible_no_log"):
156
+ event["censored"] = True
157
+ event.update(extra)
158
+ self._emit(**event)
159
+ return
160
+ message = data.get("msg") or data.get("reason")
161
+ if status in ("failed", "unreachable") and message:
162
+ event["msg"] = str(message)[:MSG_LIMIT]
163
+ routing = "group" in event or "added" in event or result._task.action in ROUTING
164
+ if not routing:
165
+ if "changed" in data:
166
+ event["changed"] = bool(data["changed"])
167
+ if isinstance(data.get("rc"), int):
168
+ event["rc"] = data["rc"]
169
+ out = {k: t for k in ("stdout", "stderr", "msg") if (t := _text(data.get(k)))}
170
+ if out:
171
+ event["out"] = out
172
+ event.update(extra)
173
+ self._emit(**event)
174
+
175
+ def v2_runner_on_ok(self, result) -> None:
176
+ self._result("ok", result)
177
+
178
+ def v2_runner_on_failed(self, result, ignore_errors: bool = False) -> None:
179
+ self._result("failed", result, ignored=ignore_errors)
180
+
181
+ def v2_runner_on_unreachable(self, result) -> None:
182
+ self._result("unreachable", result)
183
+
184
+ def v2_runner_on_skipped(self, result) -> None:
185
+ self._result("skipped", result)
186
+
187
+ def v2_runner_item_on_ok(self, result) -> None:
188
+ self._result("ok", result, item=True)
189
+
190
+ def v2_playbook_on_stats(self, stats) -> None:
191
+ hosts = sorted(stats.processed.keys())
192
+ # set_stats data (per_host: false): what an AWX workflow passes to the next segment.
193
+ custom = (getattr(stats, "custom", None) or {}).get("_run")
194
+ extra = {"custom": custom} if custom else {}
195
+ self._emit(event="stats", hosts={h: stats.summarize(h) for h in hosts}, **extra)
196
+ if self._out is not None:
197
+ self._out.close()
198
+ self._out = None