Created
August 21, 2015 12:18
-
-
Save azenk/affce5e1a64400778812 to your computer and use it in GitHub Desktop.
pre commit hook for ansible role syntax checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Install in .git/hooks/pre-commit | |
from subprocess import Popen, PIPE | |
import re | |
import os | |
import sys | |
import tempfile | |
import shutil | |
playbook_template="""--- | |
- hosts: all | |
roles: | |
- {0} | |
""" | |
def make_dummy_role(role_path, role_name): | |
args = ["ansible-galaxy", "init", "--offline", "-p", role_path, role_name ] | |
p = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE) | |
(out,err) = p.communicate() | |
rc = p.wait() | |
def check_role_syntax(role_dir): | |
tempdir = tempfile.mkdtemp() | |
pb_path = os.path.join(tempdir,"test_playbook.yml") | |
with open(pb_path, "w") as pbf: | |
pbf.write(playbook_template.format(role_dir)) | |
inv_path = os.path.join(tempdir,"dummy_inventory") | |
with open(inv_path,"w") as inv: | |
inv.write("[local]\n127.0.0.1\n") | |
args = ["ansible-playbook"] | |
args += ["--syntax-check", "-i", inv_path, pb_path] | |
p = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE) | |
(out,err) = p.communicate() | |
rc = p.wait() | |
missing_role_re = re.compile("ERROR: cannot find role in.*(?<=\/)([^ ]+)") | |
for line in err.splitlines(): | |
m = missing_role_re.match(line.strip()) | |
if m is not None: | |
make_dummy_role(os.path.join(tempdir,"roles"), m.group(1)) | |
p = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE) | |
(out,err) = p.communicate() | |
rc = p.wait() | |
shutil.rmtree(tempdir) | |
if rc != 0: | |
print("{0}".format(err)) | |
sys.exit(rc) | |
if __name__ == "__main__": | |
role_dir = os.getcwd() | |
check_role_syntax(role_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am getting an error when I run the pre-commit hook.
The problem is a dependency I declared that looks like the following:
The hook does understand how to handle dependencies that are pointing to a specific git repository.