@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.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/contract/README.md +40 -0
- package/contract/repo/flows/hello.flow.yaml +110 -0
- package/contract/repo/flows/next.flow.yaml +110 -0
- package/contract/repo/inventory/hosts.yaml +3 -0
- package/contract/server-api.json +236 -0
- package/index.d.ts +6 -0
- package/index.js +5 -0
- package/package.json +33 -4
- package/probe/afd_probe/__init__.py +6 -0
- package/probe/afd_probe/__main__.py +23 -0
- package/probe/afd_probe/catalog.py +409 -0
- package/probe/afd_probe/code.py +166 -0
- package/probe/afd_probe/lens.py +170 -0
- package/probe/afd_probe/methods.py +220 -0
- package/probe/afd_probe/serve.py +86 -0
- package/probe/callback_plugins/afd_events.py +198 -0
- package/schema/flow.schema.json +1029 -0
- package/schema/scenarios.schema.json +111 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Module catalog dump (M5, ADR-0011): what the environment can run, normalized for the host index.
|
|
2
|
+
|
|
3
|
+
`ansible-doc --metadata-dump` is internal, so everything it returns goes through `_plugin`. One
|
|
4
|
+
process per collection runs in parallel (07 §2: 37 s instead of 257 s for 93 collections), and a
|
|
5
|
+
collection is dumped again only when its version or ansible-core's minor version changed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
DUMP_TIMEOUT = 600
|
|
22
|
+
KEPT_TYPES = ("module", "filter", "test", "lookup", "keyword")
|
|
23
|
+
FORMAT = 1
|
|
24
|
+
|
|
25
|
+
# Ansible doc markup → text; code-like parts keep backticks so the UI can show them as code.
|
|
26
|
+
_MARKUP = [
|
|
27
|
+
(re.compile(r"L\(([^)]*?),\s*([^)]*?)\)"), r"\1 (\2)"),
|
|
28
|
+
(re.compile(r"[CMOVRPE]V?\(([^)]*)\)"), r"`\1`"),
|
|
29
|
+
(re.compile(r"[IBU]\(([^)]*)\)"), r"\1"),
|
|
30
|
+
(re.compile(r":(?:ref|class|meth|func|attr|term):`([^`<]*?)(?:\s*<[^>]*>)?`"), r"\1"),
|
|
31
|
+
(re.compile(r"HORIZONTALLINE"), ""),
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def text(value: Any) -> str:
|
|
36
|
+
"""Ansible doc strings (or lists of them) as one plain paragraph text."""
|
|
37
|
+
if value is None:
|
|
38
|
+
return ""
|
|
39
|
+
parts = value if isinstance(value, list) else [value]
|
|
40
|
+
out = []
|
|
41
|
+
for part in parts:
|
|
42
|
+
s = str(part)
|
|
43
|
+
for pattern, repl in _MARKUP:
|
|
44
|
+
s = pattern.sub(repl, s)
|
|
45
|
+
out.append(s.strip())
|
|
46
|
+
return "\n".join(p for p in out if p)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _option(opt: dict) -> dict:
|
|
50
|
+
out: dict[str, Any] = {
|
|
51
|
+
"type": opt.get("type") or "str",
|
|
52
|
+
"description": text(opt.get("description")),
|
|
53
|
+
}
|
|
54
|
+
for key in ("required", "default", "choices", "elements", "aliases", "no_log", "version_added"):
|
|
55
|
+
if opt.get(key) not in (None, False, [], ""):
|
|
56
|
+
out[key] = opt[key]
|
|
57
|
+
subs = opt.get("suboptions") or opt.get("options")
|
|
58
|
+
if isinstance(subs, dict):
|
|
59
|
+
out["suboptions"] = {k: _option(v) for k, v in subs.items() if isinstance(v, dict)}
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _returns(ret: Any) -> dict:
|
|
64
|
+
if not isinstance(ret, dict):
|
|
65
|
+
return {}
|
|
66
|
+
out = {}
|
|
67
|
+
for name, r in ret.items():
|
|
68
|
+
if not isinstance(r, dict):
|
|
69
|
+
continue
|
|
70
|
+
item = {"type": r.get("type") or "raw", "description": text(r.get("description"))}
|
|
71
|
+
if r.get("returned"):
|
|
72
|
+
item["returned"] = text(r.get("returned"))
|
|
73
|
+
if isinstance(r.get("contains"), dict):
|
|
74
|
+
item["contains"] = _returns(r["contains"])
|
|
75
|
+
out[name] = item
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _deprecated(dep: Any) -> dict | None:
|
|
80
|
+
if not isinstance(dep, dict):
|
|
81
|
+
return None
|
|
82
|
+
return {
|
|
83
|
+
"removed_in": str(
|
|
84
|
+
dep.get("removed_in") or dep.get("version") or dep.get("removed_at_date") or ""
|
|
85
|
+
),
|
|
86
|
+
"why": text(dep.get("why")),
|
|
87
|
+
"alternative": text(dep.get("alternative") or dep.get("alternatives")),
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _plugin(ptype: str, fqcn: str, entry: dict) -> dict | None:
|
|
92
|
+
if ptype == "keyword":
|
|
93
|
+
return {
|
|
94
|
+
"type": "keyword",
|
|
95
|
+
"fqcn": fqcn,
|
|
96
|
+
"collection": "ansible.builtin",
|
|
97
|
+
"name": fqcn,
|
|
98
|
+
"short_description": text(entry.get("description")).split("\n")[0],
|
|
99
|
+
"description": text(entry.get("description")),
|
|
100
|
+
"applies_to": entry.get("applies_to") or [],
|
|
101
|
+
}
|
|
102
|
+
doc = entry.get("doc")
|
|
103
|
+
if not isinstance(doc, dict):
|
|
104
|
+
return None
|
|
105
|
+
attributes = {}
|
|
106
|
+
for name, attr in (doc.get("attributes") or {}).items():
|
|
107
|
+
if isinstance(attr, dict):
|
|
108
|
+
attributes[name] = {
|
|
109
|
+
"support": attr.get("support"),
|
|
110
|
+
"description": text(attr.get("description")),
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
"type": ptype,
|
|
114
|
+
"fqcn": fqcn,
|
|
115
|
+
"collection": doc.get("collection") or ".".join(fqcn.split(".")[:2]),
|
|
116
|
+
"name": fqcn.split(".")[-1],
|
|
117
|
+
"short_description": text(doc.get("short_description")),
|
|
118
|
+
"description": text(doc.get("description")),
|
|
119
|
+
"options": {
|
|
120
|
+
k: _option(v) for k, v in (doc.get("options") or {}).items() if isinstance(v, dict)
|
|
121
|
+
},
|
|
122
|
+
"returns": _returns(entry.get("return")),
|
|
123
|
+
"examples": entry.get("examples") if isinstance(entry.get("examples"), str) else "",
|
|
124
|
+
"attributes": attributes,
|
|
125
|
+
"notes": text(doc.get("notes")),
|
|
126
|
+
"requirements": text(doc.get("requirements")),
|
|
127
|
+
"deprecated": _deprecated(doc.get("deprecated")),
|
|
128
|
+
"version_added": str(doc.get("version_added") or ""),
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _routing(runtime: Any) -> dict:
|
|
133
|
+
"""plugin_routing of a runtime.yml: redirects, deprecations, tombstones (removed plugins)."""
|
|
134
|
+
out: dict[str, dict] = {}
|
|
135
|
+
if not isinstance(runtime, dict):
|
|
136
|
+
return out
|
|
137
|
+
for ptype, plugins in (runtime.get("plugin_routing") or {}).items():
|
|
138
|
+
kind = "module" if ptype == "modules" else ptype.rstrip("s")
|
|
139
|
+
for name, entry in (plugins or {}).items():
|
|
140
|
+
if not isinstance(entry, dict):
|
|
141
|
+
continue
|
|
142
|
+
item: dict[str, Any] = {}
|
|
143
|
+
if entry.get("redirect"):
|
|
144
|
+
item["redirect"] = str(entry["redirect"])
|
|
145
|
+
for key in ("deprecation", "tombstone"):
|
|
146
|
+
if isinstance(entry.get(key), dict):
|
|
147
|
+
item[key] = {
|
|
148
|
+
"removal_version": str(
|
|
149
|
+
entry[key].get("removal_version")
|
|
150
|
+
or entry[key].get("removal_date")
|
|
151
|
+
or ""
|
|
152
|
+
),
|
|
153
|
+
"warning_text": text(entry[key].get("warning_text")),
|
|
154
|
+
}
|
|
155
|
+
if item:
|
|
156
|
+
out.setdefault(kind, {})[name] = item
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _load_yaml(path: str) -> Any:
|
|
161
|
+
from ansible.parsing.dataloader import DataLoader
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
return DataLoader().load_from_file(path)
|
|
165
|
+
except Exception:
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def installed_collections() -> list[dict]:
|
|
170
|
+
"""Collections the environment sees, first path wins (Ansible's own precedence)."""
|
|
171
|
+
exe = shutil.which("ansible-galaxy")
|
|
172
|
+
cmd = [exe] if exe else [sys.executable, "-m", "ansible.cli.galaxy"]
|
|
173
|
+
proc = subprocess.run(
|
|
174
|
+
[*cmd, "collection", "list", "--format", "json"],
|
|
175
|
+
capture_output=True,
|
|
176
|
+
text=True,
|
|
177
|
+
timeout=120,
|
|
178
|
+
check=False,
|
|
179
|
+
)
|
|
180
|
+
seen: dict[str, dict] = {}
|
|
181
|
+
try:
|
|
182
|
+
data = json.loads(proc.stdout or "{}")
|
|
183
|
+
except json.JSONDecodeError:
|
|
184
|
+
data = {}
|
|
185
|
+
for path, colls in data.items():
|
|
186
|
+
for name, info in (colls or {}).items():
|
|
187
|
+
if name in seen or name.startswith("ansible._"):
|
|
188
|
+
continue
|
|
189
|
+
seen[name] = {
|
|
190
|
+
"name": name,
|
|
191
|
+
"version": str((info or {}).get("version") or "0"),
|
|
192
|
+
"path": os.path.join(path, *name.split(".")),
|
|
193
|
+
}
|
|
194
|
+
return sorted(seen.values(), key=lambda c: c["name"])
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _doc_command() -> list[str]:
|
|
198
|
+
exe = shutil.which("ansible-doc")
|
|
199
|
+
return [exe] if exe else [sys.executable, "-m", "ansible.cli.doc"]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _dump(name: str, version: str, path: str | None, core: str) -> dict:
|
|
203
|
+
"""Dumps one collection (or ansible.builtin) and returns the normalized file content."""
|
|
204
|
+
started = time.monotonic()
|
|
205
|
+
proc = subprocess.run(
|
|
206
|
+
[*_doc_command(), "--metadata-dump", "--no-fail-on-errors", name],
|
|
207
|
+
capture_output=True,
|
|
208
|
+
text=True,
|
|
209
|
+
timeout=DUMP_TIMEOUT,
|
|
210
|
+
check=False,
|
|
211
|
+
)
|
|
212
|
+
try:
|
|
213
|
+
raw = json.loads(proc.stdout or "{}")
|
|
214
|
+
except json.JSONDecodeError:
|
|
215
|
+
raw = {}
|
|
216
|
+
plugins = []
|
|
217
|
+
for ptype, entries in (raw.get("all") or {}).items():
|
|
218
|
+
if ptype not in KEPT_TYPES or not isinstance(entries, dict):
|
|
219
|
+
continue
|
|
220
|
+
# Keywords come with every dump; keep them once, with ansible.builtin.
|
|
221
|
+
if ptype == "keyword" and name != "ansible.builtin":
|
|
222
|
+
continue
|
|
223
|
+
for fqcn, entry in entries.items():
|
|
224
|
+
if isinstance(entry, dict):
|
|
225
|
+
p = _plugin(ptype, fqcn, entry)
|
|
226
|
+
if p:
|
|
227
|
+
plugins.append(p)
|
|
228
|
+
if name == "ansible.builtin":
|
|
229
|
+
import ansible
|
|
230
|
+
|
|
231
|
+
runtime = _load_yaml(
|
|
232
|
+
os.path.join(os.path.dirname(ansible.__file__), "config", "ansible_builtin_runtime.yml")
|
|
233
|
+
)
|
|
234
|
+
else:
|
|
235
|
+
runtime = _load_yaml(os.path.join(path or "", "meta", "runtime.yml"))
|
|
236
|
+
errors = raw.get("errors") or []
|
|
237
|
+
return {
|
|
238
|
+
"format": FORMAT,
|
|
239
|
+
"collection": name,
|
|
240
|
+
"version": version,
|
|
241
|
+
"core": core,
|
|
242
|
+
"plugins": plugins,
|
|
243
|
+
"routing": _routing(runtime),
|
|
244
|
+
"errors": [text(e if isinstance(e, str) else e.get("msg", e)) for e in errors][:50],
|
|
245
|
+
"seconds": round(time.monotonic() - started, 2),
|
|
246
|
+
"stderr": proc.stderr[-2000:] if proc.returncode else "",
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
_DUMP_COLLECTION = re.compile(r"^[\w-]+\.[\w-]+$", re.ASCII)
|
|
251
|
+
_DUMP_VERSION = re.compile(r"^[\w.+*-]+$", re.ASCII)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _dump_name_ok(c: dict) -> bool:
|
|
255
|
+
"""Whether `<name>@<version>.json` is one plain file name (AFD-134)."""
|
|
256
|
+
return bool(
|
|
257
|
+
_DUMP_COLLECTION.match(str(c.get("name", "")))
|
|
258
|
+
and _DUMP_VERSION.match(str(c.get("version", "")))
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def catalog(root: str, cache: str, jobs: int = 8, only: list[str] | None = None) -> dict:
|
|
263
|
+
"""Dumps what is missing from `cache` and returns the manifest of this environment.
|
|
264
|
+
|
|
265
|
+
`only` limits the manifest to these collections (a partial refresh; contract tests).
|
|
266
|
+
"""
|
|
267
|
+
from ansible.release import __version__ as core_version
|
|
268
|
+
|
|
269
|
+
core_minor = ".".join(core_version.split(".")[:2])
|
|
270
|
+
folder = os.path.join(cache, core_minor)
|
|
271
|
+
os.makedirs(folder, exist_ok=True)
|
|
272
|
+
wanted = [
|
|
273
|
+
{"name": "ansible.builtin", "version": core_version, "path": None},
|
|
274
|
+
*installed_collections(),
|
|
275
|
+
]
|
|
276
|
+
if only:
|
|
277
|
+
wanted = [c for c in wanted if c["name"] in only]
|
|
278
|
+
# AFD-134: the name and version become a file name in the cache, which local and WSL runs
|
|
279
|
+
# share with the host; a collection whose metadata could name another path is left out.
|
|
280
|
+
for c in [c for c in wanted if not _dump_name_ok(c)]:
|
|
281
|
+
print(
|
|
282
|
+
f"afd_probe: catalog skips {c['name']!r} {c['version']!r}: not a safe file name",
|
|
283
|
+
file=sys.stderr,
|
|
284
|
+
)
|
|
285
|
+
wanted = [c for c in wanted if _dump_name_ok(c)]
|
|
286
|
+
todo = []
|
|
287
|
+
entries = []
|
|
288
|
+
for c in wanted:
|
|
289
|
+
file = f"{c['name']}@{c['version']}.json"
|
|
290
|
+
entries.append({"name": c["name"], "version": c["version"], "file": f"{core_minor}/{file}"})
|
|
291
|
+
if not os.path.isfile(os.path.join(folder, file)):
|
|
292
|
+
todo.append((c, file))
|
|
293
|
+
started = time.monotonic()
|
|
294
|
+
|
|
295
|
+
def work(item: tuple[dict, str]) -> tuple[str, int, str | None]:
|
|
296
|
+
c, file = item
|
|
297
|
+
try:
|
|
298
|
+
data = _dump(c["name"], c["version"], c["path"], core_version)
|
|
299
|
+
except Exception as exc: # one broken collection never stops the catalog
|
|
300
|
+
return file, 0, str(exc)
|
|
301
|
+
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
|
|
302
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
303
|
+
json.dump(data, fh)
|
|
304
|
+
os.replace(tmp, os.path.join(folder, file))
|
|
305
|
+
return file, len(data["plugins"]), None
|
|
306
|
+
|
|
307
|
+
results = {}
|
|
308
|
+
with ThreadPoolExecutor(max_workers=max(1, min(jobs, len(todo) or 1))) as pool:
|
|
309
|
+
for file, count, error in pool.map(work, todo):
|
|
310
|
+
results[file] = {"plugins": count, "error": error}
|
|
311
|
+
for e in entries:
|
|
312
|
+
done = results.get(os.path.basename(e["file"]))
|
|
313
|
+
e["dumped"] = done is not None
|
|
314
|
+
if done and done["error"]:
|
|
315
|
+
e["error"] = done["error"]
|
|
316
|
+
return {
|
|
317
|
+
"core": core_version,
|
|
318
|
+
"collections": entries,
|
|
319
|
+
"dumped": len(todo),
|
|
320
|
+
"seconds": round(time.monotonic() - started, 2),
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def roles(root: str) -> list[dict]:
|
|
325
|
+
"""Roles of the repository (roles_path) with their argument specs (meta/argument_specs.yml)."""
|
|
326
|
+
from ansible import constants as C
|
|
327
|
+
|
|
328
|
+
found: dict[str, dict] = {}
|
|
329
|
+
paths = [os.path.join(root, "roles"), *[p for p in (C.DEFAULT_ROLES_PATH or [])]]
|
|
330
|
+
for base in paths:
|
|
331
|
+
base = base if os.path.isabs(base) else os.path.join(root, base)
|
|
332
|
+
if not os.path.isdir(base):
|
|
333
|
+
continue
|
|
334
|
+
for name in sorted(os.listdir(base)):
|
|
335
|
+
role_dir = os.path.join(base, name)
|
|
336
|
+
if name in found or not os.path.isdir(os.path.join(role_dir, "tasks")):
|
|
337
|
+
continue
|
|
338
|
+
spec_file = next(
|
|
339
|
+
(
|
|
340
|
+
os.path.join(role_dir, "meta", f)
|
|
341
|
+
for f in ("argument_specs.yml", "argument_specs.yaml")
|
|
342
|
+
if os.path.isfile(os.path.join(role_dir, "meta", f))
|
|
343
|
+
),
|
|
344
|
+
None,
|
|
345
|
+
)
|
|
346
|
+
specs = _load_yaml(spec_file) if spec_file else None
|
|
347
|
+
entry_points = {}
|
|
348
|
+
for ep, spec in ((specs or {}).get("argument_specs") or {}).items():
|
|
349
|
+
if isinstance(spec, dict):
|
|
350
|
+
entry_points[ep] = {
|
|
351
|
+
"short_description": text(spec.get("short_description")),
|
|
352
|
+
"description": text(spec.get("description")),
|
|
353
|
+
"options": {
|
|
354
|
+
k: _option(v)
|
|
355
|
+
for k, v in (spec.get("options") or {}).items()
|
|
356
|
+
if isinstance(v, dict)
|
|
357
|
+
},
|
|
358
|
+
}
|
|
359
|
+
tasks_dir = os.path.join(role_dir, "tasks")
|
|
360
|
+
files = sorted(f for f in os.listdir(tasks_dir) if f.endswith((".yml", ".yaml")))
|
|
361
|
+
tasks = [f.rsplit(".", 1)[0] for f in files]
|
|
362
|
+
found[name] = {
|
|
363
|
+
"name": name,
|
|
364
|
+
"path": os.path.relpath(role_dir, root).replace(os.sep, "/"),
|
|
365
|
+
"entry_points": entry_points,
|
|
366
|
+
"tasks": tasks,
|
|
367
|
+
"includes": _task_includes(tasks_dir, files, set(tasks)),
|
|
368
|
+
}
|
|
369
|
+
return sorted(found.values(), key=lambda r: r["name"])
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
_TASK_INCLUDES = {
|
|
373
|
+
"include_tasks",
|
|
374
|
+
"import_tasks",
|
|
375
|
+
"include",
|
|
376
|
+
"ansible.builtin.include_tasks",
|
|
377
|
+
"ansible.builtin.import_tasks",
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _task_includes(tasks_dir: str, files: list[str], names: set[str]) -> dict[str, list[str]]:
|
|
382
|
+
"""Task file -> the task files of the same role it includes by a literal name (AFD-151).
|
|
383
|
+
|
|
384
|
+
A file reached only through another (main -> install -> install_Debian) is part of what
|
|
385
|
+
includes it, so drift does not offer it as a step of its own. Templated names are skipped.
|
|
386
|
+
"""
|
|
387
|
+
|
|
388
|
+
def walk(items: object, out: set[str]) -> None:
|
|
389
|
+
for task in items if isinstance(items, list) else []:
|
|
390
|
+
if not isinstance(task, dict):
|
|
391
|
+
continue
|
|
392
|
+
for key in ("block", "rescue", "always"):
|
|
393
|
+
walk(task.get(key), out)
|
|
394
|
+
for module in _TASK_INCLUDES & task.keys():
|
|
395
|
+
value = task[module]
|
|
396
|
+
target = value.get("file") if isinstance(value, dict) else value
|
|
397
|
+
if not isinstance(target, str) or "{{" in target or "{%" in target:
|
|
398
|
+
continue
|
|
399
|
+
stem = os.path.basename(target.strip()).rsplit(".", 1)[0]
|
|
400
|
+
if stem in names:
|
|
401
|
+
out.add(stem)
|
|
402
|
+
|
|
403
|
+
graph: dict[str, list[str]] = {}
|
|
404
|
+
for f in files:
|
|
405
|
+
found: set[str] = set()
|
|
406
|
+
walk(_load_yaml(os.path.join(tasks_dir, f)), found)
|
|
407
|
+
if found:
|
|
408
|
+
graph[f.rsplit(".", 1)[0]] = sorted(found)
|
|
409
|
+
return graph
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""What Ansible compiles from the repository (M6, ADR-0012): plays and tasks with their origin
|
|
2
|
+
(file and line), tags, actions, registered variables and set facts. The flow's generated
|
|
3
|
+
playbooks are matched to nodes through `node_<ULID>` tags; bound roles are expanded through a
|
|
4
|
+
synthetic play that imports them (07 §5: dynamic includes are not expanded, only reported).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
AUTO_ACTIONS = {"validate_argument_spec", "ansible.builtin.validate_argument_spec"}
|
|
13
|
+
DYNAMIC_ACTIONS = {
|
|
14
|
+
"include_tasks",
|
|
15
|
+
"include_role",
|
|
16
|
+
"ansible.builtin.include_tasks",
|
|
17
|
+
"ansible.builtin.include_role",
|
|
18
|
+
"include",
|
|
19
|
+
}
|
|
20
|
+
FACT_ACTIONS = {"set_fact", "ansible.builtin.set_fact"}
|
|
21
|
+
STATS_ACTIONS = {"set_stats", "ansible.builtin.set_stats"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _relative(root: str, path: str | None) -> str | None:
|
|
25
|
+
if not path:
|
|
26
|
+
return None
|
|
27
|
+
norm = os.path.normpath(path)
|
|
28
|
+
base = os.path.normpath(root)
|
|
29
|
+
return (
|
|
30
|
+
os.path.relpath(norm, base).replace(os.sep, "/") if norm.startswith(base + os.sep) else norm
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _origin(root: str, obj: Any) -> dict | None:
|
|
35
|
+
"""`_origin` (ansible-core 2.19+) or the older `ansible_pos` of the data structure."""
|
|
36
|
+
o = getattr(obj, "_origin", None)
|
|
37
|
+
if o is not None and getattr(o, "path", None):
|
|
38
|
+
return {"path": _relative(root, o.path), "line": getattr(o, "line_num", None)}
|
|
39
|
+
pos = getattr(getattr(obj, "_ds", None), "ansible_pos", None)
|
|
40
|
+
if pos:
|
|
41
|
+
return {"path": _relative(root, pos[0]), "line": pos[1]}
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _names(value: Any) -> list[str]:
|
|
46
|
+
"""`register: x` (string) or the 2.21 form `{x: '_task.polymorphic_result'}`."""
|
|
47
|
+
if isinstance(value, str):
|
|
48
|
+
return [value] if value else []
|
|
49
|
+
if isinstance(value, dict):
|
|
50
|
+
return [str(k) for k in value]
|
|
51
|
+
return []
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _task(root: str, task: Any, section: str) -> dict | None:
|
|
55
|
+
action = str(task.action or "")
|
|
56
|
+
origin = _origin(root, task)
|
|
57
|
+
# flush_handlers and other implicit meta tasks have no place in a file.
|
|
58
|
+
if action == "meta" and origin is None:
|
|
59
|
+
return None
|
|
60
|
+
args = task.args if isinstance(task.args, dict) else {}
|
|
61
|
+
facts: list[str] = []
|
|
62
|
+
stats: list[str] = []
|
|
63
|
+
if action in FACT_ACTIONS:
|
|
64
|
+
facts = [str(k) for k in args if k != "cacheable"]
|
|
65
|
+
if action in STATS_ACTIONS and isinstance(args.get("data"), dict):
|
|
66
|
+
stats = [str(k) for k in args["data"]]
|
|
67
|
+
role = getattr(task, "_role", None)
|
|
68
|
+
return {
|
|
69
|
+
"name": str(task.name or ""),
|
|
70
|
+
"action": action,
|
|
71
|
+
"tags": [str(t) for t in (task.tags or [])],
|
|
72
|
+
"origin": origin,
|
|
73
|
+
"register": _names(task.register),
|
|
74
|
+
"facts": facts,
|
|
75
|
+
"stats": stats,
|
|
76
|
+
"role": role.get_name() if role is not None else None,
|
|
77
|
+
"section": section,
|
|
78
|
+
"dynamic": action in DYNAMIC_ACTIONS,
|
|
79
|
+
"auto": action in AUTO_ACTIONS,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _flatten(
|
|
84
|
+
root: str, blocks: list, section: str = "block", out: list | None = None
|
|
85
|
+
) -> list[dict]:
|
|
86
|
+
out = [] if out is None else out
|
|
87
|
+
for item in blocks:
|
|
88
|
+
if hasattr(item, "block"):
|
|
89
|
+
_flatten(root, item.block, section, out)
|
|
90
|
+
_flatten(root, item.rescue, "rescue", out)
|
|
91
|
+
_flatten(root, item.always, "always", out)
|
|
92
|
+
else:
|
|
93
|
+
t = _task(root, item, section)
|
|
94
|
+
if t:
|
|
95
|
+
out.append(t)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _context(root: str):
|
|
100
|
+
from ansible.inventory.manager import InventoryManager
|
|
101
|
+
from ansible.parsing.dataloader import DataLoader
|
|
102
|
+
from ansible.vars.manager import VariableManager
|
|
103
|
+
|
|
104
|
+
loader = DataLoader()
|
|
105
|
+
loader.set_basedir(root)
|
|
106
|
+
# Compiling needs no hosts: an empty inventory keeps it offline and fast.
|
|
107
|
+
inventory = InventoryManager(loader=loader, sources=["localhost,"])
|
|
108
|
+
return loader, VariableManager(loader=loader, inventory=inventory)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _error(exc: Exception) -> str:
|
|
112
|
+
return " ".join(f"{type(exc).__name__}: {exc}".split())[:400]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def compile_code(
|
|
116
|
+
root: str,
|
|
117
|
+
playbooks: list[str] | None = None,
|
|
118
|
+
roles: list[dict] | None = None,
|
|
119
|
+
) -> dict[str, Any]:
|
|
120
|
+
from ansible.playbook import Playbook
|
|
121
|
+
from ansible.playbook.play import Play
|
|
122
|
+
|
|
123
|
+
loader, variables = _context(root)
|
|
124
|
+
out: dict[str, Any] = {"playbooks": [], "roles": []}
|
|
125
|
+
for path in playbooks or []:
|
|
126
|
+
entry: dict[str, Any] = {"path": path, "plays": []}
|
|
127
|
+
full = path if os.path.isabs(path) else os.path.join(root, path)
|
|
128
|
+
if not os.path.isfile(full):
|
|
129
|
+
entry["error"] = "not found"
|
|
130
|
+
out["playbooks"].append(entry)
|
|
131
|
+
continue
|
|
132
|
+
try:
|
|
133
|
+
book = Playbook.load(full, variable_manager=variables, loader=loader)
|
|
134
|
+
for play in book.get_plays():
|
|
135
|
+
entry["plays"].append(
|
|
136
|
+
{
|
|
137
|
+
"name": play.get_name(),
|
|
138
|
+
"hosts": str(play.hosts),
|
|
139
|
+
"tags": [str(t) for t in (play.tags or [])],
|
|
140
|
+
"origin": _origin(root, play),
|
|
141
|
+
"tasks": _flatten(root, play.compile()),
|
|
142
|
+
}
|
|
143
|
+
)
|
|
144
|
+
except Exception as exc: # one broken playbook never stops the scan
|
|
145
|
+
entry["error"] = _error(exc)
|
|
146
|
+
out["playbooks"].append(entry)
|
|
147
|
+
for spec in roles or []:
|
|
148
|
+
name = str(spec.get("name") or "")
|
|
149
|
+
tasks_from = spec.get("tasks_from") or None
|
|
150
|
+
entry = {"name": name, "tasks_from": tasks_from, "tasks": []}
|
|
151
|
+
include: dict[str, Any] = {"name": name}
|
|
152
|
+
if tasks_from:
|
|
153
|
+
include["tasks_from"] = tasks_from
|
|
154
|
+
play_ds = {
|
|
155
|
+
"name": "afd compile",
|
|
156
|
+
"hosts": "localhost",
|
|
157
|
+
"gather_facts": False,
|
|
158
|
+
"tasks": [{"ansible.builtin.import_role": include}],
|
|
159
|
+
}
|
|
160
|
+
try:
|
|
161
|
+
play = Play.load(play_ds, variable_manager=variables, loader=loader)
|
|
162
|
+
entry["tasks"] = _flatten(root, play.compile())
|
|
163
|
+
except Exception as exc:
|
|
164
|
+
entry["error"] = _error(exc)
|
|
165
|
+
out["roles"].append(entry)
|
|
166
|
+
return out
|