2012-03-03 03:08:48 +01:00
|
|
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
|
|
|
|
#
|
|
|
|
# This file is part of Ansible
|
|
|
|
#
|
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2012-03-03 03:16:29 +01:00
|
|
|
###############################################################
|
|
|
|
|
2012-03-03 03:08:48 +01:00
|
|
|
import sys
|
2012-03-03 04:10:51 +01:00
|
|
|
import os
|
2012-03-15 02:16:15 +01:00
|
|
|
import shlex
|
2012-03-20 00:32:38 +01:00
|
|
|
import re
|
2012-05-09 01:03:51 +02:00
|
|
|
import codecs
|
2012-03-20 00:23:14 +01:00
|
|
|
import jinja2
|
2012-03-20 03:42:31 +01:00
|
|
|
import yaml
|
2012-04-06 16:59:15 +02:00
|
|
|
import optparse
|
2012-07-15 14:46:58 +02:00
|
|
|
import operator
|
|
|
|
from ansible import errors
|
|
|
|
import ansible.constants as C
|
2012-07-09 09:52:00 +02:00
|
|
|
|
2012-03-03 03:08:48 +01:00
|
|
|
try:
|
|
|
|
import json
|
|
|
|
except ImportError:
|
|
|
|
import simplejson as json
|
|
|
|
|
2012-07-09 09:52:00 +02:00
|
|
|
try:
|
2012-07-09 19:27:47 +02:00
|
|
|
from hashlib import md5 as _md5
|
2012-07-09 09:52:00 +02:00
|
|
|
except ImportError:
|
2012-07-09 19:27:47 +02:00
|
|
|
from md5 import md5 as _md5
|
2012-07-09 09:52:00 +02:00
|
|
|
|
2012-03-03 03:16:29 +01:00
|
|
|
###############################################################
|
|
|
|
# UTILITY FUNCTIONS FOR COMMAND LINE TOOLS
|
|
|
|
###############################################################
|
|
|
|
|
2012-03-03 03:08:48 +01:00
|
|
|
def err(msg):
|
2012-03-03 03:16:29 +01:00
|
|
|
''' print an error message to stderr '''
|
2012-03-03 03:08:48 +01:00
|
|
|
print >> sys.stderr, msg
|
|
|
|
|
|
|
|
def exit(msg, rc=1):
|
2012-03-03 03:16:29 +01:00
|
|
|
''' quit with an error to stdout and a failure code '''
|
2012-03-03 03:08:48 +01:00
|
|
|
err(msg)
|
|
|
|
sys.exit(rc)
|
|
|
|
|
2012-07-15 16:12:49 +02:00
|
|
|
def jsonify(result, format=False):
|
|
|
|
''' format JSON output (uncompressed or uncompressed) '''
|
2012-03-21 03:29:21 +01:00
|
|
|
result2 = result.copy()
|
2012-07-15 16:12:49 +02:00
|
|
|
if format:
|
|
|
|
return json.dumps(result2, sort_keys=True, indent=4)
|
2012-03-03 03:08:48 +01:00
|
|
|
else:
|
2012-07-15 16:12:49 +02:00
|
|
|
return json.dumps(result2, sort_keys=True)
|
2012-03-03 03:08:48 +01:00
|
|
|
|
2012-03-03 04:10:51 +01:00
|
|
|
def write_tree_file(tree, hostname, buf):
|
2012-03-03 03:16:29 +01:00
|
|
|
''' write something into treedir/hostname '''
|
|
|
|
# TODO: might be nice to append playbook runs per host in a similar way
|
|
|
|
# in which case, we'd want append mode.
|
2012-03-03 04:10:51 +01:00
|
|
|
path = os.path.join(tree, hostname)
|
2012-03-03 03:08:48 +01:00
|
|
|
fd = open(path, "w+")
|
|
|
|
fd.write(buf)
|
|
|
|
fd.close()
|
|
|
|
|
|
|
|
def is_failed(result):
|
2012-03-03 03:16:29 +01:00
|
|
|
''' is a given JSON result a failed result? '''
|
2012-07-15 17:09:15 +02:00
|
|
|
return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true']))
|
2012-03-03 03:08:48 +01:00
|
|
|
|
|
|
|
def prepare_writeable_dir(tree):
|
2012-03-03 03:16:29 +01:00
|
|
|
''' make sure a directory exists and is writeable '''
|
2012-03-03 03:08:48 +01:00
|
|
|
if tree != '/':
|
2012-03-03 04:10:51 +01:00
|
|
|
tree = os.path.realpath(os.path.expanduser(tree))
|
2012-03-03 03:08:48 +01:00
|
|
|
if not os.path.exists(tree):
|
|
|
|
try:
|
|
|
|
os.makedirs(tree)
|
|
|
|
except (IOError, OSError), e:
|
|
|
|
exit("Could not make dir %s: %s" % (tree, e))
|
|
|
|
if not os.access(tree, os.W_OK):
|
|
|
|
exit("Cannot write to path %s" % tree)
|
|
|
|
|
2012-03-03 16:53:15 +01:00
|
|
|
def path_dwim(basedir, given):
|
2012-03-11 23:40:35 +01:00
|
|
|
''' make relative paths work like folks expect '''
|
2012-03-03 16:53:15 +01:00
|
|
|
if given.startswith("/"):
|
|
|
|
return given
|
|
|
|
elif given.startswith("~/"):
|
|
|
|
return os.path.expanduser(given)
|
|
|
|
else:
|
|
|
|
return os.path.join(basedir, given)
|
2012-03-03 03:08:48 +01:00
|
|
|
|
2012-03-18 22:53:58 +01:00
|
|
|
def json_loads(data):
|
2012-07-07 14:18:33 +02:00
|
|
|
''' parse a JSON string and return a data structure '''
|
2012-03-18 22:53:58 +01:00
|
|
|
return json.loads(data)
|
|
|
|
|
2012-03-15 02:16:15 +01:00
|
|
|
def parse_json(data):
|
2012-03-18 22:53:58 +01:00
|
|
|
''' this version for module return data only '''
|
2012-03-15 02:16:15 +01:00
|
|
|
try:
|
|
|
|
return json.loads(data)
|
|
|
|
except:
|
|
|
|
# not JSON, but try "Baby JSON" which allows many of our modules to not
|
|
|
|
# require JSON and makes writing modules in bash much simpler
|
|
|
|
results = {}
|
2012-07-15 15:32:47 +02:00
|
|
|
try:
|
2012-06-14 20:17:38 +02:00
|
|
|
tokens = shlex.split(data)
|
|
|
|
except:
|
|
|
|
print "failed to parse json: "+ data
|
2012-07-15 15:32:47 +02:00
|
|
|
raise
|
2012-06-14 20:17:38 +02:00
|
|
|
|
2012-03-15 02:16:15 +01:00
|
|
|
for t in tokens:
|
|
|
|
if t.find("=") == -1:
|
2012-03-18 22:16:12 +01:00
|
|
|
raise errors.AnsibleError("failed to parse: %s" % data)
|
2012-03-15 02:16:15 +01:00
|
|
|
(key,value) = t.split("=", 1)
|
|
|
|
if key == 'changed' or 'failed':
|
2012-03-16 03:32:14 +01:00
|
|
|
if value.lower() in [ 'true', '1' ]:
|
2012-03-15 02:16:15 +01:00
|
|
|
value = True
|
|
|
|
elif value.lower() in [ 'false', '0' ]:
|
|
|
|
value = False
|
|
|
|
if key == 'rc':
|
|
|
|
value = int(value)
|
|
|
|
results[key] = value
|
2012-03-16 02:53:14 +01:00
|
|
|
if len(results.keys()) == 0:
|
|
|
|
return { "failed" : True, "parsed" : False, "msg" : data }
|
2012-03-15 02:16:15 +01:00
|
|
|
return results
|
|
|
|
|
2012-05-10 19:25:28 +02:00
|
|
|
_LISTRE = re.compile(r"(\w+)\[(\d+)\]")
|
|
|
|
|
2012-06-09 21:59:22 +02:00
|
|
|
def _varLookup(name, vars):
|
2012-05-09 16:05:06 +02:00
|
|
|
''' find the contents of a possibly complex variable in vars. '''
|
|
|
|
path = name.split('.')
|
|
|
|
space = vars
|
|
|
|
for part in path:
|
|
|
|
if part in space:
|
|
|
|
space = space[part]
|
2012-05-10 19:25:28 +02:00
|
|
|
elif "[" in part:
|
|
|
|
m = _LISTRE.search(part)
|
|
|
|
if not m:
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
space = space[m.group(1)][int(m.group(2))]
|
|
|
|
except (KeyError, IndexError):
|
|
|
|
return
|
2012-05-09 16:05:06 +02:00
|
|
|
else:
|
|
|
|
return
|
|
|
|
return space
|
|
|
|
|
2012-05-10 19:25:28 +02:00
|
|
|
_KEYCRE = re.compile(r"\$(?P<complex>\{){0,1}((?(complex)[\w\.\[\]]+|\w+))(?(complex)\})")
|
2012-03-20 00:32:38 +01:00
|
|
|
|
2012-06-09 21:59:22 +02:00
|
|
|
def varLookup(varname, vars):
|
2012-07-07 14:18:33 +02:00
|
|
|
''' helper function used by varReplace '''
|
2012-06-09 21:59:22 +02:00
|
|
|
m = _KEYCRE.search(varname)
|
|
|
|
if not m:
|
|
|
|
return None
|
|
|
|
return _varLookup(m.group(2), vars)
|
|
|
|
|
2012-03-20 00:32:38 +01:00
|
|
|
def varReplace(raw, vars):
|
|
|
|
'''Perform variable replacement of $vars
|
|
|
|
|
|
|
|
@param raw: String to perform substitution on.
|
|
|
|
@param vars: Dictionary of variables to replace. Key is variable name
|
|
|
|
(without $ prefix). Value is replacement string.
|
|
|
|
@return: Input raw string with substituted values.
|
|
|
|
'''
|
|
|
|
# this code originally from yum
|
|
|
|
|
|
|
|
done = [] # Completed chunks to return
|
|
|
|
|
|
|
|
while raw:
|
|
|
|
m = _KEYCRE.search(raw)
|
|
|
|
if not m:
|
|
|
|
done.append(raw)
|
|
|
|
break
|
|
|
|
|
|
|
|
# Determine replacement value (if unknown variable then preserve
|
|
|
|
# original)
|
2012-05-11 14:14:53 +02:00
|
|
|
varname = m.group(2)
|
2012-05-09 16:05:06 +02:00
|
|
|
|
2012-06-09 21:59:22 +02:00
|
|
|
replacement = unicode(_varLookup(varname, vars) or m.group())
|
2012-03-20 00:32:38 +01:00
|
|
|
|
|
|
|
start, end = m.span()
|
|
|
|
done.append(raw[:start]) # Keep stuff leading up to token
|
|
|
|
done.append(replacement) # Append replacement value
|
|
|
|
raw = raw[end:] # Continue with remainder of string
|
|
|
|
|
|
|
|
return ''.join(done)
|
|
|
|
|
2012-06-17 22:18:08 +02:00
|
|
|
def _template(text, vars, setup_cache=None):
|
2012-03-20 00:23:14 +01:00
|
|
|
''' run a text buffer through the templating engine '''
|
2012-04-21 18:45:37 +02:00
|
|
|
vars = vars.copy()
|
|
|
|
vars['hostvars'] = setup_cache
|
2012-07-15 17:09:15 +02:00
|
|
|
return varReplace(unicode(text), vars)
|
2012-03-20 00:23:14 +01:00
|
|
|
|
2012-06-17 22:18:08 +02:00
|
|
|
def template(text, vars, setup_cache=None):
|
2012-06-09 18:40:17 +02:00
|
|
|
''' run a text buffer through the templating engine
|
|
|
|
until it no longer changes '''
|
|
|
|
prev_text = ''
|
2012-07-15 14:46:58 +02:00
|
|
|
depth = 0
|
2012-06-09 18:40:17 +02:00
|
|
|
while prev_text != text:
|
2012-07-15 14:46:58 +02:00
|
|
|
depth = depth + 1
|
|
|
|
if (depth > 20):
|
|
|
|
raise errors.AnsibleError("template recursion depth exceeded")
|
2012-06-09 18:40:17 +02:00
|
|
|
prev_text = text
|
2012-06-17 22:18:08 +02:00
|
|
|
text = _template(text, vars, setup_cache)
|
2012-06-09 18:40:17 +02:00
|
|
|
return text
|
2012-03-22 04:39:09 +01:00
|
|
|
|
2012-06-17 22:18:08 +02:00
|
|
|
def template_from_file(basedir, path, vars, setup_cache):
|
2012-03-20 00:23:14 +01:00
|
|
|
''' run a file through the templating engine '''
|
2012-06-17 22:18:08 +02:00
|
|
|
environment = jinja2.Environment(loader=jinja2.FileSystemLoader(basedir), trim_blocks=False)
|
|
|
|
data = codecs.open(path_dwim(basedir, path), encoding="utf8").read()
|
2012-07-03 16:42:00 +02:00
|
|
|
t = environment.from_string(data)
|
2012-06-17 22:18:08 +02:00
|
|
|
vars = vars.copy()
|
|
|
|
vars['hostvars'] = setup_cache
|
2012-07-03 16:42:00 +02:00
|
|
|
res = t.render(vars)
|
2012-06-17 22:18:08 +02:00
|
|
|
if data.endswith('\n') and not res.endswith('\n'):
|
|
|
|
res = res + '\n'
|
2012-07-03 16:42:00 +02:00
|
|
|
return template(res, vars, setup_cache)
|
2012-03-20 03:42:31 +01:00
|
|
|
|
|
|
|
def parse_yaml(data):
|
2012-07-07 14:18:33 +02:00
|
|
|
''' convert a yaml string to a data structure '''
|
2012-03-20 03:42:31 +01:00
|
|
|
return yaml.load(data)
|
2012-03-20 00:23:14 +01:00
|
|
|
|
2012-03-20 03:42:31 +01:00
|
|
|
def parse_yaml_from_file(path):
|
2012-07-07 14:18:33 +02:00
|
|
|
''' convert a yaml file to a data structure '''
|
2012-03-21 03:29:21 +01:00
|
|
|
try:
|
|
|
|
data = file(path).read()
|
|
|
|
except IOError:
|
|
|
|
raise errors.AnsibleError("file not found: %s" % path)
|
2012-03-20 03:42:31 +01:00
|
|
|
return parse_yaml(data)
|
2012-03-20 00:23:14 +01:00
|
|
|
|
2012-03-31 04:52:38 +02:00
|
|
|
def parse_kv(args):
|
2012-03-22 04:39:09 +01:00
|
|
|
''' convert a string of key/value items to a dict '''
|
|
|
|
options = {}
|
2012-04-27 02:42:20 +02:00
|
|
|
if args is not None:
|
2012-04-27 03:25:43 +02:00
|
|
|
vargs = shlex.split(args, posix=True)
|
|
|
|
for x in vargs:
|
|
|
|
if x.find("=") != -1:
|
2012-05-23 01:58:05 +02:00
|
|
|
k, v = x.split("=", 1)
|
2012-04-27 03:25:43 +02:00
|
|
|
options[k]=v
|
2012-03-22 04:39:09 +01:00
|
|
|
return options
|
2012-03-31 03:56:10 +02:00
|
|
|
|
2012-07-09 09:52:00 +02:00
|
|
|
def md5(filename):
|
2012-07-09 19:27:47 +02:00
|
|
|
''' Return MD5 hex digest of local file, or None if file is not present. '''
|
|
|
|
if not os.path.exists(filename):
|
|
|
|
return None
|
|
|
|
digest = _md5()
|
|
|
|
blocksize = 64 * 1024
|
|
|
|
infile = open(filename, 'rb')
|
|
|
|
block = infile.read(blocksize)
|
|
|
|
while block:
|
|
|
|
digest.update(block)
|
|
|
|
block = infile.read(blocksize)
|
|
|
|
infile.close()
|
|
|
|
return digest.hexdigest()
|
|
|
|
|
2012-07-07 14:45:06 +02:00
|
|
|
####################################################################
|
|
|
|
# option handling code for /usr/bin/ansible and ansible-playbook
|
|
|
|
# below this line
|
|
|
|
|
2012-04-10 19:51:58 +02:00
|
|
|
class SortedOptParser(optparse.OptionParser):
|
|
|
|
'''Optparser which sorts the options by opt before outputting --help'''
|
|
|
|
def format_help(self, formatter=None):
|
2012-07-15 14:46:58 +02:00
|
|
|
self.option_list.sort(key=operator.methodcaller('get_opt_string'))
|
2012-04-10 19:51:58 +02:00
|
|
|
return optparse.OptionParser.format_help(self, formatter=None)
|
|
|
|
|
2012-04-17 04:15:55 +02:00
|
|
|
def base_parser(constants=C, usage="", output_opts=False, runas_opts=False, async_opts=False, connect_opts=False):
|
2012-04-10 19:51:58 +02:00
|
|
|
''' create an options parser for any ansible script '''
|
|
|
|
|
|
|
|
parser = SortedOptParser(usage)
|
2012-06-20 03:55:57 +02:00
|
|
|
parser.add_option('-v','--verbose', default=False, action="store_true",
|
|
|
|
help='verbose mode')
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-f','--forks', dest='forks', default=constants.DEFAULT_FORKS, type='int',
|
2012-04-13 03:30:49 +02:00
|
|
|
help="specify number of parallel processes to use (default=%s)" % constants.DEFAULT_FORKS)
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-i', '--inventory-file', dest='inventory',
|
2012-04-13 03:30:49 +02:00
|
|
|
help="specify inventory host file (default=%s)" % constants.DEFAULT_HOST_LIST,
|
|
|
|
default=constants.DEFAULT_HOST_LIST)
|
2012-04-14 01:06:11 +02:00
|
|
|
parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true',
|
2012-04-10 19:51:58 +02:00
|
|
|
help='ask for SSH password')
|
2012-05-14 22:14:38 +02:00
|
|
|
parser.add_option('--private-key', default=None, dest='private_key_file',
|
|
|
|
help='use this file to authenticate the connection')
|
2012-04-14 01:06:11 +02:00
|
|
|
parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true',
|
|
|
|
help='ask for sudo password')
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-M', '--module-path', dest='module_path',
|
2012-06-06 22:42:29 +02:00
|
|
|
help="specify path(s) to module library (default=%s)" % constants.DEFAULT_MODULE_PATH,
|
2012-04-13 03:30:49 +02:00
|
|
|
default=constants.DEFAULT_MODULE_PATH)
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-T', '--timeout', default=constants.DEFAULT_TIMEOUT, type='int',
|
2012-04-13 03:30:49 +02:00
|
|
|
dest='timeout',
|
|
|
|
help="override the SSH timeout in seconds (default=%s)" % constants.DEFAULT_TIMEOUT)
|
2012-04-14 01:33:19 +02:00
|
|
|
|
2012-04-05 23:06:23 +02:00
|
|
|
if output_opts:
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-o', '--one-line', dest='one_line', action='store_true',
|
|
|
|
help='condense output')
|
|
|
|
parser.add_option('-t', '--tree', dest='tree', default=None,
|
|
|
|
help='log output to this directory')
|
2012-04-05 23:06:23 +02:00
|
|
|
|
|
|
|
if runas_opts:
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option("-s", "--sudo", default=False, action="store_true",
|
|
|
|
dest='sudo', help="run operations with sudo (nopasswd)")
|
2012-05-07 17:37:50 +02:00
|
|
|
parser.add_option('-U', '--sudo-user', dest='sudo_user', help='desired sudo user (default=root)',
|
|
|
|
default=None) # Can't default to root because we need to detect when this option was given
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER,
|
2012-04-13 03:30:49 +02:00
|
|
|
dest='remote_user',
|
|
|
|
help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER)
|
2012-04-05 23:06:23 +02:00
|
|
|
|
2012-04-11 01:13:18 +02:00
|
|
|
if connect_opts:
|
2012-04-12 20:18:35 +02:00
|
|
|
parser.add_option('-c', '--connection', dest='connection',
|
|
|
|
choices=C.DEFAULT_TRANSPORT_OPTS,
|
|
|
|
default=C.DEFAULT_TRANSPORT,
|
2012-04-13 03:20:37 +02:00
|
|
|
help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT)
|
2012-04-11 01:13:18 +02:00
|
|
|
|
2012-04-05 23:06:23 +02:00
|
|
|
if async_opts:
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-P', '--poll', default=constants.DEFAULT_POLL_INTERVAL, type='int',
|
2012-04-13 03:30:49 +02:00
|
|
|
dest='poll_interval',
|
|
|
|
help="set the poll interval if using -B (default=%s)" % constants.DEFAULT_POLL_INTERVAL)
|
2012-04-10 19:51:58 +02:00
|
|
|
parser.add_option('-B', '--background', dest='seconds', type='int', default=0,
|
2012-04-13 03:30:49 +02:00
|
|
|
help='run asynchronously, failing after X seconds (default=N/A)')
|
2012-04-06 16:59:15 +02:00
|
|
|
|
2012-04-10 19:51:58 +02:00
|
|
|
return parser
|
2012-04-06 16:59:15 +02:00
|
|
|
|
2012-04-05 23:06:23 +02:00
|
|
|
|