Last active
January 27, 2019 08:04
-
-
Save bcatubig/e57912061438d0bd2900ab652fd5bf98 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
import subprocess | |
from multiprocessing import Pool | |
from functools import partial | |
import argparse | |
import sys | |
from itertools import chain | |
def execute_playbook(ansible_string, pb): | |
# Note: If ansible fails, it prints to stdout | |
# only system errors are handled by stderr | |
print("Now executing playbook: {}".format(pb)) | |
ansible_string.append(pb) | |
p = subprocess.Popen(ansible_string, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
stdout_output = None | |
while not (stdout_output == '' and p.poll() is not None): | |
stdout_output = p.stdout.readline() | |
if stdout_output: | |
# Stream output to stdout | |
print(pb + ' | ' + stdout_output.strip()) | |
rc = p.poll() | |
stdout, stderr = p.communicate() | |
if stderr: | |
print("[-] ERROR: {}".format(stderr)) | |
return (pb, rc) | |
def build_ansible_string(extra_vars): | |
ansible_string = ['ansible-playbook', '-i', 'localhost,', '-c', 'local'] | |
for var in extra_vars: | |
ansible_string.append('-e') | |
ansible_string.append(var) | |
return ansible_string | |
def main(): | |
parser = argparse.ArgumentParser(description='Process ansible playbooks') | |
parser.add_argument('playbooks', metavar='PLAYBOOK', nargs='+', | |
help='The name of an Ansible playbook.') | |
parser.add_argument('-e', '--extra_var', metavar='EXTRA_VAR', nargs="+", | |
help="The key=value extra argument", action="append") | |
args = parser.parse_args() | |
playbooks = args.playbooks | |
extra_vars = args.extra_var | |
extra_vars = list(chain.from_iterable(extra_vars)) | |
ansible_string = build_ansible_string(extra_vars) | |
num_of_playbooks = len(playbooks) | |
pool = Pool() | |
print("Number of playbooks to process: {}".format(num_of_playbooks)) | |
func = partial(execute_playbook, ansible_string) | |
return_codes = pool.map(func, playbooks) | |
pool.close() | |
pool.join() | |
print ('-' * 80) | |
fail_counter = 0 | |
for playbook, rc in return_codes: | |
if rc != 0: | |
print("[-] {} failed to execute properly".format(playbook)) | |
fail_counter += 1 | |
if fail_counter != 0: | |
print("[-] ERROR: Failed to run all playbooks successfully.") | |
sys.exit(255) | |
for pb, rc in return_codes: | |
print("Playbook executed: {}".format(pb)) | |
print("[+] SUCCESS: All playbooks executed successfully.") | |
sys.exit(0) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Sample output