From f60596972cede8d7d71343a3253a38dcb8430377 Mon Sep 17 00:00:00 2001 From: Adrian Lopez Date: Fri, 2 Dec 2022 09:07:12 +0100 Subject: [PATCH] yaml: add new option to ignore "!ansible" tags This new option for the yaml checker modify ruamel to remove the "!" from the "!vault" tag if it is found. Removing that part allows the file to be parsed correctly, so other errors could be found. fixes: #273 --- pre_commit_hooks/check_yaml.py | 18 ++++++++++++++++++ tests/check_yaml_test.py | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/pre_commit_hooks/check_yaml.py b/pre_commit_hooks/check_yaml.py index 250794e..fa75512 100644 --- a/pre_commit_hooks/check_yaml.py +++ b/pre_commit_hooks/check_yaml.py @@ -52,11 +52,29 @@ def main(argv: Sequence[str] | None = None) -> int: 'Implies --allow-multiple-documents' ), ) + parser.add_argument( + '--ignore-ansible-vault', action='store_true', + help=( + 'Ignore keys that look like ansible vault encrypted values. ' + 'This works by removing the "!" from the "!vault" value prefix.' + ), + ) parser.add_argument('filenames', nargs='*', help='Filenames to check.') args = parser.parse_args(argv) load_fn = LOAD_FNS[Key(multi=args.multi, unsafe=args.unsafe)] + if args.ignore_ansible_vault: + def ignore_ansible_vault(loader: ruamel.yaml.Loader, + node: ruamel.yaml.Node) -> Any: + if node.value.startswith('!vault'): + node.value = node.value[1:] + return loader.construct_yaml_str(node) + + ruamel.yaml.add_constructor(u'!vault', + ignore_ansible_vault, + constructor=ruamel.yaml.SafeConstructor) + retval = 0 for filename in args.filenames: try: diff --git a/tests/check_yaml_test.py b/tests/check_yaml_test.py index 54eb16e..21cd0da 100644 --- a/tests/check_yaml_test.py +++ b/tests/check_yaml_test.py @@ -51,3 +51,22 @@ def test_main_unsafe_still_fails_on_syntax_errors(tmpdir): f = tmpdir.join('test.yaml') f.write('[') assert main(('--unsafe', str(f))) + + +def test_main_ignore_ansible_vault(tmpdir): + f = tmpdir.join('test.yaml') + f.write( + 'some_foo: !vault |\n' + ' $ANSIBLE_VAULT;1.1;AES256\n' + ' deadbeefdeadbeefdeadbeef\n', + ) + # should fail "safe" check + assert main((str(f),)) + # should pass when we allow unsafe documents + assert not main(('--ignore-ansible-vault', str(f))) + + +def test_main_ignore_ansible_vault_still_fails_on_syntax_errors(tmpdir): + f = tmpdir.join('test.yaml') + f.write('[') + assert main(('--ignore-ansible-vault', str(f)))