blob: cbd39aebf0a48a42b99d82ea4fba365123e45e60 [file] [log] [blame]
David K. Bainbridged3da6082016-08-11 14:01:27 -07001#!/usr/bin/env python
2
3import sys
4import json
5import shlex
6import subprocess
7
8# Assume nothing has changed
9result = {
10 "changed" : False,
11 "everyone" : "OK"
12}
13
14# read the argument string from the arguments file
15args_file = sys.argv[1]
16args_data = file(args_file).read()
17
18# Variables for the task options
19host_list = []
20command_on_fail = None
21
22# parse the task options
23arguments = shlex.split(args_data)
24
25for 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
47for 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.
64if command_on_fail != None:
65 result["command_on_fail"] = {}
66 result["command_on_fail"]["command"] = command_on_fail
67 try:
Andy Bavier6df04682016-09-30 06:09:36 -040068 cmd_out = subprocess.check_output(shlex.split(command_on_fail), stderr=subprocess.STDOUT)
David K. Bainbridged3da6082016-08-11 14:01:27 -070069 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
76print json.dumps(result)
77
78if result["failed"]:
79 sys.exit(1)