Skip to content

Instantly share code, notes, and snippets.

@azenk
Created August 21, 2015 12:18
Show Gist options
  • Save azenk/affce5e1a64400778812 to your computer and use it in GitHub Desktop.
Save azenk/affce5e1a64400778812 to your computer and use it in GitHub Desktop.
pre commit hook for ansible role syntax checking
#!/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)
@DebbieGillespie
Copy link

I am getting an error when I run the pre-commit hook.

ERROR: cannot find role in /var/folders/7f/d72l2g9x2g57tt5kpygfgd5rxsmw_c/T/tmpEe0oQQ/roles/git+ssh:/git@github.umn.edu:ansible-roles/bashrc.git or /var/folders/7f/d72l2g9x2g57tt5kpygfgd5rxsmw_c/T/tmpEe0oQQ/git+ssh:/git@github.umn.edu:ansible-roles/bashrc.git or /Users/debbieg/devel/asr_ansible/roles/git+ssh:/git@github.umn.edu:ansible-roles/bashrc.git

The problem is a dependency I declared that looks like the following:

dependencies:
  - { role: 'git+ssh://git@github.umn.edu:ansible-roles/bashrc.git' }

The hook does understand how to handle dependencies that are pointing to a specific git repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment