Created
October 1, 2015 20:18
-
-
Save ryancurrah/a4927c87b3c64d621c8f to your computer and use it in GitHub Desktop.
salt-target-hosts
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
from subprocess import Popen, PIPE | |
from argparse import ArgumentParser | |
from pprint import pprint | |
import logging | |
import sys | |
import salt.client | |
import json | |
logging.basicConfig(stream=sys.stdout, | |
format='%(asctime)s %(levelname)s: %(message)s', | |
level=logging.DEBUG) | |
def main(): | |
parser = ArgumentParser() | |
parser.add_argument('--filename', | |
help='File with hostname on a new line to execute commands on.') | |
parser.add_argument('--fun', | |
help='Salt function to execute. EG: "state.sls".') | |
parser.add_argument('--args', | |
help='Salt argument. EG: "splunkforwarder.conf".') | |
args = parser.parse_args() | |
json_log = '{0}_result.json'.format(args.filename) | |
json_results = [] | |
# Reading file and convert to list removing empty lines | |
hosts = [line.strip() for line in read_file(args.filename).split('\n')] | |
# Execute commands | |
for host in hosts: | |
cmd = 'salt "{0}" {1} {2}'.format(host, args.fun, args.args) | |
print 'Executing Salt command: \'{0}\' On host: \'{1}\''.format(cmd, host) | |
result = {host: run(host, args.fun, args.args)} | |
json_results.append(result) | |
logging.info(result) | |
pprint(result) | |
open(json_log, 'w').write(json.dumps(json_results)) | |
return | |
def read_file(filename): | |
return open(filename, 'r').read() | |
def run(host, fun, args): | |
local = salt.client.LocalClient() | |
try: | |
result = local.cmd(host, fun, [args]) | |
except KeyError: | |
result = 'Failed to execute Salt command on host \'{0}\''.format(host) | |
return result | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment