|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Validate every Ansible Vault payload without templating variable values.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from collections.abc import Mapping, Sequence |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +from ansible.parsing.dataloader import DataLoader |
| 13 | +from ansible.parsing.vault import VaultLib, VaultSecret, is_encrypted |
| 14 | + |
| 15 | + |
| 16 | +VAULT_HEADER = b"$ANSIBLE_VAULT;" |
| 17 | +YAML_SUFFIXES = {".yaml", ".yml"} |
| 18 | +EXCLUDED_PARTS = {".ansible", ".git", ".venv"} |
| 19 | + |
| 20 | + |
| 21 | +def encrypted_payloads(value: object): |
| 22 | + """Yield ciphertext from parsed Vault-tagged scalars without rendering Jinja.""" |
| 23 | + ciphertext = getattr(value, "_ciphertext", None) |
| 24 | + if ciphertext is not None and is_encrypted(ciphertext): |
| 25 | + yield ciphertext |
| 26 | + return |
| 27 | + |
| 28 | + if isinstance(value, Mapping): |
| 29 | + for key, item in value.items(): |
| 30 | + yield from encrypted_payloads(key) |
| 31 | + yield from encrypted_payloads(item) |
| 32 | + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): |
| 33 | + for item in value: |
| 34 | + yield from encrypted_payloads(item) |
| 35 | + |
| 36 | + |
| 37 | +def candidate_files(root: Path): |
| 38 | + for path in root.rglob("*"): |
| 39 | + if not path.is_file() or EXCLUDED_PARTS.intersection(path.parts): |
| 40 | + continue |
| 41 | + |
| 42 | + contents = path.read_bytes() |
| 43 | + if contents.lstrip().startswith(VAULT_HEADER) or ( |
| 44 | + path.suffix.lower() in YAML_SUFFIXES and VAULT_HEADER in contents |
| 45 | + ): |
| 46 | + yield path, contents |
| 47 | + |
| 48 | + |
| 49 | +def validate_file(path: Path, contents: bytes, vault: VaultLib) -> int: |
| 50 | + expected = contents.count(VAULT_HEADER) |
| 51 | + if contents.lstrip().startswith(VAULT_HEADER): |
| 52 | + vault.decrypt(contents.strip()) |
| 53 | + return 1 |
| 54 | + |
| 55 | + parsed = DataLoader().load_from_file(str(path)) |
| 56 | + payloads = list(encrypted_payloads(parsed)) |
| 57 | + if len(payloads) != expected: |
| 58 | + raise ValueError( |
| 59 | + f"found {expected} Vault header(s), but parsed {len(payloads)} encrypted value(s)" |
| 60 | + ) |
| 61 | + |
| 62 | + for payload in payloads: |
| 63 | + vault.decrypt(payload) |
| 64 | + return len(payloads) |
| 65 | + |
| 66 | + |
| 67 | +def main() -> int: |
| 68 | + parser = argparse.ArgumentParser(description=__doc__) |
| 69 | + parser.add_argument("--root", type=Path, default=Path.cwd()) |
| 70 | + parser.add_argument( |
| 71 | + "--password-file", |
| 72 | + type=Path, |
| 73 | + default=os.environ.get("ANSIBLE_VAULT_PASSWORD_FILE"), |
| 74 | + ) |
| 75 | + args = parser.parse_args() |
| 76 | + |
| 77 | + if args.password_file is None: |
| 78 | + parser.error("--password-file or ANSIBLE_VAULT_PASSWORD_FILE is required") |
| 79 | + |
| 80 | + password = args.password_file.read_bytes().rstrip(b"\r\n") |
| 81 | + if not password: |
| 82 | + parser.error("the Vault password file is empty") |
| 83 | + |
| 84 | + vault = VaultLib([("default", VaultSecret(password))]) |
| 85 | + files = list(candidate_files(args.root.resolve())) |
| 86 | + if not files: |
| 87 | + print("No Ansible Vault payloads found.", file=sys.stderr) |
| 88 | + return 1 |
| 89 | + |
| 90 | + decrypted = 0 |
| 91 | + failures = 0 |
| 92 | + for path, contents in files: |
| 93 | + try: |
| 94 | + decrypted += validate_file(path, contents, vault) |
| 95 | + except Exception as error: # Ansible exposes several version-specific Vault errors. |
| 96 | + failures += 1 |
| 97 | + print(f"{path.relative_to(args.root.resolve())}: {error}", file=sys.stderr) |
| 98 | + |
| 99 | + if failures: |
| 100 | + return 1 |
| 101 | + |
| 102 | + print(f"Validated {decrypted} Vault value(s) in {len(files)} file(s).") |
| 103 | + return 0 |
| 104 | + |
| 105 | + |
| 106 | +if __name__ == "__main__": |
| 107 | + raise SystemExit(main()) |
0 commit comments