diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index c0d811c..7d609b3 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -46,6 +46,12 @@ entry: check-json language: python types: [json] +- id: check-iam + name: check IAM + description: checks terraform files for parseable IAM syntax. + entry: check-iam + language: python + types: [tf] - id: check-shebang-scripts-are-executable name: check that scripts with shebangs are executable description: ensures that (non-binary) files with a shebang are executable. diff --git a/pre_commit_hooks/check_iam.py b/pre_commit_hooks/check_iam.py new file mode 100644 index 0000000..9fc2cbc --- /dev/null +++ b/pre_commit_hooks/check_iam.py @@ -0,0 +1,40 @@ +import argparse +import hcl2 +# from typing import Any +from typing import Sequence + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument('filenames', nargs='*', help='Filenames to check.') + args = parser.parse_args(argv) + + retval = 0 + for filename in args.filenames: + if filename == "iam.tf": + continue + with open(filename, 'rb') as f: + try: + dict = hcl2.load(f) + except ValueError as exc: + print(f'{filename}: Failed to hcl decode ({exc})') + retval = 1 + resources = data.get('resource') + if resources: + for item in resources: + for keys in item: + if key.startswith("aws_iam"): + print(f'{filename}: Has {key} resource') + retval = 1 + resources = data.get('data') + if resources: + for item in resources: + for keys in item: + if key.startswith("aws_iam"): + print(f'{filename}: Has {key} data resource') + retval = 1 + return retval + + +if __name__ == '__main__': + raise SystemExit(main())