David K. Bainbridge | d955d33 | 2016-08-11 14:01:27 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | import sys |
| 4 | import json |
| 5 | import shlex |
| 6 | import subprocess |
| 7 | |
| 8 | # Assume nothing has changed |
| 9 | result = { |
| 10 | "changed" : False, |
| 11 | "everyone" : "OK" |
| 12 | } |
| 13 | |
| 14 | # read the argument string from the arguments file |
| 15 | args_file = sys.argv[1] |
| 16 | args_data = file(args_file).read() |
| 17 | |
| 18 | # Variables for the task options |
| 19 | host_list = [] |
| 20 | command_on_fail = None |
| 21 | |
| 22 | # parse the task options |
| 23 | arguments = shlex.split(args_data) |
| 24 | |
| 25 | for arg in arguments: |
| 26 | # ignore any arguments without an equals in it |
| 27 | if "=" in arg: |
| 28 | (key, value) = arg.split("=") |
| 29 | |
| 30 | if key == "hosts": |
| 31 | # The list of hosts comes as a string that looks sort of like a python list, |
| 32 | # so some replace magic so we can parse it in to a real list |
| 33 | try: |
| 34 | value = value.replace("u'", "").replace("'", "") |
| 35 | value = json.loads(value) |
| 36 | host_list = value |
| 37 | except Exception as e: |
| 38 | result["everyone"] = "Not OK" |
| 39 | result["failed"] = True |
| 40 | result["msg"] = "Unable to parse 'hosts' argument to module : '%s'" % (e) |
| 41 | print json.dumps(result) |
| 42 | sys.stdout.flush() |
| 43 | sys.exit(1) |
| 44 | if key == "command_on_fail": |
| 45 | command_on_fail = value |
| 46 | |
| 47 | for host in host_list: |
| 48 | # Attempt to resolve hostname, if a host can't be resolved then fail the task |
| 49 | try: |
| 50 | if subprocess.check_output(["dig", "+short", "+search", host]) == '': |
| 51 | result["everyone"] = "Not OK" |
| 52 | result["failed"] = True |
| 53 | result["msg"] = "Unable to resolve host '%s'" % (host) |
| 54 | except Exception as e: |
| 55 | result["everyone"] = "Not OK" |
| 56 | result["failed"] = True |
| 57 | result["msg"] = "Error encountered while resolving '%s' : '%s'" % (host, e) |
| 58 | print json.dumps(result) |
| 59 | sys.stdout.flush() |
| 60 | sys.exit(1) |
| 61 | |
| 62 | # If not all hosts were resolved and a failure command was specified then call that |
| 63 | # command and capture the results. |
| 64 | if command_on_fail != None: |
| 65 | result["command_on_fail"] = {} |
| 66 | result["command_on_fail"]["command"] = command_on_fail |
| 67 | try: |
| 68 | cmd_out = subprocess.check_output(shlex.split(command_on_fail), shell=True, stderr=subprocess.STDOUT) |
| 69 | result["command_on_fail"]["retcode"] = 0 |
| 70 | result["command_on_fail"]["out"] = cmd_out |
| 71 | except subprocess.CalledProcessError as e: |
| 72 | result["command_on_fail"]["retcode"] = e.returncode |
| 73 | result["command_on_fail"]["out"] = e.output |
| 74 | |
| 75 | # Output the results |
| 76 | print json.dumps(result) |
| 77 | |
| 78 | if result["failed"]: |
| 79 | sys.exit(1) |