Compare commits
147 Commits
stable-2.1
...
0.4
| Author | SHA1 | Date | |
|---|---|---|---|
| 9551afc061 | |||
| e03a724dc0 | |||
| 8babac4856 | |||
| 90c70d7c05 | |||
| 0844db4462 | |||
| 0de0a999ab | |||
| a8b494bab5 | |||
| 5dc05ef556 | |||
| d4cc8dc242 | |||
| 5672d56189 | |||
| 03a3d74954 | |||
| 5ab77b8239 | |||
| c6699ad557 | |||
| 8975fe5a8e | |||
| 4f70245eb6 | |||
| 4d08940223 | |||
| 3768095645 | |||
| fa9462d687 | |||
| 404c3acbbf | |||
| 87076e29e7 | |||
| 119d7cd8fd | |||
| d67f996f8d | |||
| f5c6457de8 | |||
| 622405c03d | |||
| 94d7ceb21a | |||
| 776fe43d12 | |||
| 5338fabf20 | |||
| a5dc23b537 | |||
| c33cba3746 | |||
| ada9033acd | |||
| 2ea7110c83 | |||
| f5bd60c87c | |||
| c8b298dc56 | |||
| 733677362d | |||
| 1864a480ba | |||
| d19588b00c | |||
| 454e74620b | |||
| 84995367a5 | |||
| 81b9240979 | |||
| b1da61ae92 | |||
| 4e65b537da | |||
| 5904682fdd | |||
| 03b887a53d | |||
| 38a03aef6b | |||
| 174e4c1340 | |||
| b8573ab7d1 | |||
| b90c2356c3 | |||
| 461ba57277 | |||
| f8244f3168 | |||
| c362a2e581 | |||
| 85438bf1c0 | |||
| 480614ee91 | |||
| 63bf10bab0 | |||
| 5e5b4a90dc | |||
| abb391f3fd | |||
| 277ff4f516 | |||
| 38ad3da63b | |||
| 64673cc932 | |||
| 0956aa96f4 | |||
| 2fae38fffb | |||
| 0b5b44858e | |||
| a5b13fe4ce | |||
| 6119988934 | |||
| e0317a35d0 | |||
| 7f6add670e | |||
| a7599954a3 | |||
| 53bde0bf51 | |||
| c7c38e9a61 | |||
| 55fbc95243 | |||
| 1dbea82350 | |||
| 1c652492e1 | |||
| 5506147033 | |||
| a07f69cd54 | |||
| 1cb278f50d | |||
| 8cb22cf858 | |||
| 37b394fd6e | |||
| 9b587d4458 | |||
| 1144a21668 | |||
| b89d8db7ce | |||
| efde61e537 | |||
| 5f8e2a3651 | |||
| 325b397ac0 | |||
| dd5f535925 | |||
| 5e84a05db9 | |||
| 0abca68998 | |||
| b2485850bf | |||
| 893bf90627 | |||
| a54d9f66e6 | |||
| 6c0511a2d0 | |||
| 1d28212f86 | |||
| 3b40158961 | |||
| b5f6558872 | |||
| f09ec78fbd | |||
| f2e8836c94 | |||
| a589ee4d15 | |||
| de00dacff9 | |||
| 95069b7ee3 | |||
| db65cf5a90 | |||
| 5d63c6b204 | |||
| 96c0ee0efc | |||
| 42b55a07cd | |||
| f41fb90d78 | |||
| 6a4e8d7f4c | |||
| 472395bd77 | |||
| d6e56dee87 | |||
| 66ba6b023c | |||
| 4694c3fbba | |||
| a1ed9fc546 | |||
| abcfdbeeaf | |||
| 4d623d0356 | |||
| 98dda72be1 | |||
| cbbd9d8f3a | |||
| 85a04a2517 | |||
| a7b9bf958d | |||
| 46c661b3e3 | |||
| c804752835 | |||
| 3fb2d38514 | |||
| d9bec842ef | |||
| 4011d15faa | |||
| 958832fb1f | |||
| 23c6a0985c | |||
| 2c416b8f06 | |||
| 81b8190fc5 | |||
| aec8995fd9 | |||
| 00ea71d8de | |||
| 6be85f4fc5 | |||
| 84c9caa805 | |||
| 23ff967f38 | |||
| 672794f586 | |||
| 3803b27f6c | |||
| bcd713a9f3 | |||
| 8ec60e0b4e | |||
| 3eb00ec1e7 | |||
| 2b7828e118 | |||
| 192c0c641c | |||
| 12873b9bb6 | |||
| d6bbf288cd | |||
| fc61141ebf | |||
| 572868c9e1 | |||
| 9ad4e7d149 | |||
| 5fe677645d | |||
| 52efc90326 | |||
| cbbaee8a9f | |||
| f1b7149fcf | |||
| 887d293a3b | |||
| 40dbd9b3d7 | |||
| f9a14cfec1 |
60
CHANGELOG.md
60
CHANGELOG.md
@ -1,20 +1,60 @@
|
||||
Ansible Changes By Release
|
||||
==========================
|
||||
|
||||
0.4 "Unchained" ------- in progress, ETA May 2012
|
||||
0.4 "Unchained" ------- May 23, 2012
|
||||
|
||||
* custom facts provided by the setup module mean no dependency on Ruby, facter, or ohai
|
||||
Internals/Core
|
||||
* internal inventory API now more object oriented, parsers decoupled
|
||||
* async handling improvements
|
||||
* misc fixes for running ansible on OS X (overlord only)
|
||||
* sudo improvements, now works much more smoothly
|
||||
* some support for reading some default settings from the ssh config file (key pairs, ports)
|
||||
* OS X support in progress for ansible on the host and clients (modules still TBA)
|
||||
* sudo to a particular user with -U/--sudo-user, or using 'sudo_user: foo' in a playbook
|
||||
* --private-key CLI option to work with pem files
|
||||
|
||||
Inventory
|
||||
* can use -i host1,host2,host3:port to specify hosts not in inventory (replaces --override-hosts)
|
||||
* ansible INI style format can do groups of groups [groupname:children] and group vars [groupname:vars]
|
||||
* groups and users module takes an optional system=yes|no on creation (default no)
|
||||
* list of hosts in playbooks can be expressed as a YAML list in addition to ; delimited
|
||||
* tweaks to SELinux implementation for file module
|
||||
* first_available_file feature, see selective_file_sources.yml in examples/playbooks for info
|
||||
* fixes for yum module corner cases on EL5
|
||||
* --extra-vars="a=2 b=3" etc, now available to inject parameters into playbooks from CLI
|
||||
* file module now correctly returns the mode in octal
|
||||
* modules can no longer include stderr output (paramiko limitation from sudo)
|
||||
|
||||
Playbooks
|
||||
* variables can be replaced like ${foo.nested_hash_key.nested_subkey[array_index]}
|
||||
* unicode now ok in templates (assumes utf8)
|
||||
* able to pass host specifier or group name in to "hosts:" with --extra-vars
|
||||
* ansible-pull script and example playbook (extreme scaling, remediation)
|
||||
* inventory_hostname variable available that contains the value of the host as ansible knows it
|
||||
* variables in the 'all' section can be used to define other variables based on those values
|
||||
* 'group_names' is now a variable made available to templates
|
||||
* first_available_file feature, see selective_file_sources.yml in examples/playbooks for info
|
||||
* --extra-vars="a=2 b=3" etc, now available to inject parameters into playbooks from CLI
|
||||
|
||||
Incompatible Changes
|
||||
* jinja2 is only usable in templates, not playbooks, use $foo instead
|
||||
* --override-hosts removed, can use -i with comma notation (-i "ahost,bhost")
|
||||
* modules can no longer include stderr output (paramiko limitation from sudo)
|
||||
|
||||
Module Changes
|
||||
* tweaks to SELinux implementation for file module
|
||||
* fixes for yum module corner cases on EL5
|
||||
* file module now correctly returns the mode in octal
|
||||
* fix for symlink handling in the file module
|
||||
* service takes an enable=yes|no which works with chkconfig or updates-rc.d as appropriate
|
||||
* service module works better on Ubuntu
|
||||
* git module now does resets and such to work more smoothly on updates
|
||||
* modules all now log to syslog
|
||||
* enabled=yes|no on a service can be used to toggle chkconfig & updates-rc.d states
|
||||
* git module supports branch=
|
||||
* service fixes to better detect status using return codes of the service script
|
||||
* custom facts provided by the setup module mean no dependency on Ruby, facter, or ohai
|
||||
* service now has a state=reloaded
|
||||
* raw module for bootstrapping and talking to routers w/o Python, etc
|
||||
|
||||
Misc Bugfixes
|
||||
* fixes for variable parsing in only_if lines
|
||||
* misc fixes to key=value parsing
|
||||
* variables with mixed case now legal
|
||||
* fix to internals of hacking/test-module development script
|
||||
|
||||
|
||||
0.3 "Baluchitherium" -- April 23, 2012
|
||||
|
||||
|
||||
17
bin/ansible
17
bin/ansible
@ -22,7 +22,7 @@
|
||||
import sys
|
||||
import getpass
|
||||
|
||||
import ansible.runner
|
||||
from ansible.runner import Runner
|
||||
import ansible.constants as C
|
||||
from ansible import utils
|
||||
from ansible import errors
|
||||
@ -52,7 +52,6 @@ class Cli(object):
|
||||
parser.add_option('-m', '--module-name', dest='module_name',
|
||||
help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME,
|
||||
default=C.DEFAULT_MODULE_NAME)
|
||||
|
||||
options, args = parser.parse_args()
|
||||
self.callbacks.options = options
|
||||
|
||||
@ -71,8 +70,8 @@ class Cli(object):
|
||||
inventory_manager = inventory.Inventory(options.inventory)
|
||||
hosts = inventory_manager.list_hosts(pattern)
|
||||
if len(hosts) == 0:
|
||||
print >>sys.stderr, "No hosts matched"
|
||||
sys.exit(1)
|
||||
print >>sys.stderr, "No hosts matched"
|
||||
sys.exit(1)
|
||||
|
||||
sshpass = None
|
||||
sudopass = None
|
||||
@ -80,19 +79,23 @@ class Cli(object):
|
||||
sshpass = getpass.getpass(prompt="SSH password: ")
|
||||
if options.ask_sudo_pass:
|
||||
sudopass = getpass.getpass(prompt="sudo password: ")
|
||||
|
||||
options.sudo = True
|
||||
if options.sudo_user:
|
||||
options.sudo = True
|
||||
options.sudo_user = options.sudo_user or C.DEFAULT_SUDO_USER
|
||||
if options.tree:
|
||||
utils.prepare_writeable_dir(options.tree)
|
||||
|
||||
runner = ansible.runner.Runner(
|
||||
runner = Runner(
|
||||
module_name=options.module_name, module_path=options.module_path,
|
||||
module_args=options.module_args,
|
||||
remote_user=options.remote_user, remote_pass=sshpass,
|
||||
inventory=inventory_manager, timeout=options.timeout,
|
||||
private_key_file=options.private_key_file,
|
||||
forks=options.forks,
|
||||
pattern=pattern,
|
||||
callbacks=self.callbacks, sudo=options.sudo,
|
||||
sudo_pass=sudopass,
|
||||
sudo_pass=sudopass,sudo_user=options.sudo_user,
|
||||
transport=options.connection, debug=options.debug
|
||||
)
|
||||
|
||||
|
||||
@ -33,8 +33,6 @@ def main(args):
|
||||
# create parser for CLI options
|
||||
usage = "%prog playbook.yml"
|
||||
parser = utils.base_parser(constants=C, usage=usage, connect_opts=True, runas_opts=True)
|
||||
parser.add_option('-O', '--override-hosts', dest="override_hosts", default=None,
|
||||
help="run playbook against these hosts regardless of inventory settings")
|
||||
parser.add_option('-e', '--extra-vars', dest="extra_vars", default=None,
|
||||
help="set additional key=value variables from the CLI")
|
||||
|
||||
@ -50,9 +48,10 @@ def main(args):
|
||||
sshpass = getpass.getpass(prompt="SSH password: ")
|
||||
if options.ask_sudo_pass:
|
||||
sudopass = getpass.getpass(prompt="sudo password: ")
|
||||
override_hosts = None
|
||||
if options.override_hosts:
|
||||
override_hosts = options.override_hosts.split(",")
|
||||
options.sudo = True
|
||||
if options.sudo_user:
|
||||
options.sudo = True
|
||||
options.sudo_user = options.sudo_user or C.DEFAULT_SUDO_USER
|
||||
extra_vars = utils.parse_kv(options.extra_vars)
|
||||
|
||||
# run all playbooks specified on the command line
|
||||
@ -66,7 +65,6 @@ def main(args):
|
||||
playbook=playbook,
|
||||
module_path=options.module_path,
|
||||
host_list=options.inventory,
|
||||
override_hosts=override_hosts,
|
||||
forks=options.forks,
|
||||
debug=options.debug,
|
||||
remote_user=options.remote_user,
|
||||
@ -77,8 +75,10 @@ def main(args):
|
||||
timeout=options.timeout,
|
||||
transport=options.connection,
|
||||
sudo=options.sudo,
|
||||
sudo_user=options.sudo_user,
|
||||
sudo_pass=sudopass,
|
||||
extra_vars=extra_vars
|
||||
extra_vars=extra_vars,
|
||||
private_key_file=options.private_key_file
|
||||
)
|
||||
try:
|
||||
|
||||
|
||||
75
bin/ansible-pull
Executable file
75
bin/ansible-pull
Executable file
@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# ansible-pull is a script that runs ansible in local mode
|
||||
# after checking out a playbooks directory from git. There is an
|
||||
# example playbook to bootstrap this script in the examples/ dir which
|
||||
# installs ansible and sets it up to run on cron.
|
||||
#
|
||||
# usage:
|
||||
# ansible-pull -d /var/ansible/local -U http://wherever/content.git -C production
|
||||
#
|
||||
# the git repo must contain a playbook named 'local.yml'
|
||||
|
||||
# (c) 2012, Stephen Fromm <sfromm@gmail.com>
|
||||
#
|
||||
# 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/>.
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from optparse import OptionParser
|
||||
|
||||
DEFAULT_PLAYBOOK = 'local.yml'
|
||||
|
||||
def _run(cmd):
|
||||
cmd = subprocess.Popen(cmd, shell=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(out, err) = cmd.communicate()
|
||||
print out
|
||||
if cmd.returncode != 0:
|
||||
print err
|
||||
return cmd.returncode
|
||||
|
||||
def main(args):
|
||||
""" Set up and run a local playbook """
|
||||
usage = "%prog [options]"
|
||||
parser = OptionParser()
|
||||
parser.add_option('-d', '--directory', dest='dest', default=None,
|
||||
help='Directory to checkout git repository')
|
||||
parser.add_option('-U', '--url', dest='url',
|
||||
default=None,
|
||||
help='URL of git repository')
|
||||
parser.add_option('-C', '--checkout', dest='checkout',
|
||||
default="HEAD",
|
||||
help='Branch/Tag/Commit to checkout. Defaults to HEAD.')
|
||||
options, args = parser.parse_args(args)
|
||||
|
||||
git_opts = "repo=%s dest=%s version=%s" % (options.url, options.dest, options.checkout)
|
||||
cmd = 'ansible all -c local -m git -a "%s"' % git_opts
|
||||
print "cmd=%s" % cmd
|
||||
rc = _run(cmd)
|
||||
if rc != 0:
|
||||
return rc
|
||||
|
||||
os.chdir(options.dest)
|
||||
cmd = 'ansible-playbook -c local %s' % DEFAULT_PLAYBOOK
|
||||
rc = _run(cmd)
|
||||
return rc
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
except KeyboardInterrupt, e:
|
||||
print >>sys.stderr, "Exit on user request.\n"
|
||||
sys.exit(1)
|
||||
@ -71,12 +71,6 @@ Prompt for the password to use for playbook plays that request sudo access, if a
|
||||
Connection timeout to use when trying to talk to hosts, in 'SECONDS'.
|
||||
|
||||
|
||||
*-O* 'OVERRIDE_HOSTS', *--override-hosts=*'OVERRIDE_HOSTS'::
|
||||
|
||||
Ignore the inventory file and run the playbook against only these hosts. "hosts:" line
|
||||
in playbook should be set to 'all' when using this option.
|
||||
|
||||
|
||||
*-s*, *--sudo*::
|
||||
|
||||
Force all plays to use sudo, even if not marked as such.
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
.\" Title: ansible
|
||||
.\" Author: [see the "AUTHOR" section]
|
||||
.\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
|
||||
.\" Date: 04/26/2012
|
||||
.\" Date: 05/06/2012
|
||||
.\" Manual: System administration commands
|
||||
.\" Source: Ansible 0.4
|
||||
.\" Language: English
|
||||
.\"
|
||||
.TH "ANSIBLE" "1" "04/26/2012" "Ansible 0\&.4" "System administration commands"
|
||||
.TH "ANSIBLE" "1" "05/06/2012" "Ansible 0\&.4" "System administration commands"
|
||||
.\" -----------------------------------------------------------------
|
||||
.\" * set default formatting
|
||||
.\" -----------------------------------------------------------------
|
||||
@ -72,7 +72,7 @@ to pass to the module\&.
|
||||
.PP
|
||||
\fB\-D\fR, \fB\-\-debug\fR
|
||||
.RS 4
|
||||
Print any messages the remote module sends to standard error to the console
|
||||
Debug mode
|
||||
.RE
|
||||
.PP
|
||||
\fB\-k\fR, \fB\-\-ask\-pass\fR
|
||||
@ -129,6 +129,13 @@ Use this remote
|
||||
instead of root\&.
|
||||
.RE
|
||||
.PP
|
||||
\fB\-U\fR \fISUDO_USERNAME\fR, \fB\-\-sudo\-user=\fR\fISUDO_USERNAME\fR
|
||||
.RS 4
|
||||
Sudo to
|
||||
\fISUDO_USERNAME\fR
|
||||
instead of root\&. Implies \-\-sudo\&.
|
||||
.RE
|
||||
.PP
|
||||
\fB\-c\fR \fICONNECTION\fR, \fB\-\-connection=\fR\fICONNECTION\fR
|
||||
.RS 4
|
||||
Connection type to use\&. Possible options are
|
||||
|
||||
@ -101,6 +101,10 @@ Poll a background job every 'NUM' seconds. Requires *-B*.
|
||||
|
||||
Use this remote 'USERNAME' instead of root.
|
||||
|
||||
*-U* 'SUDO_USERNAME', *--sudo-user=*'SUDO_USERNAME'::
|
||||
|
||||
Sudo to 'SUDO_USERNAME' instead of root. Implies --sudo.
|
||||
|
||||
*-c* 'CONNECTION', *--connection=*'CONNECTION'::
|
||||
|
||||
Connection type to use. Possible options are 'paramiko' (SSH) and 'local'.
|
||||
|
||||
51
examples/playbooks/ansible_pull.yml
Normal file
51
examples/playbooks/ansible_pull.yml
Normal file
@ -0,0 +1,51 @@
|
||||
# ansibple-pull setup
|
||||
#
|
||||
# on remote hosts, set up ansible to run periodically using the latest code
|
||||
# from a particular checkout, in pull based fashion, inverting Ansible's
|
||||
# usual push-based operating mode.
|
||||
#
|
||||
# This particular pull based mode is ideal for:
|
||||
#
|
||||
# (A) massive scale out
|
||||
# (B) continual system remediation
|
||||
#
|
||||
# DO NOT RUN THIS AGAINST YOUR HOSTS WITHOUT CHANGING THE repo_url
|
||||
# TO SOMETHING YOU HAVE PERSONALLY VERIFIED
|
||||
#
|
||||
#
|
||||
---
|
||||
|
||||
- hosts: pull_mode_hosts
|
||||
user: root
|
||||
|
||||
vars:
|
||||
|
||||
# schdule is fed directly to cron
|
||||
schedule: '*/15 * * * *'
|
||||
|
||||
# User to run ansible-pull as from cron
|
||||
cron_user: root
|
||||
|
||||
# Directory to where repository will be cloned
|
||||
workdir: /var/lib/ansible/local
|
||||
|
||||
# Repository to check out -- YOU MUST CHANGE THIS
|
||||
# repo must contain a local.yml file at top level
|
||||
#repo_url: git://github.com/sfromm/ansible-playbooks.git
|
||||
repo_url: SUPPLY_YOUR_OWN_GIT_URL_HERE
|
||||
|
||||
tasks:
|
||||
|
||||
- name: Install ansible
|
||||
action: yum pkg=ansible state=installed
|
||||
|
||||
- name: Create local directory to work from
|
||||
action: file path=$workdir state=directory owner=root group=root mode=0751
|
||||
|
||||
- name: Copy ansible inventory file to client
|
||||
action: copy src=/etc/ansible/hosts dest=/etc/ansible/hosts
|
||||
owner=root group=root mode=0644
|
||||
|
||||
- name: Create crontab entry to clone/pull git repository
|
||||
action: template src=templates/ansible-pull.j2 dest=/etc/cron.d/ansible-pull owner=root group=root mode=0644
|
||||
|
||||
@ -34,7 +34,7 @@
|
||||
|
||||
# we could also have done something like:
|
||||
# - include: wordpress.yml user=timmy
|
||||
# and had access to the template variable {{ user }} in the
|
||||
# and had access to the template variable $user in the
|
||||
# included file, if we wanted to. Variables from vars
|
||||
# and vars_files are also available inside include files
|
||||
|
||||
|
||||
@ -13,13 +13,13 @@
|
||||
first_available_file:
|
||||
|
||||
# first see if we have a file for this specific host
|
||||
- /srv/whatever/{{ ansible_hostname }}.conf
|
||||
- /srv/whatever/${ansible_hostname}.conf
|
||||
|
||||
# next try to load something like CentOS6.2.conf
|
||||
- /srv/whatever/{{ ansible_distribution }}{{ ansible_distribution_version }}.conf
|
||||
- /srv/whatever/${ansible_distribution}${ansible_distribution_version}.conf
|
||||
|
||||
# next see if there's a CentOS.conf
|
||||
- /srv/whatever/{{ ansible_distribution }}.conf
|
||||
- /srv/whatever/${ansible_distribution}.conf
|
||||
|
||||
# finally give up and just use something generic
|
||||
- /srv/whatever/default
|
||||
|
||||
2
examples/playbooks/templates/ansible-pull.j2
Normal file
2
examples/playbooks/templates/ansible-pull.j2
Normal file
@ -0,0 +1,2 @@
|
||||
# Cron job to git clone/pull a repo and then run locally
|
||||
{{ schedule }} {{ cron_user }} ansible-pull -d {{ workdir }} -U {{ repo_url }} >/var/log/ansible-pull.log 2>&1
|
||||
@ -49,7 +49,7 @@ if len(sys.argv) > 1:
|
||||
else:
|
||||
args = ""
|
||||
|
||||
argspath = os.path.expanduser("/.ansible_test_module_arguments")
|
||||
argspath = os.path.expanduser("~/.ansible_test_module_arguments")
|
||||
argsfile = open(argspath, 'w')
|
||||
argsfile.write(args)
|
||||
argsfile.close()
|
||||
|
||||
@ -44,10 +44,10 @@ class Connection(object):
|
||||
|
||||
_LOCALHOSTRE = re.compile(r"^(127.0.0.1|localhost|%s)$" % os.uname()[1])
|
||||
|
||||
def __init__(self, runner, transport):
|
||||
def __init__(self, runner, transport,sudo_user):
|
||||
self.runner = runner
|
||||
self.transport = transport
|
||||
|
||||
self.sudo_user = sudo_user
|
||||
def connect(self, host, port=None):
|
||||
conn = None
|
||||
if self.transport == 'local' and self._LOCALHOSTRE.search(host):
|
||||
@ -76,27 +76,7 @@ class ParamikoConnection(object):
|
||||
self.port = self.runner.remote_port
|
||||
|
||||
def _get_conn(self):
|
||||
credentials = {}
|
||||
user = self.runner.remote_user
|
||||
keypair = None
|
||||
|
||||
# Read file ~/.ssh/config, get data hostname, keyfile, port, etc
|
||||
# This will *NOT* overrides the ansible username and hostname " , getting the port and keyfile only.
|
||||
|
||||
try:
|
||||
ssh_config = paramiko.SSHConfig()
|
||||
config_file = ('~/.ssh/config')
|
||||
if os.path.exists(os.path.expanduser(config_file)):
|
||||
ssh_config.parse(open(os.path.expanduser(config_file)))
|
||||
credentials = ssh_config.lookup(self.host)
|
||||
|
||||
except IOError,e:
|
||||
raise errors.AnsibleConnectionFailed(str(e))
|
||||
|
||||
if 'port' in credentials:
|
||||
self.port = int(credentials['port'])
|
||||
if 'identityfile' in credentials:
|
||||
keypair = os.path.expanduser(credentials['identityfile'])
|
||||
|
||||
ssh = paramiko.SSHClient()
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
@ -107,8 +87,8 @@ class ParamikoConnection(object):
|
||||
username=user,
|
||||
allow_agent=True,
|
||||
look_for_keys=True,
|
||||
key_filename=self.runner.private_key_file,
|
||||
password=self.runner.remote_pass,
|
||||
key_filename=keypair,
|
||||
timeout=self.runner.timeout,
|
||||
port=self.port
|
||||
)
|
||||
@ -126,20 +106,12 @@ class ParamikoConnection(object):
|
||||
self.ssh = self._get_conn()
|
||||
return self
|
||||
|
||||
def exec_command(self, cmd, tmp_path, sudoable=False):
|
||||
def exec_command(self, cmd, tmp_path,sudo_user,sudoable=False):
|
||||
|
||||
''' run a command on the remote host '''
|
||||
|
||||
bufsize = 4096
|
||||
# reusing runner's TCP connect timeout as command progress timeout (correct?)
|
||||
timeout_secs = self.runner.timeout
|
||||
chan = self.ssh.get_transport().open_session()
|
||||
chan.settimeout(timeout_secs)
|
||||
stdin = chan.makefile('wb', bufsize)
|
||||
stdout = chan.makefile('rb', bufsize)
|
||||
stderr = chan.makefile_stderr('rb', bufsize)
|
||||
chan.get_pty()
|
||||
chan.set_combine_stderr(False)
|
||||
|
||||
if not self.runner.sudo or not sudoable:
|
||||
quoted_command = '"$SHELL" -c ' + pipes.quote(cmd)
|
||||
@ -150,11 +122,13 @@ class ParamikoConnection(object):
|
||||
# tells sudo that this is the end of sudo options and the command
|
||||
# follows. Passing a quoted compound command to sudo (or sudo -s)
|
||||
# directly doesn't work, so we shellquote it with pipes.quote()
|
||||
# and pass the quoted string to the user's shell.
|
||||
|
||||
# and pass the quoted string to the user's shell. We loop reading
|
||||
# output until we see the randomly-generated sudo prompt set with
|
||||
# the -p option.
|
||||
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
|
||||
prompt = '[sudo via ansible, key=%s] password: ' % randbits
|
||||
sudocmd = 'sudo -k -p "%s" -- "$SHELL" -c %s' % (prompt, pipes.quote(cmd))
|
||||
sudocmd = 'sudo -k -p "%s" -u %s -- "$SHELL" -c %s' % (prompt,
|
||||
sudo_user, pipes.quote(cmd))
|
||||
sudo_output = ''
|
||||
try:
|
||||
chan.exec_command(sudocmd)
|
||||
@ -170,7 +144,7 @@ class ParamikoConnection(object):
|
||||
|
||||
stdin = chan.makefile('wb', bufsize)
|
||||
stdout = chan.makefile('rb', bufsize)
|
||||
stderr = chan.makefile_stderr('rb', bufsize)
|
||||
stderr = '' # stderr goes to stdout when using a pty, so this will never output anything.
|
||||
return stdin, stdout, stderr
|
||||
|
||||
def put_file(self, in_path, out_path):
|
||||
@ -214,7 +188,7 @@ class LocalConnection(object):
|
||||
|
||||
return self
|
||||
|
||||
def exec_command(self, cmd, tmp_path, sudoable=False):
|
||||
def exec_command(self, cmd, tmp_path,sudo_user,sudoable=False):
|
||||
''' run a command on the local host '''
|
||||
if self.runner.sudo and sudoable:
|
||||
cmd = "sudo -s %s" % cmd
|
||||
|
||||
@ -23,6 +23,8 @@ DEFAULT_HOST_LIST = os.environ.get('ANSIBLE_HOSTS',
|
||||
'/etc/ansible/hosts')
|
||||
DEFAULT_MODULE_PATH = os.environ.get('ANSIBLE_LIBRARY',
|
||||
'/usr/share/ansible')
|
||||
DEFAULT_REMOTE_TMP = os.environ.get('ANSIBLE_REMOTE_TMP',
|
||||
'/$HOME/.ansible/tmp')
|
||||
|
||||
DEFAULT_MODULE_NAME = 'command'
|
||||
DEFAULT_PATTERN = '*'
|
||||
@ -32,7 +34,9 @@ DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_POLL_INTERVAL = 15
|
||||
DEFAULT_REMOTE_USER = 'root'
|
||||
DEFAULT_REMOTE_PASS = None
|
||||
DEFAULT_PRIVATE_KEY_FILE = None
|
||||
DEFAULT_SUDO_PASS = None
|
||||
DEFAULT_SUDO_USER = 'root'
|
||||
DEFAULT_REMOTE_PORT = 22
|
||||
DEFAULT_TRANSPORT = 'paramiko'
|
||||
DEFAULT_TRANSPORT_OPTS = ['local', 'paramiko']
|
||||
|
||||
76
lib/ansible/group.py
Normal file
76
lib/ansible/group.py
Normal file
@ -0,0 +1,76 @@
|
||||
# (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/>.
|
||||
|
||||
#############################################
|
||||
|
||||
# from ansible import errors
|
||||
|
||||
class Group(object):
|
||||
"""
|
||||
Group of ansible hosts
|
||||
"""
|
||||
|
||||
def __init__(self, name=None):
|
||||
self.name = name
|
||||
self.hosts = []
|
||||
self.vars = {}
|
||||
self.child_groups = []
|
||||
self.parent_groups = []
|
||||
if self.name is None:
|
||||
raise Exception("group name is required")
|
||||
|
||||
def add_child_group(self, group):
|
||||
if self == group:
|
||||
raise Exception("can't add group to itself")
|
||||
self.child_groups.append(group)
|
||||
group.parent_groups.append(self)
|
||||
|
||||
def add_host(self, host):
|
||||
self.hosts.append(host)
|
||||
host.add_group(self)
|
||||
|
||||
def set_variable(self, key, value):
|
||||
self.vars[key] = value
|
||||
|
||||
def get_hosts(self):
|
||||
hosts = []
|
||||
for kid in self.child_groups:
|
||||
hosts.extend(kid.get_hosts())
|
||||
hosts.extend(self.hosts)
|
||||
return hosts
|
||||
|
||||
def get_variables(self):
|
||||
vars = {}
|
||||
# FIXME: verify this variable override order is what we want
|
||||
for ancestor in self.get_ancestors():
|
||||
vars.update(ancestor.get_variables())
|
||||
vars.update(self.vars)
|
||||
return vars
|
||||
|
||||
def _get_ancestors(self):
|
||||
results = {}
|
||||
for g in self.parent_groups:
|
||||
results[g.name] = g
|
||||
results.update(g._get_ancestors())
|
||||
return results
|
||||
|
||||
def get_ancestors(self):
|
||||
return self._get_ancestors().values()
|
||||
|
||||
|
||||
|
||||
|
||||
62
lib/ansible/host.py
Normal file
62
lib/ansible/host.py
Normal file
@ -0,0 +1,62 @@
|
||||
# (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/>.
|
||||
|
||||
#############################################
|
||||
|
||||
from ansible import errors
|
||||
import ansible.constants as C
|
||||
|
||||
class Host(object):
|
||||
"""
|
||||
Group of ansible hosts
|
||||
"""
|
||||
|
||||
def __init__(self, name=None, port=None):
|
||||
self.name = name
|
||||
self.vars = {}
|
||||
self.groups = []
|
||||
if port and port != C.DEFAULT_REMOTE_PORT:
|
||||
self.set_variable('ansible_ssh_port', int(port))
|
||||
|
||||
if self.name is None:
|
||||
raise Exception("host name is required")
|
||||
|
||||
def add_group(self, group):
|
||||
self.groups.append(group)
|
||||
|
||||
def set_variable(self, key, value):
|
||||
self.vars[key]=value;
|
||||
|
||||
def get_groups(self):
|
||||
groups = {}
|
||||
for g in self.groups:
|
||||
groups[g.name] = g
|
||||
ancestors = g.get_ancestors()
|
||||
for a in ancestors:
|
||||
groups[a.name] = a
|
||||
return groups.values()
|
||||
|
||||
def get_variables(self):
|
||||
results = {}
|
||||
for group in self.groups:
|
||||
results.update(group.get_variables())
|
||||
results.update(self.vars)
|
||||
results['inventory_hostname'] = self.name
|
||||
groups = self.get_groups()
|
||||
results['group_names'] = sorted([ g.name for g in groups if g.name != 'all'])
|
||||
return results
|
||||
|
||||
@ -19,309 +19,146 @@
|
||||
|
||||
import fnmatch
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import constants as C
|
||||
import subprocess
|
||||
from ansible.inventory_parser import InventoryParser
|
||||
from ansible.inventory_parser_yaml import InventoryParserYaml
|
||||
from ansible.inventory_script import InventoryScript
|
||||
from ansible.group import Group
|
||||
from ansible.host import Host
|
||||
from ansible import errors
|
||||
from ansible import utils
|
||||
|
||||
class Inventory(object):
|
||||
""" Host inventory for ansible.
|
||||
|
||||
The inventory is either a simple text file with systems and [groups] of
|
||||
systems, or a script that will be called with --list or --host.
|
||||
"""
|
||||
Host inventory for ansible.
|
||||
"""
|
||||
|
||||
def __init__(self, host_list=C.DEFAULT_HOST_LIST, global_host_vars={}):
|
||||
def __init__(self, host_list=C.DEFAULT_HOST_LIST):
|
||||
|
||||
# the host file file, or script path, or list of hosts
|
||||
# if a list, inventory data will NOT be loaded
|
||||
self.host_list = host_list
|
||||
|
||||
# the inventory object holds a list of groups
|
||||
self.groups = []
|
||||
|
||||
# a list of host(names) to contain current inquiries to
|
||||
self._restriction = None
|
||||
self._variables = {}
|
||||
self._global_host_vars = global_host_vars # lets us pass in a global var list
|
||||
# that each host gets
|
||||
# after we have set up the inventory
|
||||
# to get all group variables
|
||||
|
||||
|
||||
# whether the inventory file is a script
|
||||
self._is_script = False
|
||||
|
||||
if type(host_list) in [ str, unicode ]:
|
||||
if host_list.find(",") != -1:
|
||||
host_list = host_list.split(",")
|
||||
|
||||
if type(host_list) == list:
|
||||
self.host_list = host_list
|
||||
self.groups = dict(ungrouped=host_list)
|
||||
self._is_script = False
|
||||
return
|
||||
|
||||
inventory_file = os.path.expanduser(host_list)
|
||||
if not os.path.exists(inventory_file):
|
||||
raise errors.AnsibleFileNotFound("inventory file not found: %s" % host_list)
|
||||
|
||||
self.inventory_file = os.path.abspath(inventory_file)
|
||||
|
||||
if os.access(self.inventory_file, os.X_OK):
|
||||
self.host_list, self.groups = self._parse_from_script()
|
||||
all = Group('all')
|
||||
self.groups = [ all ]
|
||||
for x in host_list:
|
||||
if x.find(":") != -1:
|
||||
tokens = x.split(":",1)
|
||||
all.add_host(Host(tokens[0], tokens[1]))
|
||||
else:
|
||||
all.add_host(Host(x))
|
||||
elif os.access(host_list, os.X_OK):
|
||||
self._is_script = True
|
||||
self.parser = InventoryScript(filename=host_list)
|
||||
self.groups = self.parser.groups.values()
|
||||
else:
|
||||
self.host_list, self.groups = self._parse_from_file()
|
||||
self._is_script = False
|
||||
data = file(host_list).read()
|
||||
if not data.startswith("---"):
|
||||
self.parser = InventoryParser(filename=host_list)
|
||||
self.groups = self.parser.groups.values()
|
||||
else:
|
||||
self.parser = InventoryParserYaml(filename=host_list)
|
||||
self.groups = self.parser.groups.values()
|
||||
|
||||
def _match(self, str, pattern_str):
|
||||
return fnmatch.fnmatch(str, pattern_str)
|
||||
|
||||
# *****************************************************
|
||||
# Public API
|
||||
def get_hosts(self, pattern="all"):
|
||||
""" Get all host objects matching the pattern """
|
||||
hosts = {}
|
||||
patterns = pattern.replace(";",":").split(":")
|
||||
|
||||
groups = self.get_groups()
|
||||
for group in groups:
|
||||
for host in group.get_hosts():
|
||||
for pat in patterns:
|
||||
if group.name == pat or pat == 'all' or self._match(host.name, pat):
|
||||
if not self._restriction:
|
||||
hosts[host.name] = host
|
||||
if self._restriction and host.name in self._restriction:
|
||||
hosts[host.name] = host
|
||||
return sorted(hosts.values(), key=lambda x: x.name)
|
||||
|
||||
def get_groups(self):
|
||||
return self.groups
|
||||
|
||||
def get_host(self, hostname):
|
||||
for group in self.groups:
|
||||
for host in group.get_hosts():
|
||||
if hostname == host.name:
|
||||
return host
|
||||
return None
|
||||
|
||||
def get_group(self, groupname):
|
||||
for group in self.groups:
|
||||
if group.name == groupname:
|
||||
return group
|
||||
return None
|
||||
|
||||
def get_group_variables(self, groupname):
|
||||
group = self.get_group(groupname)
|
||||
if group is None:
|
||||
raise Exception("group not found: %s" % groupname)
|
||||
return group.get_variables()
|
||||
|
||||
def get_variables(self, hostname):
|
||||
|
||||
if self._is_script:
|
||||
# TODO: move this to inventory_script.py
|
||||
host = self.get_host(hostname)
|
||||
cmd = subprocess.Popen(
|
||||
[self.host_list,"--host",hostname],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE
|
||||
)
|
||||
(out, err) = cmd.communicate()
|
||||
results = utils.parse_json(out)
|
||||
results['inventory_hostname'] = hostname
|
||||
groups = [ g.name for g in host.get_groups() if g.name != 'all' ]
|
||||
results['group_names'] = sorted(groups)
|
||||
return results
|
||||
|
||||
host = self.get_host(hostname)
|
||||
if host is None:
|
||||
raise Exception("host not found: %s" % hostname)
|
||||
return host.get_variables()
|
||||
|
||||
def add_group(self, group):
|
||||
self.groups.append(group)
|
||||
|
||||
def list_hosts(self, pattern="all"):
|
||||
""" Return a list of hosts [matching the pattern] """
|
||||
if self._restriction is None:
|
||||
host_list = self.host_list
|
||||
else:
|
||||
host_list = [ h for h in self.host_list if h in self._restriction ]
|
||||
return [ h for h in host_list if self._matches(h, pattern) ]
|
||||
return [ h.name for h in self.get_hosts(pattern) ]
|
||||
|
||||
def restrict_to(self, restriction):
|
||||
def list_groups(self):
|
||||
return [ g.name for g in self.groups ]
|
||||
|
||||
def get_restriction(self):
|
||||
return self._restriction
|
||||
|
||||
def restrict_to(self, restriction, append_missing=False):
|
||||
""" Restrict list operations to the hosts given in restriction """
|
||||
if type(restriction)!=list:
|
||||
restriction = [ restriction ]
|
||||
|
||||
self._restriction = restriction
|
||||
|
||||
if type(restriction) != list:
|
||||
restriction = [ restriction ]
|
||||
self._restriction = restriction
|
||||
|
||||
def lift_restriction(self):
|
||||
""" Do not restrict list operations """
|
||||
|
||||
self._restriction = None
|
||||
|
||||
def get_variables(self, host):
|
||||
""" Return the variables associated with this host. """
|
||||
|
||||
variables = {
|
||||
'inventory_hostname': host,
|
||||
}
|
||||
|
||||
if host in self._variables:
|
||||
variables.update(self._variables[host].copy())
|
||||
|
||||
if self._is_script:
|
||||
variables.update(self._get_variables_from_script(host))
|
||||
|
||||
variables['group_names'] = []
|
||||
for name,hosts in self.groups.iteritems():
|
||||
if host in hosts:
|
||||
variables['group_names'].append(name)
|
||||
|
||||
return variables
|
||||
|
||||
def get_global_vars(self):
|
||||
return self._global_host_vars
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _parse_from_file(self):
|
||||
''' parse a textual host file '''
|
||||
|
||||
results = []
|
||||
groups = dict(ungrouped=[])
|
||||
lines = file(self.inventory_file).read().split("\n")
|
||||
if "---" in lines:
|
||||
return self._parse_yaml()
|
||||
group_name = 'ungrouped'
|
||||
for item in lines:
|
||||
item = item.lstrip().rstrip()
|
||||
if item.startswith("#"):
|
||||
# ignore commented out lines
|
||||
pass
|
||||
elif item.startswith("["):
|
||||
# looks like a group
|
||||
group_name = item.replace("[","").replace("]","").lstrip().rstrip()
|
||||
groups[group_name] = []
|
||||
elif item != "":
|
||||
# looks like a regular host
|
||||
if ":" in item:
|
||||
# a port was specified
|
||||
item, port = item.split(":")
|
||||
try:
|
||||
port = int(port)
|
||||
except ValueError:
|
||||
raise errors.AnsibleError("SSH port for %s in inventory (%s) should be numerical."%(item, port))
|
||||
self._set_variable(item, "ansible_ssh_port", port)
|
||||
groups[group_name].append(item)
|
||||
if not item in results:
|
||||
results.append(item)
|
||||
return (results, groups)
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _parse_from_script(self):
|
||||
''' evaluate a script that returns list of hosts by groups '''
|
||||
|
||||
results = []
|
||||
groups = dict(ungrouped=[])
|
||||
|
||||
cmd = [self.inventory_file, '--list']
|
||||
|
||||
try:
|
||||
cmd = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
|
||||
out, err = cmd.communicate()
|
||||
except Exception, e:
|
||||
raise errors.AnsibleError("Failure executing %s to produce host list:\n %s" % (self.inventory_file, str(e)))
|
||||
|
||||
rc = cmd.returncode
|
||||
if rc:
|
||||
raise errors.AnsibleError("%s: %s" % self.inventory_file, err)
|
||||
|
||||
try:
|
||||
groups = utils.json_loads(out)
|
||||
except:
|
||||
raise errors.AnsibleError("invalid JSON response from script: %s" % self.inventory_file)
|
||||
|
||||
for (groupname, hostlist) in groups.iteritems():
|
||||
for host in hostlist:
|
||||
if host not in results:
|
||||
results.append(host)
|
||||
return (results, groups)
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _parse_yaml(self):
|
||||
""" Load the inventory from a yaml file.
|
||||
|
||||
returns hosts and groups"""
|
||||
data = utils.parse_yaml_from_file(self.inventory_file)
|
||||
|
||||
if type(data) != list:
|
||||
raise errors.AnsibleError("YAML inventory should be a list.")
|
||||
|
||||
hosts = []
|
||||
groups = {}
|
||||
ungrouped = []
|
||||
|
||||
|
||||
# go through once and grab up the global_host_vars from the 'all' group
|
||||
for item in data:
|
||||
if type(item) == dict:
|
||||
if "group" in item and 'all' == item["group"]:
|
||||
if "vars" in item:
|
||||
variables = item['vars']
|
||||
if type(variables) == list:
|
||||
for variable in variables:
|
||||
if len(variable) != 1:
|
||||
raise errors.AnsibleError("Only one item expected in %s"%(variable))
|
||||
k, v = variable.items()[0]
|
||||
self._global_host_vars[k] = utils.template(v, self._global_host_vars, {})
|
||||
elif type(variables) == dict:
|
||||
self._global_host_vars.update(variables)
|
||||
|
||||
for item in data:
|
||||
if type(item) == dict:
|
||||
if "group" in item:
|
||||
group_name = item["group"]
|
||||
|
||||
group_vars = []
|
||||
if "vars" in item:
|
||||
group_vars.extend(item["vars"])
|
||||
|
||||
group_hosts = []
|
||||
if "hosts" in item:
|
||||
for host in item["hosts"]:
|
||||
host_name = self._parse_yaml_host(host, group_vars)
|
||||
group_hosts.append(host_name)
|
||||
|
||||
groups[group_name] = group_hosts
|
||||
hosts.extend(group_hosts)
|
||||
|
||||
elif "host" in item:
|
||||
host_name = self._parse_yaml_host(item)
|
||||
hosts.append(host_name)
|
||||
ungrouped.append(host_name)
|
||||
else:
|
||||
host_name = self._parse_yaml_host(item)
|
||||
hosts.append(host_name)
|
||||
ungrouped.append(host_name)
|
||||
|
||||
# filter duplicate hosts
|
||||
output_hosts = []
|
||||
for host in hosts:
|
||||
if host not in output_hosts:
|
||||
output_hosts.append(host)
|
||||
|
||||
if len(ungrouped) > 0 :
|
||||
# hosts can be defined top-level, but also in a group
|
||||
really_ungrouped = []
|
||||
for host in ungrouped:
|
||||
already_grouped = False
|
||||
for name, group_hosts in groups.items():
|
||||
if host in group_hosts:
|
||||
already_grouped = True
|
||||
if not already_grouped:
|
||||
really_ungrouped.append(host)
|
||||
groups["ungrouped"] = really_ungrouped
|
||||
|
||||
return output_hosts, groups
|
||||
|
||||
def _parse_yaml_host(self, item, variables=[]):
|
||||
def set_variables(host, variables):
|
||||
if type(variables) == list:
|
||||
for variable in variables:
|
||||
if len(variable) != 1:
|
||||
raise errors.AnsibleError("Only one item expected in %s"%(variable))
|
||||
k, v = variable.items()[0]
|
||||
self._set_variable(host, k, v)
|
||||
elif type(variables) == dict:
|
||||
for k, v in variables.iteritems():
|
||||
self._set_variable(host, k, v)
|
||||
|
||||
|
||||
if type(item) in [str, unicode]:
|
||||
set_variables(item, variables)
|
||||
return item
|
||||
elif type(item) == dict:
|
||||
if "host" in item:
|
||||
host_name = item["host"]
|
||||
set_variables(host_name, variables)
|
||||
|
||||
if "vars" in item:
|
||||
set_variables(host_name, item["vars"])
|
||||
|
||||
return host_name
|
||||
else:
|
||||
raise errors.AnsibleError("Unknown item in inventory: %s"%(item))
|
||||
|
||||
|
||||
def _get_variables_from_script(self, host):
|
||||
''' support per system variabes from external variable scripts, see web docs '''
|
||||
|
||||
cmd = [self.inventory_file, '--host', host]
|
||||
|
||||
cmd = subprocess.Popen(cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
shell=False
|
||||
)
|
||||
out, err = cmd.communicate()
|
||||
|
||||
variables = {}
|
||||
try:
|
||||
variables = utils.json_loads(out)
|
||||
except:
|
||||
raise errors.AnsibleError("%s returned invalid result when called with hostname %s" % (
|
||||
self.inventory_file,
|
||||
host
|
||||
))
|
||||
return variables
|
||||
|
||||
def _set_variable(self, host, key, value):
|
||||
if not host in self._variables:
|
||||
self._variables[host] = {}
|
||||
self._variables[host][key] = value
|
||||
|
||||
def _matches(self, host_name, pattern):
|
||||
''' returns if a hostname is matched by the pattern '''
|
||||
|
||||
# a pattern is in fnmatch format but more than one pattern
|
||||
# can be strung together with semicolons. ex:
|
||||
# atlanta-web*.example.com;dc-web*.example.com
|
||||
|
||||
if host_name == '':
|
||||
return False
|
||||
pattern = pattern.replace(";",":")
|
||||
subpatterns = pattern.split(":")
|
||||
for subpattern in subpatterns:
|
||||
if subpattern == 'all':
|
||||
return True
|
||||
if fnmatch.fnmatch(host_name, subpattern):
|
||||
return True
|
||||
elif subpattern in self.groups:
|
||||
if host_name in self.groups[subpattern]:
|
||||
return True
|
||||
return False
|
||||
|
||||
151
lib/ansible/inventory_parser.py
Normal file
151
lib/ansible/inventory_parser.py
Normal file
@ -0,0 +1,151 @@
|
||||
# (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/>.
|
||||
|
||||
#############################################
|
||||
|
||||
import fnmatch
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import constants as C
|
||||
from ansible.host import Host
|
||||
from ansible.group import Group
|
||||
from ansible import errors
|
||||
from ansible import utils
|
||||
|
||||
class InventoryParser(object):
|
||||
"""
|
||||
Host inventory for ansible.
|
||||
"""
|
||||
|
||||
def __init__(self, filename=C.DEFAULT_HOST_LIST):
|
||||
|
||||
fh = open(filename)
|
||||
self.lines = fh.readlines()
|
||||
self.groups = {}
|
||||
self.hosts = {}
|
||||
self._parse()
|
||||
|
||||
def _parse(self):
|
||||
|
||||
self._parse_base_groups()
|
||||
self._parse_group_children()
|
||||
self._parse_group_variables()
|
||||
return self.groups
|
||||
|
||||
# [webservers]
|
||||
# alpha
|
||||
# beta:2345
|
||||
# gamma sudo=True user=root
|
||||
# delta asdf=jkl favcolor=red
|
||||
|
||||
def _parse_base_groups(self):
|
||||
|
||||
ungrouped = Group(name='ungrouped')
|
||||
all = Group(name='all')
|
||||
all.add_child_group(ungrouped)
|
||||
|
||||
self.groups = dict(all=all, ungrouped=ungrouped)
|
||||
active_group_name = 'ungrouped'
|
||||
|
||||
for line in self.lines:
|
||||
if line.startswith("["):
|
||||
active_group_name = line.replace("[","").replace("]","").strip()
|
||||
if line.find(":vars") != -1 or line.find(":children") != -1:
|
||||
active_group_name = None
|
||||
else:
|
||||
new_group = self.groups[active_group_name] = Group(name=active_group_name)
|
||||
all.add_child_group(new_group)
|
||||
elif line.startswith("#") or line == '':
|
||||
pass
|
||||
elif active_group_name:
|
||||
tokens = line.split()
|
||||
if len(tokens) == 0:
|
||||
continue
|
||||
hostname = tokens[0]
|
||||
port = C.DEFAULT_REMOTE_PORT
|
||||
if hostname.find(":") != -1:
|
||||
tokens2 = hostname.split(":")
|
||||
hostname = tokens2[0]
|
||||
port = tokens2[1]
|
||||
host = None
|
||||
if hostname in self.hosts:
|
||||
host = self.hosts[hostname]
|
||||
else:
|
||||
host = Host(name=hostname, port=port)
|
||||
self.hosts[hostname] = host
|
||||
if len(tokens) > 1:
|
||||
for t in tokens[1:]:
|
||||
(k,v) = t.split("=")
|
||||
host.set_variable(k,v)
|
||||
self.groups[active_group_name].add_host(host)
|
||||
|
||||
# [southeast:children]
|
||||
# atlanta
|
||||
# raleigh
|
||||
|
||||
def _parse_group_children(self):
|
||||
group = None
|
||||
|
||||
for line in self.lines:
|
||||
line = line.strip()
|
||||
if line is None or line == '':
|
||||
continue
|
||||
if line.startswith("[") and line.find(":children]") != -1:
|
||||
line = line.replace("[","").replace(":children]","")
|
||||
group = self.groups.get(line, None)
|
||||
if group is None:
|
||||
group = self.groups[line] = Group(name=line)
|
||||
elif line.startswith("#"):
|
||||
pass
|
||||
elif line.startswith("["):
|
||||
group = None
|
||||
elif group:
|
||||
kid_group = self.groups.get(line, None)
|
||||
if kid_group is None:
|
||||
raise errors.AnsibleError("child group is not defined: (%s)" % line)
|
||||
else:
|
||||
group.add_child_group(kid_group)
|
||||
|
||||
|
||||
# [webservers:vars]
|
||||
# http_port=1234
|
||||
# maxRequestsPerChild=200
|
||||
|
||||
def _parse_group_variables(self):
|
||||
group = None
|
||||
for line in self.lines:
|
||||
line = line.strip()
|
||||
if line.startswith("[") and line.find(":vars]") != -1:
|
||||
line = line.replace("[","").replace(":vars]","")
|
||||
group = self.groups.get(line, None)
|
||||
if group is None:
|
||||
raise errors.AnsibleError("can't add vars to undefined group: %s" % line)
|
||||
elif line.startswith("#"):
|
||||
pass
|
||||
elif line.startswith("["):
|
||||
group = None
|
||||
elif line == '':
|
||||
pass
|
||||
elif group:
|
||||
if line.find("=") == -1:
|
||||
raise errors.AnsibleError("variables assigned to group must be in key=value form")
|
||||
else:
|
||||
(k,v) = line.split("=")
|
||||
group.set_variable(k,v)
|
||||
|
||||
|
||||
108
lib/ansible/inventory_parser_yaml.py
Normal file
108
lib/ansible/inventory_parser_yaml.py
Normal file
@ -0,0 +1,108 @@
|
||||
# (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/>.
|
||||
|
||||
#############################################
|
||||
|
||||
import constants as C
|
||||
from ansible.host import Host
|
||||
from ansible.group import Group
|
||||
from ansible import errors
|
||||
from ansible import utils
|
||||
|
||||
class InventoryParserYaml(object):
|
||||
"""
|
||||
Host inventory for ansible.
|
||||
"""
|
||||
|
||||
def __init__(self, filename=C.DEFAULT_HOST_LIST):
|
||||
|
||||
fh = open(filename)
|
||||
data = fh.read()
|
||||
fh.close()
|
||||
self._hosts = {}
|
||||
self._parse(data)
|
||||
|
||||
def _make_host(self, hostname):
|
||||
if hostname in self._hosts:
|
||||
return self._hosts[hostname]
|
||||
else:
|
||||
host = Host(hostname)
|
||||
self._hosts[hostname] = host
|
||||
return host
|
||||
|
||||
# see file 'test/yaml_hosts' for syntax
|
||||
|
||||
def _parse(self, data):
|
||||
|
||||
all = Group('all')
|
||||
ungrouped = Group('ungrouped')
|
||||
all.add_child_group(ungrouped)
|
||||
|
||||
self.groups = dict(all=all, ungrouped=ungrouped)
|
||||
|
||||
yaml = utils.parse_yaml(data)
|
||||
for item in yaml:
|
||||
|
||||
if type(item) in [ str, unicode ]:
|
||||
host = self._make_host(item)
|
||||
ungrouped.add_host(host)
|
||||
|
||||
elif type(item) == dict and 'host' in item:
|
||||
host = self._make_host(item['host'])
|
||||
vars = item.get('vars', {})
|
||||
if type(vars)==list:
|
||||
varlist, vars = vars, {}
|
||||
for subitem in varlist:
|
||||
vars.update(subitem)
|
||||
for (k,v) in vars.items():
|
||||
host.set_variable(k,v)
|
||||
|
||||
elif type(item) == dict and 'group' in item:
|
||||
group = Group(item['group'])
|
||||
|
||||
for subresult in item.get('hosts',[]):
|
||||
|
||||
if type(subresult) in [ str, unicode ]:
|
||||
host = self._make_host(subresult)
|
||||
group.add_host(host)
|
||||
elif type(subresult) == dict:
|
||||
host = self._make_host(subresult['host'])
|
||||
vars = subresult.get('vars',{})
|
||||
if type(vars) == list:
|
||||
for subitem in vars:
|
||||
for (k,v) in subitem.items():
|
||||
host.set_variable(k,v)
|
||||
elif type(vars) == dict:
|
||||
for (k,v) in subresult.get('vars',{}).items():
|
||||
host.set_variable(k,v)
|
||||
else:
|
||||
raise errors.AnsibleError("unexpected type for variable")
|
||||
group.add_host(host)
|
||||
|
||||
vars = item.get('vars',{})
|
||||
if type(vars) == dict:
|
||||
for (k,v) in item.get('vars',{}).items():
|
||||
group.set_variable(k,v)
|
||||
elif type(vars) == list:
|
||||
for subitem in vars:
|
||||
if type(subitem) != dict:
|
||||
raise errors.AnsibleError("expected a dictionary")
|
||||
for (k,v) in subitem.items():
|
||||
group.set_variable(k,v)
|
||||
|
||||
self.groups[group.name] = group
|
||||
all.add_child_group(group)
|
||||
59
lib/ansible/inventory_script.py
Normal file
59
lib/ansible/inventory_script.py
Normal file
@ -0,0 +1,59 @@
|
||||
# (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/>.
|
||||
|
||||
#############################################
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import constants as C
|
||||
import os
|
||||
from ansible.host import Host
|
||||
from ansible.group import Group
|
||||
from ansible import errors
|
||||
from ansible import utils
|
||||
|
||||
class InventoryScript(object):
|
||||
"""
|
||||
Host inventory parser for ansible using external inventory scripts.
|
||||
"""
|
||||
|
||||
def __init__(self, filename=C.DEFAULT_HOST_LIST):
|
||||
|
||||
cmd = [ filename, "--list" ]
|
||||
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(stdout, stderr) = sp.communicate()
|
||||
self.data = stdout
|
||||
self.groups = self._parse()
|
||||
|
||||
def _parse(self):
|
||||
groups = {}
|
||||
self.raw = utils.parse_json(self.data)
|
||||
all=Group('all')
|
||||
self.groups = dict(all=all)
|
||||
group = None
|
||||
for (group_name, hosts) in self.raw.items():
|
||||
group = groups[group_name] = Group(group_name)
|
||||
host = None
|
||||
for hostname in hosts:
|
||||
host = Host(hostname)
|
||||
group.add_host(host)
|
||||
# FIXME: hack shouldn't be needed
|
||||
all.add_host(host)
|
||||
all.add_child_group(group)
|
||||
return groups
|
||||
|
||||
|
||||
@ -56,12 +56,13 @@ class PlayBook(object):
|
||||
sudo_pass = C.DEFAULT_SUDO_PASS,
|
||||
remote_port = C.DEFAULT_REMOTE_PORT,
|
||||
transport = C.DEFAULT_TRANSPORT,
|
||||
override_hosts = None,
|
||||
private_key_file = C.DEFAULT_PRIVATE_KEY_FILE,
|
||||
debug = False,
|
||||
callbacks = None,
|
||||
runner_callbacks = None,
|
||||
stats = None,
|
||||
sudo = False,
|
||||
sudo_user = C.DEFAULT_SUDO_USER,
|
||||
extra_vars = None):
|
||||
|
||||
"""
|
||||
@ -75,7 +76,6 @@ class PlayBook(object):
|
||||
sudo_pass: if sudo==True, and a password is required, this is the sudo password
|
||||
remote_port: default remote port to use if not specified with the host or play
|
||||
transport: how to connect to hosts that don't specify a transport (local, paramiko, etc)
|
||||
override_hosts: skip the inventory file, just talk to these hosts
|
||||
callbacks output callbacks for the playbook
|
||||
runner_callbacks: more callbacks, this time for the runner API
|
||||
stats: holds aggregrate data about events occuring to each host
|
||||
@ -98,22 +98,19 @@ class PlayBook(object):
|
||||
self.debug = debug
|
||||
self.callbacks = callbacks
|
||||
self.runner_callbacks = runner_callbacks
|
||||
self.override_hosts = override_hosts
|
||||
self.stats = stats
|
||||
self.sudo = sudo
|
||||
self.sudo_pass = sudo_pass
|
||||
self.sudo_user = sudo_user
|
||||
self.extra_vars = extra_vars
|
||||
self.global_vars = {}
|
||||
self.private_key_file = private_key_file
|
||||
|
||||
if override_hosts is not None:
|
||||
if type(override_hosts) != list:
|
||||
raise errors.AnsibleError("override hosts must be a list")
|
||||
self.global_vars.update(ansible.inventory.Inventory(host_list).get_global_vars())
|
||||
self.inventory = ansible.inventory.Inventory(override_hosts)
|
||||
self.inventory = ansible.inventory.Inventory(host_list)
|
||||
|
||||
|
||||
else:
|
||||
self.inventory = ansible.inventory.Inventory(host_list)
|
||||
self.global_vars.update(ansible.inventory.Inventory(host_list).get_global_vars())
|
||||
if not self.inventory._is_script:
|
||||
self.global_vars.update(self.inventory.get_group_variables('all'))
|
||||
|
||||
self.basedir = os.path.dirname(playbook)
|
||||
self.playbook = self._parse_playbook(playbook)
|
||||
@ -165,8 +162,7 @@ class PlayBook(object):
|
||||
include_vars[k] = v
|
||||
inject_vars = play_vars.copy()
|
||||
inject_vars.update(include_vars)
|
||||
included = utils.template_from_file(path, inject_vars, SETUP_CACHE)
|
||||
included = utils.parse_yaml(included)
|
||||
included = utils.parse_yaml_from_file(path)
|
||||
for x in included:
|
||||
if len(include_vars):
|
||||
x["vars"] = include_vars
|
||||
@ -176,9 +172,9 @@ class PlayBook(object):
|
||||
|
||||
def _include_handlers(self, play, handler, dirname, new_handlers):
|
||||
''' load handlers from external files '''
|
||||
|
||||
path = utils.path_dwim(dirname, handler['include'])
|
||||
inject_vars = self._get_vars(play, dirname)
|
||||
path = utils.template(handler['include'], inject_vars, SETUP_CACHE)
|
||||
path = utils.path_dwim(dirname, path)
|
||||
included = utils.template_from_file(path, inject_vars, SETUP_CACHE)
|
||||
included = utils.parse_yaml(included)
|
||||
for x in included:
|
||||
@ -274,7 +270,7 @@ class PlayBook(object):
|
||||
# *****************************************************
|
||||
|
||||
def _run_module(self, pattern, module, args, vars, remote_user,
|
||||
async_seconds, async_poll_interval, only_if, sudo, transport, port):
|
||||
async_seconds, async_poll_interval, only_if, sudo, sudo_user, transport, port):
|
||||
''' run a particular module step in a playbook '''
|
||||
|
||||
hosts = [ h for h in self.inventory.list_hosts() if (h not in self.stats.failures) and (h not in self.stats.dark)]
|
||||
@ -289,9 +285,10 @@ class PlayBook(object):
|
||||
remote_pass=self.remote_pass, module_path=self.module_path,
|
||||
timeout=self.timeout, remote_user=remote_user,
|
||||
remote_port=port, module_vars=vars,
|
||||
private_key_file=self.private_key_file,
|
||||
setup_cache=SETUP_CACHE, basedir=self.basedir,
|
||||
conditional=only_if, callbacks=self.runner_callbacks,
|
||||
debug=self.debug, sudo=sudo,
|
||||
debug=self.debug, sudo=sudo, sudo_user=sudo_user,
|
||||
transport=transport, sudo_pass=self.sudo_pass, is_playbook=True
|
||||
)
|
||||
|
||||
@ -311,7 +308,8 @@ class PlayBook(object):
|
||||
# *****************************************************
|
||||
|
||||
def _run_task(self, pattern=None, task=None,
|
||||
remote_user=None, handlers=None, conditional=False, sudo=False, transport=None, port=None):
|
||||
remote_user=None, handlers=None, conditional=False,
|
||||
sudo=False, sudo_user=None, transport=None, port=None):
|
||||
''' run a single task in the playbook and recursively run any subtasks. '''
|
||||
|
||||
# load the module name and parameters from the task entry
|
||||
@ -347,7 +345,7 @@ class PlayBook(object):
|
||||
# run the task in parallel
|
||||
results = self._run_module(pattern, module_name,
|
||||
module_args, module_vars, remote_user, async_seconds,
|
||||
async_poll_interval, only_if, sudo, transport, port)
|
||||
async_poll_interval, only_if, sudo, sudo_user, transport, port)
|
||||
|
||||
# add facts to the global setup cache
|
||||
for host, result in results['contacted'].iteritems():
|
||||
@ -368,6 +366,8 @@ class PlayBook(object):
|
||||
# we would only trigger restarting Apache on half of the nodes
|
||||
|
||||
subtasks = task.get('notify', [])
|
||||
if isinstance(subtasks, basestring):
|
||||
subtasks = [subtasks]
|
||||
if len(subtasks) > 0:
|
||||
for host, results in results.get('contacted',{}).iteritems():
|
||||
if results.get('changed', False):
|
||||
@ -403,19 +403,23 @@ class PlayBook(object):
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _do_conditional_imports(self, vars_files):
|
||||
def _do_conditional_imports(self, vars_files, pattern=None):
|
||||
''' handle the vars_files section, which can contain variables '''
|
||||
|
||||
|
||||
# FIXME: save parsed variable results in memory to avoid excessive re-reading/parsing
|
||||
# FIXME: currently parses imports for hosts not in the pattern, that is not wrong, but it's
|
||||
# not super optimized yet either, because we wouldn't have hit them, ergo
|
||||
# it will raise false errors if there is no defaults variable file without any $vars
|
||||
# in it, which could happen on uncontacted hosts.
|
||||
|
||||
|
||||
if type(vars_files) != list:
|
||||
raise errors.AnsibleError("vars_files must be a list")
|
||||
for host in self.inventory.list_hosts():
|
||||
cache_vars = SETUP_CACHE.get(host,{})
|
||||
|
||||
host_list = [ h for h in self.inventory.list_hosts(pattern)
|
||||
if not (h in self.stats.failures or h in self.stats.dark) ]
|
||||
|
||||
for host in host_list:
|
||||
cache_vars = SETUP_CACHE.get(host,{})
|
||||
SETUP_CACHE[host] = cache_vars
|
||||
for filename in vars_files:
|
||||
if type(filename) == list:
|
||||
@ -448,7 +452,7 @@ class PlayBook(object):
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _do_setup_step(self, pattern, vars, user, port, sudo, transport, vars_files=None):
|
||||
def _do_setup_step(self, pattern, vars, user, port, sudo, sudo_user, transport, vars_files=None):
|
||||
''' push variables down to the systems and get variables+facts back up '''
|
||||
|
||||
# this enables conditional includes like $facter_os.yml and is only done
|
||||
@ -457,12 +461,13 @@ class PlayBook(object):
|
||||
|
||||
if vars_files is not None:
|
||||
self.callbacks.on_setup_secondary()
|
||||
self._do_conditional_imports(vars_files)
|
||||
self._do_conditional_imports(vars_files, pattern)
|
||||
else:
|
||||
self.callbacks.on_setup_primary()
|
||||
|
||||
host_list = [ h for h in self.inventory.list_hosts(pattern)
|
||||
if not (h in self.stats.failures or h in self.stats.dark) ]
|
||||
|
||||
self.inventory.restrict_to(host_list)
|
||||
|
||||
# push any variables down to the system
|
||||
@ -472,9 +477,11 @@ class PlayBook(object):
|
||||
forks=self.forks, module_path=self.module_path,
|
||||
timeout=self.timeout, remote_user=user,
|
||||
remote_pass=self.remote_pass, remote_port=port,
|
||||
private_key_file=self.private_key_file,
|
||||
setup_cache=SETUP_CACHE,
|
||||
callbacks=self.runner_callbacks, sudo=sudo, debug=self.debug,
|
||||
transport=transport, sudo_pass=self.sudo_pass, is_playbook=True
|
||||
callbacks=self.runner_callbacks, sudo=sudo, sudo_user=sudo_user,
|
||||
debug=self.debug, transport=transport,
|
||||
sudo_pass=self.sudo_pass, is_playbook=True
|
||||
).run()
|
||||
self.stats.compute(setup_results, setup=True)
|
||||
|
||||
@ -495,14 +502,13 @@ class PlayBook(object):
|
||||
''' run a list of tasks for a given pattern, in order '''
|
||||
|
||||
# get configuration information about the pattern
|
||||
pattern = pg.get('hosts',None)
|
||||
name = pg.get('name', pattern)
|
||||
if isinstance(pattern, list):
|
||||
pattern = ';'.join(pattern)
|
||||
if self.override_hosts:
|
||||
pattern = 'all'
|
||||
pattern = pg.get('hosts')
|
||||
if pattern is None:
|
||||
raise errors.AnsibleError('hosts declaration is required')
|
||||
if isinstance(pattern, list):
|
||||
pattern = ';'.join(pattern)
|
||||
pattern = utils.template(pattern, self.extra_vars, {})
|
||||
name = pg.get('name', pattern)
|
||||
|
||||
vars = self._get_vars(pg, self.basedir)
|
||||
vars_files = pg.get('vars_files', {})
|
||||
@ -511,16 +517,21 @@ class PlayBook(object):
|
||||
user = pg.get('user', self.remote_user)
|
||||
port = pg.get('port', self.remote_port)
|
||||
sudo = pg.get('sudo', self.sudo)
|
||||
sudo_user = pg.get('sudo_user', self.sudo_user)
|
||||
transport = pg.get('connection', self.transport)
|
||||
|
||||
# the default sudo user is root, so if you change it, sudo is implied
|
||||
if sudo_user != 'root':
|
||||
sudo = True
|
||||
|
||||
self.callbacks.on_play_start(name)
|
||||
|
||||
# push any variables down to the system # and get facts/ohai/other data back up
|
||||
self._do_setup_step(pattern, vars, user, port, sudo, transport, None)
|
||||
self._do_setup_step(pattern, vars, user, port, sudo, sudo_user, transport, None)
|
||||
|
||||
# now with that data, handle contentional variable file imports!
|
||||
if len(vars_files) > 0:
|
||||
self._do_setup_step(pattern, vars, user, port, sudo, transport, vars_files)
|
||||
self._do_setup_step(pattern, vars, user, port, sudo, sudo_user, transport, vars_files)
|
||||
|
||||
# run all the top level tasks, these get run on every node
|
||||
for task in tasks:
|
||||
@ -530,6 +541,7 @@ class PlayBook(object):
|
||||
handlers=handlers,
|
||||
remote_user=user,
|
||||
sudo=sudo,
|
||||
sudo_user=sudo_user,
|
||||
transport=transport,
|
||||
port=port
|
||||
)
|
||||
@ -551,6 +563,7 @@ class PlayBook(object):
|
||||
conditional=True,
|
||||
remote_user=user,
|
||||
sudo=sudo,
|
||||
sudo_user=sudo_user,
|
||||
transport=transport,
|
||||
port=port
|
||||
)
|
||||
|
||||
@ -29,6 +29,7 @@ import tempfile
|
||||
import time
|
||||
import base64
|
||||
import getpass
|
||||
import codecs
|
||||
|
||||
import ansible.constants as C
|
||||
import ansible.connection
|
||||
@ -75,10 +76,11 @@ class Runner(object):
|
||||
forks=C.DEFAULT_FORKS, timeout=C.DEFAULT_TIMEOUT,
|
||||
pattern=C.DEFAULT_PATTERN, remote_user=C.DEFAULT_REMOTE_USER,
|
||||
remote_pass=C.DEFAULT_REMOTE_PASS, remote_port=C.DEFAULT_REMOTE_PORT,
|
||||
sudo_pass=C.DEFAULT_SUDO_PASS, background=0, basedir=None,
|
||||
setup_cache=None, transport=C.DEFAULT_TRANSPORT, conditional='True',
|
||||
callbacks=None, debug=False, sudo=False, module_vars=None,
|
||||
is_playbook=False, inventory=None):
|
||||
private_key_file=C.DEFAULT_PRIVATE_KEY_FILE, sudo_pass=C.DEFAULT_SUDO_PASS,
|
||||
background=0, basedir=None, setup_cache=None,
|
||||
transport=C.DEFAULT_TRANSPORT, conditional='True', callbacks=None,
|
||||
debug=False, sudo=False, sudo_user=C.DEFAULT_SUDO_USER,
|
||||
module_vars=None, is_playbook=False, inventory=None):
|
||||
|
||||
"""
|
||||
host_list : path to a host list file, like /etc/ansible/hosts
|
||||
@ -91,6 +93,8 @@ class Runner(object):
|
||||
remote_user : connect as this remote username
|
||||
remote_pass : supply this password (if not using keys)
|
||||
remote_port : use this default remote port (if not set by the inventory system)
|
||||
private_key_file : use this private key as your auth key
|
||||
sudo_user : If you want to sudo to a user other than root.
|
||||
sudo_pass : sudo password if using sudo and sudo requires a password
|
||||
background : run asynchronously with a cap of this many # of seconds (if not 0)
|
||||
basedir : paths used by modules if not absolute are relative to here
|
||||
@ -115,8 +119,9 @@ class Runner(object):
|
||||
|
||||
self.generated_jid = str(random.randint(0, 999999999999))
|
||||
|
||||
self.sudo_user = sudo_user
|
||||
self.transport = transport
|
||||
self.connector = ansible.connection.Connection(self, self.transport)
|
||||
self.connector = ansible.connection.Connection(self, self.transport, self.sudo_user)
|
||||
|
||||
if inventory is None:
|
||||
self.inventory = ansible.inventory.Inventory(host_list)
|
||||
@ -139,6 +144,7 @@ class Runner(object):
|
||||
self.remote_user = remote_user
|
||||
self.remote_pass = remote_pass
|
||||
self.remote_port = remote_port
|
||||
self.private_key_file = private_key_file
|
||||
self.background = background
|
||||
self.basedir = basedir
|
||||
self.sudo = sudo
|
||||
@ -156,19 +162,6 @@ class Runner(object):
|
||||
|
||||
# *****************************************************
|
||||
|
||||
@classmethod
|
||||
def parse_hosts(cls, host_list, override_hosts=None):
|
||||
''' parse the host inventory file, returns (hosts, groups) '''
|
||||
|
||||
if override_hosts is None:
|
||||
inventory = ansible.inventory.Inventory(host_list)
|
||||
else:
|
||||
inventory = ansible.inventory.Inventory(override_hosts)
|
||||
|
||||
return inventory.host_list, inventory.groups
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _return_from_module(self, conn, host, result, err, executed=None):
|
||||
''' helper function to handle JSON parsing of results '''
|
||||
|
||||
@ -213,7 +206,7 @@ class Runner(object):
|
||||
|
||||
afd, afile = tempfile.mkstemp()
|
||||
afo = os.fdopen(afd, 'w')
|
||||
afo.write(data)
|
||||
afo.write(data.encode("utf8"))
|
||||
afo.flush()
|
||||
afo.close()
|
||||
|
||||
@ -257,13 +250,13 @@ class Runner(object):
|
||||
if self.remote_user == 'root':
|
||||
args = "%s metadata=/etc/ansible/setup" % args
|
||||
else:
|
||||
args = "%s metadata=$HOME/.ansible/setup" % args
|
||||
args = "%s metadata=%s/.ansible/setup" % (args, C.DEFAULT_REMOTE_TMP)
|
||||
else:
|
||||
if not 'metadata' in args:
|
||||
if self.remote_user == 'root':
|
||||
args['metadata'] = '/etc/ansible/setup'
|
||||
else:
|
||||
args['metadata'] = "$HOME/.ansible/setup"
|
||||
args['metadata'] = "%s/.ansible/setup" % C.DEFAULT_REMOTE_TMP
|
||||
return args
|
||||
|
||||
# *****************************************************
|
||||
@ -272,15 +265,18 @@ class Runner(object):
|
||||
async_jid=None, async_module=None, async_limit=None):
|
||||
''' runs a module that has already been transferred '''
|
||||
|
||||
inject = self.setup_cache.get(conn.host,{})
|
||||
inject = self.setup_cache.get(conn.host,{}).copy()
|
||||
host_variables = self.inventory.get_variables(conn.host)
|
||||
inject.update(host_variables)
|
||||
inject.update(self.module_vars)
|
||||
|
||||
conditional = utils.double_template(self.conditional, inject, self.setup_cache)
|
||||
if not eval(conditional):
|
||||
return [ utils.smjson(dict(skipped=True)), None, 'skipped' ]
|
||||
|
||||
host_variables = self.inventory.get_variables(conn.host)
|
||||
inject.update(host_variables)
|
||||
|
||||
if self.module_name == 'setup':
|
||||
if not args:
|
||||
args = {}
|
||||
args = self._add_setup_vars(inject, args)
|
||||
args = self._add_setup_metadata(args)
|
||||
|
||||
@ -340,6 +336,17 @@ class Runner(object):
|
||||
|
||||
# *****************************************************
|
||||
|
||||
def _execute_raw(self, conn, host, tmp):
|
||||
''' execute a non-module command for bootstrapping, or if there's no python on a device '''
|
||||
stdout, stderr = self._exec_command( conn, self.module_args, tmp, sudoable = True )
|
||||
data = dict(stdout=stdout)
|
||||
if stderr:
|
||||
data['stderr'] = stderr
|
||||
return (host, True, data, '')
|
||||
|
||||
# ***************************************************
|
||||
|
||||
|
||||
def _execute_normal_module(self, conn, host, tmp, module_name):
|
||||
''' transfer & execute a module that is not 'copy' or 'template' '''
|
||||
|
||||
@ -441,6 +448,13 @@ class Runner(object):
|
||||
if source is None or dest is None:
|
||||
return (host, True, dict(failed=True, msg="src and dest are required"), '')
|
||||
|
||||
# apply templating to source argument
|
||||
inject = self.setup_cache.get(conn.host,{})
|
||||
source = utils.template(source, inject, self.setup_cache)
|
||||
|
||||
# apply templating to dest argument
|
||||
dest = utils.template(dest, inject, self.setup_cache)
|
||||
|
||||
# files are saved in dest dir, with a subdir for each host, then the filename
|
||||
dest = "%s/%s/%s" % (utils.path_dwim(self.basedir, dest), host, source)
|
||||
dest = dest.replace("//","/")
|
||||
@ -454,6 +468,7 @@ class Runner(object):
|
||||
if remote_md5 != local_md5:
|
||||
# create the containing directories, if needed
|
||||
os.makedirs(os.path.dirname(dest))
|
||||
|
||||
# fetch the file and check for changes
|
||||
conn.fetch_file(source, dest)
|
||||
new_md5 = os.popen("md5sum %s" % dest).read().split()[0]
|
||||
@ -545,10 +560,9 @@ class Runner(object):
|
||||
copy_module = self._transfer_module(conn, tmp, 'copy')
|
||||
|
||||
# template the source data locally
|
||||
source_data = file(utils.path_dwim(self.basedir, source)).read()
|
||||
resultant = ''
|
||||
try:
|
||||
resultant = utils.template(source_data, inject, self.setup_cache)
|
||||
resultant = utils.template_from_file(utils.path_dwim(self.basedir, source),
|
||||
inject, self.setup_cache, no_engine=False)
|
||||
except Exception, e:
|
||||
return (host, False, dict(failed=True, msg=str(e)), '')
|
||||
xfered = self._transfer_str(conn, tmp, 'source', resultant)
|
||||
@ -606,6 +620,8 @@ class Runner(object):
|
||||
result = self._execute_fetch(conn, host, tmp)
|
||||
elif self.module_name == 'template':
|
||||
result = self._execute_template(conn, host, tmp)
|
||||
elif self.module_name == 'raw':
|
||||
result = self._execute_raw(conn, host, tmp)
|
||||
else:
|
||||
if self.background == 0:
|
||||
result = self._execute_normal_module(conn, host, tmp, module_name)
|
||||
@ -636,8 +652,8 @@ class Runner(object):
|
||||
|
||||
def _exec_command(self, conn, cmd, tmp, sudoable=False):
|
||||
''' execute a command string over SSH, return the output '''
|
||||
|
||||
stdin, stdout, stderr = conn.exec_command(cmd, tmp, sudoable=sudoable)
|
||||
sudo_user = self.sudo_user
|
||||
stdin, stdout, stderr = conn.exec_command(cmd, tmp, sudo_user, sudoable=sudoable)
|
||||
err=None
|
||||
out=None
|
||||
if type(stderr) != str:
|
||||
@ -656,19 +672,18 @@ class Runner(object):
|
||||
def _get_tmp_path(self, conn):
|
||||
''' gets a temporary path on a remote box '''
|
||||
|
||||
# The problem with this is that it's executed on the
|
||||
# overlord, not on the target so we can't use tempdir and os.path
|
||||
# Only support the *nix world for now by using the $HOME env var
|
||||
|
||||
basetmp = "/var/tmp"
|
||||
if self.remote_user != 'root':
|
||||
basetmp = "$HOME/.ansible/tmp"
|
||||
basetmp = C.DEFAULT_REMOTE_TMP
|
||||
if self.remote_user == 'root':
|
||||
basetmp ="/var/tmp"
|
||||
cmd = "mktemp -d %s/ansible.XXXXXX" % basetmp
|
||||
if self.remote_user != 'root':
|
||||
cmd = "mkdir -p %s && %s" % (basetmp, cmd)
|
||||
|
||||
result, err = self._exec_command(conn, cmd, None, sudoable=False)
|
||||
cleaned = result.split("\n")[0].strip() + '/'
|
||||
if self.remote_user != 'root':
|
||||
cmd = 'chmod a+x %s' % cleaned
|
||||
result, err = self._exec_command(conn, cmd, None, sudoable=False)
|
||||
return cleaned
|
||||
|
||||
|
||||
|
||||
@ -21,6 +21,7 @@ import sys
|
||||
import os
|
||||
import shlex
|
||||
import re
|
||||
import codecs
|
||||
import jinja2
|
||||
import yaml
|
||||
import optparse
|
||||
@ -198,7 +199,29 @@ def parse_json(data):
|
||||
return { "failed" : True, "parsed" : False, "msg" : data }
|
||||
return results
|
||||
|
||||
_KEYCRE = re.compile(r"\$(\w+)")
|
||||
_LISTRE = re.compile(r"(\w+)\[(\d+)\]")
|
||||
|
||||
def varLookup(name, vars):
|
||||
''' 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]
|
||||
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
|
||||
else:
|
||||
return
|
||||
return space
|
||||
|
||||
_KEYCRE = re.compile(r"\$(?P<complex>\{){0,1}((?(complex)[\w\.\[\]]+|\w+))(?(complex)\})")
|
||||
# if { -> complex if complex, allow . and need trailing }
|
||||
|
||||
def varReplace(raw, vars):
|
||||
'''Perform variable replacement of $vars
|
||||
@ -220,8 +243,9 @@ def varReplace(raw, vars):
|
||||
|
||||
# Determine replacement value (if unknown variable then preserve
|
||||
# original)
|
||||
varname = m.group(1).lower()
|
||||
replacement = str(vars.get(varname, m.group()))
|
||||
varname = m.group(2)
|
||||
|
||||
replacement = unicode(varLookup(varname, vars) or m.group())
|
||||
|
||||
start, end = m.span()
|
||||
done.append(raw[:start]) # Keep stuff leading up to token
|
||||
@ -230,21 +254,29 @@ def varReplace(raw, vars):
|
||||
|
||||
return ''.join(done)
|
||||
|
||||
def template(text, vars, setup_cache):
|
||||
def template(text, vars, setup_cache, no_engine=True):
|
||||
''' run a text buffer through the templating engine '''
|
||||
vars = vars.copy()
|
||||
text = varReplace(str(text), vars)
|
||||
vars['hostvars'] = setup_cache
|
||||
template = jinja2.Template(text)
|
||||
return template.render(vars)
|
||||
text = varReplace(unicode(text), vars)
|
||||
if no_engine:
|
||||
# used when processing include: directives so that Jinja is evaluated
|
||||
# in a later context when more variables are available
|
||||
return text
|
||||
else:
|
||||
template = jinja2.Template(text)
|
||||
res = template.render(vars)
|
||||
if text.endswith('\n') and not res.endswith('\n'):
|
||||
res = res + '\n'
|
||||
return res
|
||||
|
||||
def double_template(text, vars, setup_cache):
|
||||
return template(template(text, vars, setup_cache), vars, setup_cache)
|
||||
|
||||
def template_from_file(path, vars, setup_cache):
|
||||
def template_from_file(path, vars, setup_cache, no_engine=True):
|
||||
''' run a file through the templating engine '''
|
||||
data = file(path).read()
|
||||
return template(data, vars, setup_cache)
|
||||
data = codecs.open(path, encoding="utf8").read()
|
||||
return template(data, vars, setup_cache, no_engine=no_engine)
|
||||
|
||||
def parse_yaml(data):
|
||||
return yaml.load(data)
|
||||
@ -263,7 +295,7 @@ def parse_kv(args):
|
||||
vargs = shlex.split(args, posix=True)
|
||||
for x in vargs:
|
||||
if x.find("=") != -1:
|
||||
k, v = x.split("=")
|
||||
k, v = x.split("=", 1)
|
||||
options[k]=v
|
||||
return options
|
||||
|
||||
@ -286,6 +318,8 @@ def base_parser(constants=C, usage="", output_opts=False, runas_opts=False, asyn
|
||||
default=constants.DEFAULT_HOST_LIST)
|
||||
parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true',
|
||||
help='ask for SSH password')
|
||||
parser.add_option('--private-key', default=None, dest='private_key_file',
|
||||
help='use this file to authenticate the connection')
|
||||
parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true',
|
||||
help='ask for sudo password')
|
||||
parser.add_option('-M', '--module-path', dest='module_path',
|
||||
@ -304,6 +338,8 @@ def base_parser(constants=C, usage="", output_opts=False, runas_opts=False, asyn
|
||||
if runas_opts:
|
||||
parser.add_option("-s", "--sudo", default=False, action="store_true",
|
||||
dest='sudo', help="run operations with sudo (nopasswd)")
|
||||
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
|
||||
parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER,
|
||||
dest='remote_user',
|
||||
help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER)
|
||||
|
||||
@ -25,6 +25,7 @@ import os
|
||||
import sys
|
||||
import shlex
|
||||
import subprocess
|
||||
import syslog
|
||||
import traceback
|
||||
|
||||
APT_PATH = "/usr/bin/apt-get"
|
||||
@ -81,7 +82,7 @@ def install(pkgspec, cache, upgrade=False, default_release=None):
|
||||
name, version = package_split(pkgspec)
|
||||
installed, upgradable = package_status(name, version, cache)
|
||||
if not installed or (upgrade and upgradable):
|
||||
cmd = "%s -q -y install '%s'" % (APT, pkgspec)
|
||||
cmd = "%s --option Dpkg::Options::=--force-confold -q -y install '%s'" % (APT, pkgspec)
|
||||
if default_release:
|
||||
cmd += " -t '%s'" % (default_release,)
|
||||
rc, out, err = run_apt(cmd)
|
||||
@ -113,6 +114,8 @@ if not os.path.exists(APT_PATH):
|
||||
argfile = sys.argv[1]
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
fail_json(msg='the module requires arguments -a')
|
||||
|
||||
@ -28,13 +28,18 @@ import subprocess
|
||||
import sys
|
||||
import datetime
|
||||
import traceback
|
||||
import syslog
|
||||
|
||||
# ===========================================
|
||||
|
||||
# FIXME: better error handling
|
||||
|
||||
argsfile = sys.argv[1]
|
||||
items = shlex.split(file(argsfile).read())
|
||||
args = open(argsfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
params = {}
|
||||
for x in items:
|
||||
|
||||
@ -30,6 +30,7 @@ import datetime
|
||||
import traceback
|
||||
import signal
|
||||
import time
|
||||
import syslog
|
||||
|
||||
def daemonize_self():
|
||||
# daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
|
||||
@ -76,6 +77,9 @@ wrapped_module = sys.argv[3]
|
||||
argsfile = sys.argv[4]
|
||||
cmd = "%s %s" % (wrapped_module, argsfile)
|
||||
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % " ".join(sys.argv[1:]))
|
||||
|
||||
# setup logging directory
|
||||
logdir = os.path.expanduser("~/.ansible_async")
|
||||
log_path = os.path.join(logdir, jid)
|
||||
|
||||
@ -29,9 +29,12 @@ import datetime
|
||||
import traceback
|
||||
import shlex
|
||||
import os
|
||||
import syslog
|
||||
|
||||
argfile = sys.argv[1]
|
||||
args = open(argfile, 'r').read()
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
shell = False
|
||||
|
||||
|
||||
@ -21,6 +21,7 @@
|
||||
import sys
|
||||
import os
|
||||
import shlex
|
||||
import syslog
|
||||
|
||||
# ===========================================
|
||||
# convert arguments of form a=b c=d
|
||||
@ -32,7 +33,11 @@ if len(sys.argv) == 1:
|
||||
argfile = sys.argv[1]
|
||||
if not os.path.exists(argfile):
|
||||
sys.exit(1)
|
||||
items = shlex.split(open(argfile, 'r').read())
|
||||
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
|
||||
params = {}
|
||||
|
||||
@ -22,4 +22,5 @@
|
||||
# facter
|
||||
# ruby-json
|
||||
|
||||
/usr/bin/facter --json
|
||||
/usr/bin/logger -t ansible-facter Invoked as-is
|
||||
/usr/bin/facter --json 2>/dev/null
|
||||
|
||||
101
library/file
101
library/file
@ -17,10 +17,6 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
try:
|
||||
import json
|
||||
except ImportError:
|
||||
import simplejson as json
|
||||
import os
|
||||
import sys
|
||||
import shlex
|
||||
@ -29,27 +25,25 @@ import shutil
|
||||
import stat
|
||||
import grp
|
||||
import pwd
|
||||
import syslog
|
||||
try:
|
||||
import selinux
|
||||
HAVE_SELINUX=True
|
||||
except ImportError:
|
||||
HAVE_SELINUX=False
|
||||
|
||||
def debug(msg):
|
||||
# ansible ignores stderr, so it's safe to use for debug
|
||||
# print >>sys.stderr, msg
|
||||
pass
|
||||
def dump_kv(vars):
|
||||
return " ".join("%s=%s" % (k,v) for (k,v) in vars.items())
|
||||
|
||||
def exit_json(rc=0, **kwargs):
|
||||
def exit_kv(rc=0, **kwargs):
|
||||
if 'path' in kwargs:
|
||||
debug("adding path info")
|
||||
add_path_info(kwargs)
|
||||
print json.dumps(kwargs)
|
||||
print dump_kv(kwargs)
|
||||
sys.exit(rc)
|
||||
|
||||
def fail_json(**kwargs):
|
||||
def fail_kv(**kwargs):
|
||||
kwargs['failed'] = True
|
||||
exit_json(rc=1, **kwargs)
|
||||
exit_kv(rc=1, **kwargs)
|
||||
|
||||
def add_path_info(kwargs):
|
||||
path = kwargs['path']
|
||||
@ -81,20 +75,16 @@ def selinux_mls_enabled():
|
||||
if not HAVE_SELINUX:
|
||||
return False
|
||||
if selinux.is_selinux_mls_enabled() == 1:
|
||||
debug('selinux mls is enabled')
|
||||
return True
|
||||
else:
|
||||
debug('selinux mls is disabled')
|
||||
return False
|
||||
|
||||
def selinux_enabled():
|
||||
if not HAVE_SELINUX:
|
||||
return False
|
||||
if selinux.is_selinux_enabled() == 1:
|
||||
debug('selinux is enabled')
|
||||
return True
|
||||
else:
|
||||
debug('selinux is disabled')
|
||||
return False
|
||||
|
||||
# Determine whether we need a placeholder for selevel/mls
|
||||
@ -112,13 +102,10 @@ def selinux_default_context(path, mode=0):
|
||||
try:
|
||||
ret = selinux.matchpathcon(path, mode)
|
||||
except OSError:
|
||||
debug("no default context available")
|
||||
return context
|
||||
if ret[0] == -1:
|
||||
debug("no default context available")
|
||||
return context
|
||||
context = ret[1].split(':')
|
||||
debug("got default secontext=%s" % ret[1])
|
||||
return context
|
||||
|
||||
def selinux_context(path):
|
||||
@ -128,11 +115,10 @@ def selinux_context(path):
|
||||
try:
|
||||
ret = selinux.lgetfilecon(path)
|
||||
except:
|
||||
fail_json(path=path, msg='failed to retrieve selinux context')
|
||||
fail_kv(path=path, msg='failed to retrieve selinux context')
|
||||
if ret[0] == -1:
|
||||
return context
|
||||
context = ret[1].split(':')
|
||||
debug("got current secontext=%s" % ret[1])
|
||||
return context
|
||||
|
||||
# ===========================================
|
||||
@ -140,9 +126,11 @@ def selinux_context(path):
|
||||
argfile = sys.argv[1]
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
fail_json(msg='the module requires arguments -a')
|
||||
fail_kv(msg='the module requires arguments -a')
|
||||
sys.exit(1)
|
||||
|
||||
params = {}
|
||||
@ -170,25 +158,22 @@ seuser = params.get('seuser', None)
|
||||
serole = params.get('serole', None)
|
||||
setype = params.get('setype', None)
|
||||
selevel = params.get('serange', 's0')
|
||||
context = params.get('context', None)
|
||||
secontext = [seuser, serole, setype]
|
||||
if selinux_mls_enabled():
|
||||
secontext.append(selevel)
|
||||
|
||||
if context is not None:
|
||||
if context != 'default':
|
||||
fail_json(msg='invalid context: %s' % context)
|
||||
if seuser is not None or serole is not None or setype is not None:
|
||||
fail_json(msg='cannot define context=default and seuser, serole or setype')
|
||||
secontext = selinux_default_context(path)
|
||||
default_secontext = selinux_default_context(path)
|
||||
for i in range(len(default_secontext)):
|
||||
if i is not None and secontext[i] == '_default':
|
||||
secontext[i] = default_secontext[i]
|
||||
|
||||
if state not in [ 'file', 'directory', 'link', 'absent']:
|
||||
fail_json(msg='invalid state: %s' % state)
|
||||
fail_kv(msg='invalid state: %s' % state)
|
||||
|
||||
if state == 'link' and (src is None or dest is None):
|
||||
fail_json(msg='src and dest are required for "link" state')
|
||||
fail_kv(msg='src and dest are required for "link" state')
|
||||
elif path is None:
|
||||
fail_json(msg='path is required')
|
||||
fail_kv(msg='path is required')
|
||||
|
||||
changed = False
|
||||
|
||||
@ -204,7 +189,6 @@ def user_and_group(filename):
|
||||
gid = st.st_gid
|
||||
user = pwd.getpwuid(uid)[0]
|
||||
group = grp.getgrgid(gid)[0]
|
||||
debug("got user=%s and group=%s" % (user, group))
|
||||
return (user, group)
|
||||
|
||||
def set_context_if_different(path, context, changed):
|
||||
@ -212,59 +196,52 @@ def set_context_if_different(path, context, changed):
|
||||
return changed
|
||||
cur_context = selinux_context(path)
|
||||
new_context = list(cur_context)
|
||||
debug("current secontext is %s" % ':'.join(cur_context))
|
||||
# Iterate over the current context instead of the
|
||||
# argument context, which may have selevel.
|
||||
for i in range(len(cur_context)):
|
||||
if context[i] is not None and context[i] != cur_context[i]:
|
||||
new_context[i] = context[i]
|
||||
debug("new secontext is %s" % ':'.join(new_context))
|
||||
if cur_context != new_context:
|
||||
try:
|
||||
rc = selinux.lsetfilecon(path, ':'.join(new_context))
|
||||
except OSError:
|
||||
fail_json(path=path, msg='invalid selinux context')
|
||||
fail_kv(path=path, msg='invalid selinux context')
|
||||
if rc != 0:
|
||||
fail_json(path=path, msg='set selinux context failed')
|
||||
fail_kv(path=path, msg='set selinux context failed')
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
def set_owner_if_different(path, owner, changed):
|
||||
if owner is None:
|
||||
debug('not tweaking owner')
|
||||
return changed
|
||||
user, group = user_and_group(path)
|
||||
if owner != user:
|
||||
debug('setting owner')
|
||||
rc = os.system("/bin/chown -R %s %s" % (owner, path))
|
||||
if rc != 0:
|
||||
fail_json(path=path, msg='chown failed')
|
||||
fail_kv(path=path, msg='chown failed')
|
||||
return True
|
||||
|
||||
return changed
|
||||
|
||||
def set_group_if_different(path, group, changed):
|
||||
if group is None:
|
||||
debug('not tweaking group')
|
||||
return changed
|
||||
old_user, old_group = user_and_group(path)
|
||||
if old_group != group:
|
||||
debug('setting group')
|
||||
rc = os.system("/bin/chgrp -R %s %s" % (group, path))
|
||||
if rc != 0:
|
||||
fail_json(path=path, msg='chgrp failed')
|
||||
fail_kv(path=path, msg='chgrp failed')
|
||||
return True
|
||||
return changed
|
||||
|
||||
def set_mode_if_different(path, mode, changed):
|
||||
if mode is None:
|
||||
debug('not tweaking mode')
|
||||
return changed
|
||||
try:
|
||||
# FIXME: support English modes
|
||||
mode = int(mode, 8)
|
||||
except Exception, e:
|
||||
fail_json(path=path, msg='mode needs to be something octalish', details=str(e))
|
||||
fail_kv(path=path, msg='mode needs to be something octalish', details=str(e))
|
||||
|
||||
st = os.stat(path)
|
||||
prev_mode = stat.S_IMODE(st[stat.ST_MODE])
|
||||
@ -273,10 +250,9 @@ def set_mode_if_different(path, mode, changed):
|
||||
# FIXME: comparison against string above will cause this to be executed
|
||||
# every time
|
||||
try:
|
||||
debug('setting mode')
|
||||
os.chmod(path, mode)
|
||||
except Exception, e:
|
||||
fail_json(path=path, msg='chmod failed', details=str(e))
|
||||
fail_kv(path=path, msg='chmod failed', details=str(e))
|
||||
|
||||
st = os.stat(path)
|
||||
new_mode = stat.S_IMODE(st[stat.ST_MODE])
|
||||
@ -287,13 +263,13 @@ def set_mode_if_different(path, mode, changed):
|
||||
|
||||
|
||||
def rmtree_error(func, path, exc_info):
|
||||
fail_json(path=path, msg='failed to remove directory')
|
||||
fail_kv(path=path, msg='failed to remove directory')
|
||||
|
||||
# ===========================================
|
||||
# go...
|
||||
|
||||
prev_state = 'absent'
|
||||
if os.path.exists(path):
|
||||
if os.path.lexists(path):
|
||||
if os.path.islink(path):
|
||||
prev_state = 'link'
|
||||
elif os.path.isfile(path):
|
||||
@ -302,7 +278,6 @@ if os.path.exists(path):
|
||||
prev_state = 'directory'
|
||||
|
||||
if prev_state != 'absent' and state == 'absent':
|
||||
debug('requesting absent')
|
||||
try:
|
||||
if prev_state == 'directory':
|
||||
if os.path.islink(path):
|
||||
@ -312,21 +287,20 @@ if prev_state != 'absent' and state == 'absent':
|
||||
else:
|
||||
os.unlink(path)
|
||||
except Exception, e:
|
||||
fail_json(path=path, msg=str(e))
|
||||
exit_json(path=path, changed=True)
|
||||
fail_kv(path=path, msg=str(e))
|
||||
exit_kv(path=path, changed=True)
|
||||
sys.exit(0)
|
||||
|
||||
if prev_state != 'absent' and prev_state != state:
|
||||
fail_json(path=path, msg='refusing to convert between %s and %s' % (prev_state, state))
|
||||
fail_kv(path=path, msg='refusing to convert between %s and %s' % (prev_state, state))
|
||||
|
||||
if prev_state == 'absent' and state == 'absent':
|
||||
exit_json(path=path, changed=False)
|
||||
exit_kv(path=path, changed=False)
|
||||
|
||||
if state == 'file':
|
||||
|
||||
debug('requesting file')
|
||||
if prev_state == 'absent':
|
||||
fail_json(path=path, msg='file does not exist, use copy or template module to create')
|
||||
fail_kv(path=path, msg='file does not exist, use copy or template module to create')
|
||||
|
||||
# set modes owners and context as needed
|
||||
changed = set_context_if_different(path, secontext, changed)
|
||||
@ -334,11 +308,10 @@ if state == 'file':
|
||||
changed = set_group_if_different(path, group, changed)
|
||||
changed = set_mode_if_different(path, mode, changed)
|
||||
|
||||
exit_json(path=path, changed=changed)
|
||||
exit_kv(path=path, changed=changed)
|
||||
|
||||
elif state == 'directory':
|
||||
|
||||
debug('requesting directory')
|
||||
if prev_state == 'absent':
|
||||
os.makedirs(path)
|
||||
changed = True
|
||||
@ -349,7 +322,7 @@ elif state == 'directory':
|
||||
changed = set_group_if_different(path, group, changed)
|
||||
changed = set_mode_if_different(path, mode, changed)
|
||||
|
||||
exit_json(path=path, changed=changed)
|
||||
exit_kv(path=path, changed=changed)
|
||||
|
||||
elif state == 'link':
|
||||
|
||||
@ -358,7 +331,7 @@ elif state == 'link':
|
||||
else:
|
||||
abs_src = os.path.join(os.path.dirname(dest), src)
|
||||
if not os.path.exists(abs_src):
|
||||
fail_json(dest=dest, src=src, msg='src file does not exist')
|
||||
fail_kv(dest=dest, src=src, msg='src file does not exist')
|
||||
|
||||
if prev_state == 'absent':
|
||||
os.symlink(src, dest)
|
||||
@ -371,7 +344,7 @@ elif state == 'link':
|
||||
os.unlink(dest)
|
||||
os.symlink(src, dest)
|
||||
else:
|
||||
fail_json(dest=dest, src=src, msg='unexpected position reached')
|
||||
fail_kv(dest=dest, src=src, msg='unexpected position reached')
|
||||
|
||||
# set modes owners and context as needed
|
||||
changed = set_context_if_different(dest, secontext, changed)
|
||||
@ -379,9 +352,9 @@ elif state == 'link':
|
||||
changed = set_group_if_different(dest, group, changed)
|
||||
changed = set_mode_if_different(dest, mode, changed)
|
||||
|
||||
exit_json(dest=dest, src=src, changed=changed)
|
||||
exit_kv(dest=dest, src=src, changed=changed)
|
||||
|
||||
|
||||
fail_json(path=path, msg='unexpected position reached')
|
||||
fail_kv(path=path, msg='unexpected position reached')
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
131
library/git
131
library/git
@ -18,19 +18,31 @@
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# I wanted to keep this simple at first, so for now this checks out
|
||||
# from the MASTER branch of a repo at a particular SHA or
|
||||
# from the given branch of a repo at a particular SHA or
|
||||
# tag. Latest is not supported, you should not be doing
|
||||
# that. Branch checkouts are not supported. Contribs
|
||||
# welcome! -- MPD
|
||||
# that. Contribs welcome! -- MPD
|
||||
|
||||
try:
|
||||
import json
|
||||
except ImportError:
|
||||
import simplejson as json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import shlex
|
||||
import subprocess
|
||||
import syslog
|
||||
|
||||
# ===========================================
|
||||
# Basic support methods
|
||||
|
||||
def exit_json(rc=0, **kwargs):
|
||||
print json.dumps(kwargs)
|
||||
sys.exit(rc)
|
||||
|
||||
def fail_json(**kwargs):
|
||||
kwargs['failed'] = True
|
||||
exit_json(rc=1, **kwargs)
|
||||
|
||||
# ===========================================
|
||||
# convert arguments of form a=b c=d
|
||||
@ -38,29 +50,19 @@ import subprocess
|
||||
# FIXME: make more idiomatic
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
print json.dumps({
|
||||
"failed" : True,
|
||||
"msg" : "the command module requires arguments (-a)"
|
||||
})
|
||||
sys.exit(1)
|
||||
fail_json(msg="the command module requires arguments (-a)")
|
||||
|
||||
argfile = sys.argv[1]
|
||||
if not os.path.exists(argfile):
|
||||
print json.dumps({
|
||||
"failed" : True,
|
||||
"msg" : "Argument file not found"
|
||||
})
|
||||
sys.exit(1)
|
||||
fail_json(msg="Argument file not found")
|
||||
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
print json.dumps({
|
||||
"failed" : True,
|
||||
"msg" : "the command module requires arguments (-a)"
|
||||
})
|
||||
sys.exit(1)
|
||||
fail_json(msg="the command module requires arguments (-a)")
|
||||
|
||||
params = {}
|
||||
for x in items:
|
||||
@ -69,7 +71,8 @@ for x in items:
|
||||
|
||||
dest = params['dest']
|
||||
repo = params['repo']
|
||||
version = params['version']
|
||||
branch = params.get('branch', 'master')
|
||||
version = params.get('version', 'HEAD')
|
||||
|
||||
# ===========================================
|
||||
|
||||
@ -81,7 +84,7 @@ def get_version(dest):
|
||||
sha = sha[0].split()[1]
|
||||
return sha
|
||||
|
||||
def clone(repo, dest):
|
||||
def clone(repo, dest, branch):
|
||||
''' makes a new git repo if it does not already exist '''
|
||||
try:
|
||||
os.makedirs(dest)
|
||||
@ -89,12 +92,68 @@ def clone(repo, dest):
|
||||
pass
|
||||
cmd = "git clone %s %s" % (repo, dest)
|
||||
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(out, err) = cmd.communicate()
|
||||
rc = cmd.returncode
|
||||
|
||||
if branch is None or rc != 0:
|
||||
return (out, err)
|
||||
|
||||
os.chdir(dest)
|
||||
cmd = "git checkout -b %s origin/%s" % (branch, branch)
|
||||
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
return cmd.communicate()
|
||||
|
||||
def pull(repo, dest):
|
||||
def reset(dest):
|
||||
'''
|
||||
Resets the index and working tree to HEAD.
|
||||
Discards any changes to tracked files in working
|
||||
tree since that commit.
|
||||
'''
|
||||
os.chdir(dest)
|
||||
cmd = "git reset --hard HEAD"
|
||||
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(out, err) = cmd.communicate()
|
||||
rc = cmd.returncode
|
||||
return (rc, out, err)
|
||||
|
||||
def switchLocalBranch( branch ):
|
||||
cmd = "git checkout %s" % branch
|
||||
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
return cmd.communicate()
|
||||
|
||||
def pull(repo, dest, branch):
|
||||
''' updates repo from remote sources '''
|
||||
os.chdir(dest)
|
||||
cmd = "git pull -u origin"
|
||||
cmd = "git branch -a"
|
||||
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(gbranch_out, gbranch_err) = cmd.communicate()
|
||||
|
||||
try:
|
||||
m = re.search( '^\* (\S+|\(no branch\))$', gbranch_out, flags=re.M )
|
||||
cur_branch = m.group(1)
|
||||
m = re.search( '\s+remotes/origin/HEAD -> origin/(\S+)', gbranch_out, flags=re.M )
|
||||
default_branch = m.group(1)
|
||||
except:
|
||||
fail_json(msg="could not determine branch data - received: %s" % gbranch_out)
|
||||
|
||||
if branch is None:
|
||||
if cur_branch != default_branch:
|
||||
(out, err) = switchLocalBranch( default_branch )
|
||||
|
||||
cmd = "git pull -u origin"
|
||||
|
||||
elif branch == cur_branch:
|
||||
cmd = "git pull -u origin"
|
||||
|
||||
else:
|
||||
m = re.search( '^\s+%s$' % branch, gbranch_out, flags=re.M ) #see if we've already checked it out
|
||||
if m is None:
|
||||
cmd = "git checkout -b %s origin/%s" % (branch, branch)
|
||||
|
||||
else:
|
||||
(out, err) = switchLocalBranch( branch )
|
||||
cmd = "git pull -u origin"
|
||||
|
||||
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
return cmd.communicate()
|
||||
|
||||
@ -120,33 +179,26 @@ out, err, status = (None, None, None)
|
||||
|
||||
before = None
|
||||
if not os.path.exists(gitconfig):
|
||||
(out, err) = clone(repo, dest)
|
||||
(out, err) = clone(repo, dest, branch)
|
||||
else:
|
||||
# else do a pull
|
||||
before = get_version(dest)
|
||||
(out, err) = pull(repo, dest)
|
||||
(rc, out, err) = reset(dest)
|
||||
if rc != 0:
|
||||
fail_json(out=out, err=err)
|
||||
(out, err) = pull(repo, dest, branch)
|
||||
|
||||
# handle errors from clone or pull
|
||||
|
||||
if out.find('error') != -1:
|
||||
print json.dumps({
|
||||
"failed" : True,
|
||||
"out" : out,
|
||||
"err" : err
|
||||
})
|
||||
sys.exit(1)
|
||||
fail_json(out=out, err=err)
|
||||
|
||||
# switch to version specified regardless of whether
|
||||
# we cloned or pulled
|
||||
|
||||
(out, err) = switchver(version, dest)
|
||||
if err.find('error') != -1:
|
||||
print json.dumps({
|
||||
"failed" : True,
|
||||
"out" : out,
|
||||
"err" : err
|
||||
})
|
||||
sys.exit(1)
|
||||
fail_json(out=out, err=err)
|
||||
|
||||
# determine if we changed anything
|
||||
|
||||
@ -156,9 +208,4 @@ changed = False
|
||||
if before != after:
|
||||
changed = True
|
||||
|
||||
print json.dumps({
|
||||
"changed" : changed,
|
||||
"before" : before,
|
||||
"after" : after
|
||||
})
|
||||
|
||||
exit_json(changed=changed, before=before, after=after)
|
||||
|
||||
@ -26,6 +26,7 @@ import grp
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import syslog
|
||||
|
||||
GROUPADD = "/usr/sbin/groupadd"
|
||||
GROUPDEL = "/usr/sbin/groupdel"
|
||||
@ -131,6 +132,8 @@ if len(sys.argv) == 2 and os.path.exists(sys.argv[1]):
|
||||
else:
|
||||
args = ' '.join(sys.argv[1:])
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
fail_json(msg='the module requires arguments -a')
|
||||
|
||||
@ -18,4 +18,5 @@
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
/usr/bin/logger -t ansible-ohai Invoked as-is
|
||||
/usr/bin/ohai
|
||||
|
||||
@ -22,4 +22,10 @@ try:
|
||||
except ImportError:
|
||||
import simplejson as json
|
||||
|
||||
import os
|
||||
import syslog
|
||||
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked as-is')
|
||||
|
||||
print json.dumps({ "ping" : "pong" })
|
||||
|
||||
23
library/raw
Executable file
23
library/raw
Executable file
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# (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/>.
|
||||
|
||||
# hey the Ansible raw module isn't really a remote transferred
|
||||
# module. All the magic happens in Runner.py, see the web docs
|
||||
# for more details.
|
||||
|
||||
111
library/service
111
library/service
@ -24,14 +24,50 @@ except ImportError:
|
||||
import sys
|
||||
import shlex
|
||||
import subprocess
|
||||
import os.path
|
||||
import syslog
|
||||
|
||||
# TODO: switch to fail_json and other helper functions
|
||||
# like other modules are using
|
||||
|
||||
# ===========================================
|
||||
|
||||
SERVICE = '/sbin/service'
|
||||
CHKCONFIG = '/sbin/chkconfig'
|
||||
SERVICE = None
|
||||
CHKCONFIG = None
|
||||
|
||||
def fail_json(d):
|
||||
print json.dumps(d)
|
||||
sys.exit(1)
|
||||
|
||||
def _find_binaries():
|
||||
# list of possible paths for service/chkconfig binaries
|
||||
# with the most probable first
|
||||
global CHKCONFIG
|
||||
global SERVICE
|
||||
paths = ['/sbin', '/usr/sbin', '/bin', '/usr/bin']
|
||||
binaries = [ 'service', 'chkconfig', 'update-rc.d' ]
|
||||
location = dict()
|
||||
|
||||
for binary in binaries:
|
||||
location[binary] = None
|
||||
|
||||
for binary in binaries:
|
||||
for path in paths:
|
||||
if os.path.exists(path + '/' + binary):
|
||||
location[binary] = path + '/' + binary
|
||||
break
|
||||
|
||||
if location.get('chkconfig', None):
|
||||
CHKCONFIG = location['chkconfig']
|
||||
elif location.get('update-rc.d', None):
|
||||
CHKCONFIG = location['update-rc.d']
|
||||
else:
|
||||
fail_json(dict(failed=True, msg='unable to find chkconfig or update-rc.d binary'))
|
||||
if location.get('service', None):
|
||||
SERVICE = location['service']
|
||||
else:
|
||||
fail_json(dict(failed=True, msg='unable to find service binary'))
|
||||
|
||||
|
||||
def _run(cmd):
|
||||
# returns (rc, stdout, stderr) from shell command
|
||||
@ -41,49 +77,60 @@ def _run(cmd):
|
||||
|
||||
|
||||
def _do_enable(name, enable):
|
||||
if enable.lower() in ['on', 'true', 'yes']:
|
||||
rc, stdout, stderr = _run("%s %s on" % (CHKCONFIG, name))
|
||||
elif enable.lower() in ['off', 'false', 'no']:
|
||||
rc, stdout, stderr = _run("%s %s off" % (CHKCONFIG, name))
|
||||
# we change argument depending on real binary used
|
||||
# update-rc.d wants enable/disable while
|
||||
# chkconfig wants on/off
|
||||
valid_argument = dict({'on' : 'on', 'off' : 'off'})
|
||||
|
||||
if CHKCONFIG.endswith("update-rc.d"):
|
||||
valid_argument['on'] = "enable"
|
||||
valid_argument['off'] = "disable"
|
||||
|
||||
if enable.lower() in ['on', 'true', 'yes', 'enable']:
|
||||
rc, stdout, stderr = _run("%s %s %s" % (CHKCONFIG, name, valid_argument['on']))
|
||||
elif enable.lower() in ['off', 'false', 'no', 'disable']:
|
||||
rc, stdout, stderr = _run("%s %s %s" % (CHKCONFIG, name, valid_argument['off']))
|
||||
|
||||
return rc, stdout, stderr
|
||||
|
||||
argfile = sys.argv[1]
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
print json.dumps(dict(failed=True, msg='this module requires arguments (-a)'))
|
||||
sys.exit(1)
|
||||
fail_json(dict(failed=True, msg='this module requires arguments (-a)'))
|
||||
|
||||
params = {}
|
||||
for arg in items:
|
||||
if "=" not in arg:
|
||||
print json.dumps(dict(failed=True, msg='expected key=value format arguments'))
|
||||
sys.exit(1)
|
||||
fail_json(dict(failed=True, msg='expected key=value format arguments'))
|
||||
|
||||
(name, value) = arg.split("=")
|
||||
params[name] = value
|
||||
|
||||
name = params.get('name', None)
|
||||
|
||||
if name is None:
|
||||
print json.dumps(dict(failed=True, msg='missing name'))
|
||||
sys.exit(1)
|
||||
fail_json(dict(failed=True, msg='missing name'))
|
||||
|
||||
state = params.get('state', None)
|
||||
list_items = params.get('list', None)
|
||||
enable = params.get('enable', None)
|
||||
enable = params.get('enabled', params.get('enable', None))
|
||||
|
||||
# running and started are the same
|
||||
if state and state not in [ 'running', 'started', 'stopped', 'restarted' ]:
|
||||
print json.dumps(dict(failed=True, msg='invalid value for state'))
|
||||
sys.exit(1)
|
||||
if list_items and list_items not in [ 'status' ]:
|
||||
print json.dumps(dict(failed=True, msg='invalid value for list'))
|
||||
sys.exit(1)
|
||||
if enable and enable.lower() not in [ 'on', 'off', 'true', 'false', 'yes', 'no' ]:
|
||||
print json.dumps(dict(failed=True, msg='invalid value for enable'))
|
||||
sys.exit(1)
|
||||
if state and state.lower() not in [ 'running', 'started', 'stopped', 'restarted','reloaded' ]:
|
||||
fail_json(dict(failed=True, msg='invalid value for state'))
|
||||
if list_items and list_items.lower() not in [ 'status' ]:
|
||||
fail_json(dict(failed=True, msg='invalid value for list'))
|
||||
if enable and enable.lower() not in [ 'on', 'off', 'true', 'false', 'yes', 'no', 'enable', 'disable' ]:
|
||||
fail_json(dict(failed=True, msg='invalid value for enable'))
|
||||
|
||||
|
||||
# ===========================================
|
||||
# find binaries locations on minion
|
||||
_find_binaries()
|
||||
|
||||
|
||||
# ===========================================
|
||||
@ -94,9 +141,9 @@ status = status_stdout + status_stderr
|
||||
|
||||
|
||||
running = False
|
||||
if status_stdout.find("not running") != -1:
|
||||
if status_stdout.find("stopped") != -1 or rc == 3:
|
||||
running = False
|
||||
elif status_stdout.find("running") != -1:
|
||||
elif status_stdout.find("running") != -1 or rc == 0:
|
||||
running = True
|
||||
elif name == 'iptables' and status_stdout.find("ACCEPT") != -1:
|
||||
# iptables status command output is lame
|
||||
@ -121,9 +168,9 @@ if state or enable:
|
||||
# ===========================================
|
||||
# determine if we are going to change anything
|
||||
|
||||
if not running and state == "started":
|
||||
if not running and state in ("started", "running"):
|
||||
changed = True
|
||||
elif running and state == "stopped":
|
||||
elif running and state in ("stopped","reloaded"):
|
||||
changed = True
|
||||
elif state == "restarted":
|
||||
changed = True
|
||||
@ -136,17 +183,19 @@ if state or enable:
|
||||
rc_state, stdout, stderr = _run("%s %s start" % (SERVICE, name))
|
||||
elif state == 'stopped':
|
||||
rc_state, stdout, stderr = _run("%s %s stop" % (SERVICE, name))
|
||||
elif state == 'reloaded':
|
||||
rc_state, stdout, stderr = _run("%s %s reload" % (SERVICE, name))
|
||||
elif state == 'restarted':
|
||||
rc1, stdout1, stderr1 = _run("%s %s stop" % (SERVICE, name))
|
||||
rc2, stdout2, stderr2 = _run("%s %s start" % (SERVICE, name))
|
||||
rc_state = rc and rc1 and rc2
|
||||
rc_state = rc + rc1 + rc2
|
||||
stdout = stdout1 + stdout2
|
||||
stderr = stderr1 + stderr2
|
||||
|
||||
|
||||
out += stdout
|
||||
err += stderr
|
||||
rc = rc and rc_state
|
||||
|
||||
rc = rc + rc_state
|
||||
|
||||
if rc != 0:
|
||||
|
||||
print json.dumps({
|
||||
@ -180,7 +229,7 @@ elif list_items is not None:
|
||||
|
||||
else:
|
||||
|
||||
print json.dumps(dict(failed=True, msg="expected state or list parameters"))
|
||||
print json.dumps(dict(failed=True, msg="expected state or list parameters"))
|
||||
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
@ -31,6 +31,7 @@ import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import traceback
|
||||
import syslog
|
||||
|
||||
try:
|
||||
import json
|
||||
@ -241,6 +242,9 @@ def get_network_facts(facts):
|
||||
facts[iface]['ipv4'] = {}
|
||||
facts[iface]['ipv4'] = { 'address': data[1].split(':')[1],
|
||||
'netmask': data[-1].split(':')[1] }
|
||||
ip = struct.unpack("!L", socket.inet_aton(facts[iface]['ipv4']['address']))[0]
|
||||
mask = struct.unpack("!L", socket.inet_aton(facts[iface]['ipv4']['netmask']))[0]
|
||||
facts[iface]['ipv4']['network'] = socket.inet_ntoa(struct.pack("!L", ip & mask))
|
||||
if 'inet6 addr' in line:
|
||||
(ip, prefix) = data[2].split('/')
|
||||
scope = data[3].split(':')[1].lower()
|
||||
@ -263,8 +267,32 @@ def get_public_ssh_host_keys(facts):
|
||||
else:
|
||||
facts['ssh_host_key_rsa_public'] = rsa.split()[1]
|
||||
|
||||
def get_selinux_facts(facts):
|
||||
if os.path.exists("/usr/sbin/sestatus"):
|
||||
cmd = subprocess.Popen("/usr/sbin/sestatus", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
out, err = cmd.communicate()
|
||||
if err == '':
|
||||
facts['selinux'] = {}
|
||||
list = out.split("\n")
|
||||
status = re.search("(enabled|disabled)", list[0])
|
||||
if status.group() == "enabled":
|
||||
mode = re.search("(enforcing|disabled|permissive)", list[2])
|
||||
config_mode = re.search("(enforcing|disabled|permissive)", list[3])
|
||||
policyvers = re.search("\d+", list[4])
|
||||
type = re.search("(targeted|strict|mls)", list[5])
|
||||
facts['selinux']['status'] = status.group()
|
||||
facts['selinux']['mode'] = mode.group()
|
||||
facts['selinux']['config_mode'] = config_mode.group()
|
||||
facts['selinux']['policyvers'] = policyvers.group()
|
||||
facts['selinux']['type'] = type.group()
|
||||
elif status.group() == "disabled":
|
||||
facts['selinux']['status'] = status.group()
|
||||
else:
|
||||
facts['selinux'] = False
|
||||
|
||||
def get_service_facts(facts):
|
||||
get_public_ssh_host_keys(facts)
|
||||
get_selinux_facts(facts)
|
||||
|
||||
def ansible_facts():
|
||||
facts = {}
|
||||
@ -295,6 +323,9 @@ except:
|
||||
(k,v) = opt.split("=")
|
||||
setup_options[k]=v
|
||||
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % setup_options)
|
||||
|
||||
ansible_file = os.path.expandvars(setup_options.get('metadata', DEFAULT_ANSIBLE_SETUP))
|
||||
ansible_dir = os.path.dirname(ansible_file)
|
||||
|
||||
|
||||
@ -21,6 +21,7 @@ import sys
|
||||
import os
|
||||
import shlex
|
||||
import base64
|
||||
import syslog
|
||||
|
||||
try:
|
||||
import json
|
||||
@ -36,7 +37,11 @@ if len(sys.argv) == 1:
|
||||
argfile = sys.argv[1]
|
||||
if not os.path.exists(argfile):
|
||||
sys.exit(1)
|
||||
items = shlex.split(open(argfile, 'r').read())
|
||||
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
params = {}
|
||||
for x in items:
|
||||
|
||||
46
library/user
46
library/user
@ -25,9 +25,14 @@ import os
|
||||
import pwd
|
||||
import grp
|
||||
import shlex
|
||||
import spwd
|
||||
import subprocess
|
||||
import sys
|
||||
import syslog
|
||||
try:
|
||||
import spwd
|
||||
HAVE_SPWD=True
|
||||
except:
|
||||
HAVE_SPWD=False
|
||||
|
||||
USERADD = "/usr/sbin/useradd"
|
||||
USERMOD = "/usr/sbin/usermod"
|
||||
@ -119,6 +124,10 @@ def user_add(user, **kwargs):
|
||||
else:
|
||||
return False
|
||||
|
||||
"""
|
||||
Without spwd, we would have to resort to reading /etc/shadow
|
||||
to get the encrypted string. For now, punt on idempotent password changes.
|
||||
"""
|
||||
def user_mod(user, **kwargs):
|
||||
cmd = [USERMOD]
|
||||
info = user_info(user)
|
||||
@ -135,14 +144,27 @@ def user_mod(user, **kwargs):
|
||||
cmd.append('-g')
|
||||
cmd.append(kwargs[key])
|
||||
elif key == 'groups' and kwargs[key] is not None:
|
||||
defined_groups = kwargs[key].split(',')
|
||||
for g in defined_groups:
|
||||
current_groups = user_group_membership(user)
|
||||
groups = kwargs[key].split(',')
|
||||
for g in groups:
|
||||
if not group_exists(g):
|
||||
fail_json(msg="Group %s does not exist" % (g))
|
||||
existing_groups = user_group_membership(user)
|
||||
if sorted(defined_groups) != sorted(existing_groups):
|
||||
group_diff = set(sorted(current_groups)).symmetric_difference(set(sorted(groups)))
|
||||
groups_need_mod = False
|
||||
|
||||
if group_diff:
|
||||
if kwargs['append'] is not None and kwargs['append'] == 'yes':
|
||||
for g in groups:
|
||||
if g in group_diff:
|
||||
cmd.append('-a')
|
||||
groups_need_mod = True
|
||||
else:
|
||||
groups_need_mod = True
|
||||
|
||||
if groups_need_mod:
|
||||
cmd.append('-G')
|
||||
cmd.append(kwargs[key])
|
||||
cmd.append(','.join(groups))
|
||||
|
||||
elif key == 'comment':
|
||||
if kwargs[key] is not None and info[4] != kwargs[key]:
|
||||
cmd.append('-c')
|
||||
@ -159,10 +181,6 @@ def user_mod(user, **kwargs):
|
||||
if kwargs[key] is not None and info[1] != kwargs[key]:
|
||||
cmd.append('-p')
|
||||
cmd.append(kwargs[key])
|
||||
elif key == 'append':
|
||||
if kwargs[key] is not None and kwargs[key] == 'yes':
|
||||
if 'groups' in kwargs and kwargs['groups'] is not None:
|
||||
cmd.append('-a')
|
||||
# skip if no changes to be made
|
||||
if len(cmd) == 1:
|
||||
return False
|
||||
@ -217,10 +235,12 @@ def user_info(user):
|
||||
return False
|
||||
try:
|
||||
info = get_pwd_info(user)
|
||||
sinfo = spwd.getspnam(user)
|
||||
if HAVE_SPWD:
|
||||
sinfo = spwd.getspnam(user)
|
||||
except KeyError:
|
||||
return False
|
||||
info[1] = sinfo[1]
|
||||
if HAVE_SPWD:
|
||||
info[1] = sinfo[1]
|
||||
return info
|
||||
|
||||
# ===========================================
|
||||
@ -244,6 +264,8 @@ if not os.path.exists(USERDEL):
|
||||
argfile = sys.argv[1]
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
fail_json(msg='the module requires arguments -a')
|
||||
|
||||
@ -27,6 +27,7 @@ except ImportError:
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import syslog
|
||||
try:
|
||||
import libvirt
|
||||
except ImportError:
|
||||
@ -366,6 +367,8 @@ def main():
|
||||
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
return VIRT_FAILED, msg
|
||||
|
||||
@ -27,6 +27,7 @@ import datetime
|
||||
import shlex
|
||||
import re
|
||||
import traceback
|
||||
import syslog
|
||||
|
||||
|
||||
try:
|
||||
@ -299,6 +300,8 @@ def main():
|
||||
|
||||
args = open(argfile, 'r').read()
|
||||
items = shlex.split(args)
|
||||
syslog.openlog('ansible-%s' % os.path.basename(__file__))
|
||||
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
|
||||
|
||||
if not len(items):
|
||||
msg = "the yum module requires arguments (-a)"
|
||||
|
||||
@ -6,7 +6,7 @@ BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot
|
||||
Name: ansible
|
||||
Release: 1%{?dist}
|
||||
Summary: Minimal SSH command and control
|
||||
Version: 0.3
|
||||
Version: 0.4
|
||||
|
||||
Group: Development/Libraries
|
||||
License: GPLv3
|
||||
|
||||
@ -3,6 +3,7 @@ import unittest
|
||||
|
||||
from ansible.inventory import Inventory
|
||||
from ansible.runner import Runner
|
||||
# from nose.plugins.skip import SkipTest
|
||||
|
||||
class TestInventory(unittest.TestCase):
|
||||
|
||||
@ -10,60 +11,73 @@ class TestInventory(unittest.TestCase):
|
||||
self.cwd = os.getcwd()
|
||||
self.test_dir = os.path.join(self.cwd, 'test')
|
||||
|
||||
self.inventory_file = os.path.join(self.test_dir, 'simple_hosts')
|
||||
self.inventory_script = os.path.join(self.test_dir, 'inventory_api.py')
|
||||
self.inventory_yaml = os.path.join(self.test_dir, 'yaml_hosts')
|
||||
self.inventory_file = os.path.join(self.test_dir, 'simple_hosts')
|
||||
self.complex_inventory_file = os.path.join(self.test_dir, 'complex_hosts')
|
||||
self.inventory_script = os.path.join(self.test_dir, 'inventory_api.py')
|
||||
self.inventory_yaml = os.path.join(self.test_dir, 'yaml_hosts')
|
||||
|
||||
os.chmod(self.inventory_script, 0755)
|
||||
|
||||
def tearDown(self):
|
||||
os.chmod(self.inventory_script, 0644)
|
||||
|
||||
### Simple inventory format tests
|
||||
def compare(self, left, right):
|
||||
left = sorted(left)
|
||||
right = sorted(right)
|
||||
print left
|
||||
print right
|
||||
assert left == right
|
||||
|
||||
|
||||
def simple_inventory(self):
|
||||
return Inventory( self.inventory_file )
|
||||
return Inventory(self.inventory_file)
|
||||
|
||||
def script_inventory(self):
|
||||
return Inventory( self.inventory_script )
|
||||
return Inventory(self.inventory_script)
|
||||
|
||||
def yaml_inventory(self):
|
||||
return Inventory( self.inventory_yaml )
|
||||
return Inventory(self.inventory_yaml)
|
||||
|
||||
def complex_inventory(self):
|
||||
return Inventory(self.complex_inventory_file)
|
||||
|
||||
#####################################
|
||||
### Simple inventory format tests
|
||||
|
||||
def test_simple(self):
|
||||
inventory = self.simple_inventory()
|
||||
hosts = inventory.list_hosts()
|
||||
|
||||
expected_hosts=['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
assert sorted(hosts) == sorted(expected_hosts)
|
||||
|
||||
def test_simple_all(self):
|
||||
inventory = self.simple_inventory()
|
||||
hosts = inventory.list_hosts('all')
|
||||
|
||||
expected_hosts=['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
assert sorted(hosts) == sorted(expected_hosts)
|
||||
|
||||
def test_simple_norse(self):
|
||||
inventory = self.simple_inventory()
|
||||
hosts = inventory.list_hosts("norse")
|
||||
|
||||
expected_hosts=['thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
assert sorted(hosts) == sorted(expected_hosts)
|
||||
|
||||
def test_simple_ungrouped(self):
|
||||
inventory = self.simple_inventory()
|
||||
hosts = inventory.list_hosts("ungrouped")
|
||||
|
||||
expected_hosts=['jupiter', 'saturn']
|
||||
assert hosts == expected_hosts
|
||||
assert sorted(hosts) == sorted(expected_hosts)
|
||||
|
||||
def test_simple_combined(self):
|
||||
inventory = self.simple_inventory()
|
||||
hosts = inventory.list_hosts("norse:greek")
|
||||
|
||||
expected_hosts=['zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
assert sorted(hosts) == sorted(expected_hosts)
|
||||
|
||||
def test_simple_restrict(self):
|
||||
inventory = self.simple_inventory()
|
||||
@ -74,17 +88,22 @@ class TestInventory(unittest.TestCase):
|
||||
inventory.restrict_to(restricted_hosts)
|
||||
hosts = inventory.list_hosts("norse:greek")
|
||||
|
||||
assert hosts == restricted_hosts
|
||||
print "Hosts=%s" % hosts
|
||||
print "Restricted=%s" % restricted_hosts
|
||||
assert sorted(hosts) == sorted(restricted_hosts)
|
||||
|
||||
inventory.lift_restriction()
|
||||
hosts = inventory.list_hosts("norse:greek")
|
||||
|
||||
assert hosts == expected_hosts
|
||||
print hosts
|
||||
print expected_hosts
|
||||
assert sorted(hosts) == sorted(expected_hosts)
|
||||
|
||||
def test_simple_vars(self):
|
||||
inventory = self.simple_inventory()
|
||||
vars = inventory.get_variables('thor')
|
||||
|
||||
print vars
|
||||
assert vars == {'group_names': ['norse'],
|
||||
'inventory_hostname': 'thor'}
|
||||
|
||||
@ -92,10 +111,34 @@ class TestInventory(unittest.TestCase):
|
||||
inventory = self.simple_inventory()
|
||||
vars = inventory.get_variables('hera')
|
||||
|
||||
assert vars == {'ansible_ssh_port': 3000,
|
||||
print vars
|
||||
expected = {'ansible_ssh_port': 3000,
|
||||
'group_names': ['greek'],
|
||||
'inventory_hostname': 'hera'}
|
||||
print expected
|
||||
assert vars == expected
|
||||
|
||||
###################################################
|
||||
### INI file advanced tests
|
||||
|
||||
def test_complex_vars(self):
|
||||
inventory = self.complex_inventory()
|
||||
|
||||
vars = inventory.get_variables('rtp_a')
|
||||
print vars
|
||||
|
||||
expected = dict(
|
||||
a='1', b='2', c='3', d='100002', rga='1', rgb='2', rgc='3',
|
||||
inventory_hostname='rtp_a',
|
||||
group_names=[ 'eastcoast', 'nc', 'redundantgroup', 'redundantgroup2', 'redundantgroup3', 'rtp', 'us' ]
|
||||
)
|
||||
print vars
|
||||
print expected
|
||||
assert vars == expected
|
||||
|
||||
|
||||
|
||||
###################################################
|
||||
### Inventory API tests
|
||||
|
||||
def test_script(self):
|
||||
@ -149,6 +192,8 @@ class TestInventory(unittest.TestCase):
|
||||
inventory = self.script_inventory()
|
||||
vars = inventory.get_variables('thor')
|
||||
|
||||
print "VARS=%s" % vars
|
||||
|
||||
assert vars == {'hammer':True,
|
||||
'group_names': ['norse'],
|
||||
'inventory_hostname': 'thor'}
|
||||
@ -160,35 +205,35 @@ class TestInventory(unittest.TestCase):
|
||||
hosts = inventory.list_hosts()
|
||||
print hosts
|
||||
expected_hosts=['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
self.compare(hosts, expected_hosts)
|
||||
|
||||
def test_yaml_all(self):
|
||||
inventory = self.yaml_inventory()
|
||||
hosts = inventory.list_hosts('all')
|
||||
|
||||
expected_hosts=['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
self.compare(hosts, expected_hosts)
|
||||
|
||||
def test_yaml_norse(self):
|
||||
inventory = self.yaml_inventory()
|
||||
hosts = inventory.list_hosts("norse")
|
||||
|
||||
expected_hosts=['thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
self.compare(hosts, expected_hosts)
|
||||
|
||||
def test_simple_ungrouped(self):
|
||||
def test_yaml_ungrouped(self):
|
||||
inventory = self.yaml_inventory()
|
||||
hosts = inventory.list_hosts("ungrouped")
|
||||
|
||||
expected_hosts=['jupiter']
|
||||
assert hosts == expected_hosts
|
||||
self.compare(hosts, expected_hosts)
|
||||
|
||||
def test_yaml_combined(self):
|
||||
inventory = self.yaml_inventory()
|
||||
hosts = inventory.list_hosts("norse:greek")
|
||||
|
||||
expected_hosts=['zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
self.compare(hosts, expected_hosts)
|
||||
|
||||
def test_yaml_restrict(self):
|
||||
inventory = self.yaml_inventory()
|
||||
@ -199,21 +244,28 @@ class TestInventory(unittest.TestCase):
|
||||
inventory.restrict_to(restricted_hosts)
|
||||
hosts = inventory.list_hosts("norse:greek")
|
||||
|
||||
assert hosts == restricted_hosts
|
||||
self.compare(hosts, restricted_hosts)
|
||||
|
||||
inventory.lift_restriction()
|
||||
hosts = inventory.list_hosts("norse:greek")
|
||||
|
||||
assert hosts == expected_hosts
|
||||
self.compare(hosts, expected_hosts)
|
||||
|
||||
def test_yaml_vars(self):
|
||||
inventory = self.yaml_inventory()
|
||||
vars = inventory.get_variables('thor')
|
||||
print vars
|
||||
assert vars == {'group_names': ['norse'],
|
||||
'hammer':True,
|
||||
'inventory_hostname': 'thor'}
|
||||
|
||||
def test_yaml_list_vars(self):
|
||||
inventory = self.yaml_inventory()
|
||||
vars = inventory.get_variables('zeus')
|
||||
assert vars == {'ansible_ssh_port': 3001,
|
||||
'group_names': ['greek', 'ruler'],
|
||||
'inventory_hostname': 'zeus',
|
||||
'ntp_server': 'olympus.example.com'}
|
||||
|
||||
def test_yaml_change_vars(self):
|
||||
inventory = self.yaml_inventory()
|
||||
vars = inventory.get_variables('thor')
|
||||
@ -221,6 +273,7 @@ class TestInventory(unittest.TestCase):
|
||||
vars["hammer"] = False
|
||||
|
||||
vars = inventory.get_variables('thor')
|
||||
print vars
|
||||
assert vars == {'hammer':True,
|
||||
'inventory_hostname': 'thor',
|
||||
'group_names': ['norse']}
|
||||
@ -229,6 +282,7 @@ class TestInventory(unittest.TestCase):
|
||||
inventory = self.yaml_inventory()
|
||||
vars = inventory.get_variables('saturn')
|
||||
|
||||
print vars
|
||||
assert vars == {'inventory_hostname': 'saturn',
|
||||
'moon': 'titan',
|
||||
'moon2': 'enceladus',
|
||||
@ -238,6 +292,7 @@ class TestInventory(unittest.TestCase):
|
||||
inventory = self.yaml_inventory()
|
||||
vars = inventory.get_variables('hera')
|
||||
|
||||
print vars
|
||||
assert vars == {'ansible_ssh_port': 3000,
|
||||
'inventory_hostname': 'hera',
|
||||
'ntp_server': 'olympus.example.com',
|
||||
@ -250,25 +305,3 @@ class TestInventory(unittest.TestCase):
|
||||
assert 'group_names' in vars
|
||||
assert sorted(vars['group_names']) == [ 'norse', 'ruler' ]
|
||||
|
||||
### Test Runner class method
|
||||
|
||||
def test_class_method(self):
|
||||
hosts, groups = Runner.parse_hosts(self.inventory_file)
|
||||
|
||||
expected_hosts = ['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
|
||||
assert hosts == expected_hosts
|
||||
|
||||
expected_groups= {
|
||||
'ungrouped': ['jupiter', 'saturn'],
|
||||
'greek': ['zeus', 'hera', 'poseidon'],
|
||||
'norse': ['thor', 'odin', 'loki']
|
||||
}
|
||||
assert groups == expected_groups
|
||||
|
||||
def test_class_override(self):
|
||||
override_hosts = ['thor', 'odin']
|
||||
hosts, groups = Runner.parse_hosts(self.inventory_file, override_hosts)
|
||||
|
||||
assert hosts == override_hosts
|
||||
|
||||
assert groups == { 'ungrouped': override_hosts }
|
||||
|
||||
@ -10,9 +10,9 @@ import os
|
||||
import shutil
|
||||
import time
|
||||
try:
|
||||
import json
|
||||
import json
|
||||
except:
|
||||
import simplejson as json
|
||||
import simplejson as json
|
||||
|
||||
from nose.plugins.skip import SkipTest
|
||||
|
||||
@ -25,202 +25,211 @@ def get_binary(name):
|
||||
|
||||
class TestRunner(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.user = getpass.getuser()
|
||||
self.runner = ansible.runner.Runner(
|
||||
module_name='ping',
|
||||
module_path='library/',
|
||||
module_args='',
|
||||
remote_user=self.user,
|
||||
remote_pass=None,
|
||||
host_list='test/ansible_hosts',
|
||||
timeout=5,
|
||||
forks=1,
|
||||
background=0,
|
||||
pattern='all',
|
||||
)
|
||||
self.cwd = os.getcwd()
|
||||
self.test_dir = os.path.join(self.cwd, 'test')
|
||||
self.stage_dir = self._prepare_stage_dir()
|
||||
def setUp(self):
|
||||
self.user = getpass.getuser()
|
||||
self.runner = ansible.runner.Runner(
|
||||
module_name='ping',
|
||||
module_path='library/',
|
||||
module_args='',
|
||||
remote_user=self.user,
|
||||
remote_pass=None,
|
||||
host_list='test/ansible_hosts',
|
||||
timeout=5,
|
||||
forks=1,
|
||||
background=0,
|
||||
pattern='all',
|
||||
)
|
||||
self.cwd = os.getcwd()
|
||||
self.test_dir = os.path.join(self.cwd, 'test')
|
||||
self.stage_dir = self._prepare_stage_dir()
|
||||
|
||||
def _prepare_stage_dir(self):
|
||||
stage_path = os.path.join(self.test_dir, 'test_data')
|
||||
if os.path.exists(stage_path):
|
||||
shutil.rmtree(stage_path, ignore_errors=False)
|
||||
assert not os.path.exists(stage_path)
|
||||
os.makedirs(stage_path)
|
||||
assert os.path.exists(stage_path)
|
||||
return stage_path
|
||||
def _prepare_stage_dir(self):
|
||||
stage_path = os.path.join(self.test_dir, 'test_data')
|
||||
if os.path.exists(stage_path):
|
||||
shutil.rmtree(stage_path, ignore_errors=False)
|
||||
assert not os.path.exists(stage_path)
|
||||
os.makedirs(stage_path)
|
||||
assert os.path.exists(stage_path)
|
||||
return stage_path
|
||||
|
||||
def _get_test_file(self, filename):
|
||||
# get a file inside the test input directory
|
||||
filename = os.path.join(self.test_dir, filename)
|
||||
assert os.path.exists(filename)
|
||||
return filename
|
||||
|
||||
def _get_stage_file(self, filename):
|
||||
# get a file inside the test output directory
|
||||
filename = os.path.join(self.stage_dir, filename)
|
||||
return filename
|
||||
def _get_test_file(self, filename):
|
||||
# get a file inside the test input directory
|
||||
filename = os.path.join(self.test_dir, filename)
|
||||
assert os.path.exists(filename)
|
||||
return filename
|
||||
|
||||
def _run(self, module_name, module_args, background=0):
|
||||
''' run a module and get the localhost results '''
|
||||
self.runner.module_name = module_name
|
||||
args = ' '.join(module_args)
|
||||
print "DEBUG: using args=%s" % args
|
||||
self.runner.module_args = args
|
||||
self.runner.background = background
|
||||
results = self.runner.run()
|
||||
# when using nosetests this will only show up on failure
|
||||
# which is pretty useful
|
||||
print "RESULTS=%s" % results
|
||||
assert "127.0.0.2" in results['contacted']
|
||||
return results['contacted']['127.0.0.2']
|
||||
def _get_stage_file(self, filename):
|
||||
# get a file inside the test output directory
|
||||
filename = os.path.join(self.stage_dir, filename)
|
||||
return filename
|
||||
|
||||
def test_ping(self):
|
||||
result = self._run('ping',[])
|
||||
assert "ping" in result
|
||||
def _run(self, module_name, module_args, background=0):
|
||||
''' run a module and get the localhost results '''
|
||||
self.runner.module_name = module_name
|
||||
args = ' '.join(module_args)
|
||||
print "DEBUG: using args=%s" % args
|
||||
self.runner.module_args = args
|
||||
self.runner.background = background
|
||||
results = self.runner.run()
|
||||
# when using nosetests this will only show up on failure
|
||||
# which is pretty useful
|
||||
print "RESULTS=%s" % results
|
||||
assert "127.0.0.2" in results['contacted']
|
||||
return results['contacted']['127.0.0.2']
|
||||
|
||||
def test_facter(self):
|
||||
if not get_binary("facter"):
|
||||
raise SkipTest
|
||||
result = self._run('facter',[])
|
||||
assert "hostname" in result
|
||||
def test_ping(self):
|
||||
result = self._run('ping', [])
|
||||
assert "ping" in result
|
||||
|
||||
# temporarily disbabled since it occasionally hangs
|
||||
# ohai's fault, setup module doesn't actually run this
|
||||
# to get ohai's "facts" anyway
|
||||
#
|
||||
#def test_ohai(self):
|
||||
# if not get_binary("facter"):
|
||||
# raise SkipTest
|
||||
# result = self._run('ohai',[])
|
||||
# assert "hostname" in result
|
||||
def test_facter(self):
|
||||
if not get_binary("facter"):
|
||||
raise SkipTest
|
||||
result = self._run('facter', [])
|
||||
assert "hostname" in result
|
||||
|
||||
def test_copy(self):
|
||||
# test copy module, change trigger, etc
|
||||
pass
|
||||
# temporarily disbabled since it occasionally hangs
|
||||
# ohai's fault, setup module doesn't actually run this
|
||||
# to get ohai's "facts" anyway
|
||||
#
|
||||
#def test_ohai(self):
|
||||
# if not get_binary("facter"):
|
||||
# raise SkipTest
|
||||
# result = self._run('ohai',[])
|
||||
# assert "hostname" in result
|
||||
|
||||
def test_copy(self):
|
||||
input = self._get_test_file('sample.j2')
|
||||
output = self._get_stage_file('sample.out')
|
||||
assert not os.path.exists(output)
|
||||
result = self._run('copy', [
|
||||
"src=%s" % input,
|
||||
"dest=%s" % output,
|
||||
])
|
||||
assert os.path.exists(output)
|
||||
data_in = file(input).read()
|
||||
data_out = file(output).read()
|
||||
assert data_in == data_out
|
||||
assert 'failed' not in result
|
||||
assert result['changed'] == True
|
||||
assert 'md5sum' in result
|
||||
result = self._run('copy', [
|
||||
"src=%s" % input,
|
||||
"dest=%s" % output,
|
||||
])
|
||||
assert result['changed'] == False
|
||||
def test_copy(self):
|
||||
# test copy module, change trigger, etc
|
||||
input_ = self._get_test_file('sample.j2')
|
||||
output = self._get_stage_file('sample.out')
|
||||
assert not os.path.exists(output)
|
||||
result = self._run('copy', [
|
||||
"src=%s" % input_,
|
||||
"dest=%s" % output,
|
||||
])
|
||||
assert os.path.exists(output)
|
||||
data_in = file(input_).read()
|
||||
data_out = file(output).read()
|
||||
assert data_in == data_out
|
||||
assert 'failed' not in result
|
||||
assert result['changed'] == True
|
||||
assert 'md5sum' in result
|
||||
result = self._run('copy', [
|
||||
"src=%s" % input_,
|
||||
"dest=%s" % output,
|
||||
])
|
||||
assert result['changed'] == False
|
||||
|
||||
def test_template(self):
|
||||
input = self._get_test_file('sample.j2')
|
||||
metadata = self._get_test_file('metadata.json')
|
||||
output = self._get_stage_file('sample.out')
|
||||
result = self._run('template', [
|
||||
"src=%s" % input,
|
||||
"dest=%s" % output,
|
||||
"metadata=%s" % metadata
|
||||
])
|
||||
assert os.path.exists(output)
|
||||
out = file(output).read()
|
||||
assert out.find("duck") != -1
|
||||
assert result['changed'] == True
|
||||
assert 'md5sum' in result
|
||||
assert 'failed' not in result
|
||||
result = self._run('template', [
|
||||
"src=%s" % input,
|
||||
"dest=%s" % output,
|
||||
"metadata=%s" % metadata
|
||||
])
|
||||
assert result['changed'] == False
|
||||
def test_template(self):
|
||||
input_ = self._get_test_file('sample.j2')
|
||||
metadata = self._get_test_file('metadata.json')
|
||||
output = self._get_stage_file('sample.out')
|
||||
result = self._run('template', [
|
||||
"src=%s" % input_,
|
||||
"dest=%s" % output,
|
||||
"metadata=%s" % metadata
|
||||
])
|
||||
assert os.path.exists(output)
|
||||
out = file(output).read()
|
||||
assert out.find("duck") != -1
|
||||
assert result['changed'] == True
|
||||
assert 'md5sum' in result
|
||||
assert 'failed' not in result
|
||||
result = self._run('template', [
|
||||
"src=%s" % input_,
|
||||
"dest=%s" % output,
|
||||
"metadata=%s" % metadata
|
||||
])
|
||||
assert result['changed'] == False
|
||||
|
||||
def test_command(self):
|
||||
|
||||
# test command module, change trigger, etc
|
||||
result = self._run('command', [ "/bin/echo", "hi" ])
|
||||
assert "failed" not in result
|
||||
assert "msg" not in result
|
||||
assert result['rc'] == 0
|
||||
assert result['stdout'] == 'hi'
|
||||
assert result['stderr'] == ''
|
||||
|
||||
result = self._run('command', [ "/bin/false" ])
|
||||
assert result['rc'] == 1
|
||||
assert 'failed' not in result
|
||||
|
||||
result = self._run('command', [ "/usr/bin/this_does_not_exist", "splat" ])
|
||||
assert 'msg' in result
|
||||
assert 'failed' in result
|
||||
assert 'rc' not in result
|
||||
def test_command(self):
|
||||
# test command module, change trigger, etc
|
||||
result = self._run('command', [ "/bin/echo", "hi" ])
|
||||
assert "failed" not in result
|
||||
assert "msg" not in result
|
||||
assert result['rc'] == 0
|
||||
assert result['stdout'] == 'hi'
|
||||
assert result['stderr'] == ''
|
||||
|
||||
result = self._run('shell', [ "/bin/echo", "$HOME" ])
|
||||
assert 'failed' not in result
|
||||
assert result['rc'] == 0
|
||||
|
||||
result = self._run('command', [ "/bin/false" ])
|
||||
assert result['rc'] == 1
|
||||
assert 'failed' not in result
|
||||
|
||||
def test_setup(self):
|
||||
output = self._get_stage_file('output.json')
|
||||
result = self._run('setup', [ "metadata=%s" % output, "a=2", "b=3", "c=4" ])
|
||||
assert 'failed' not in result
|
||||
assert 'md5sum' in result
|
||||
assert result['changed'] == True
|
||||
outds = json.loads(file(output).read())
|
||||
assert outds['c'] == '4'
|
||||
# not bothering to test change hooks here since ohai/facter results change
|
||||
# almost every time so changed is always true, this just tests that
|
||||
# rewriting the file is ok
|
||||
result = self._run('setup', [ "metadata=%s" % output, "a=2", "b=3", "c=4" ])
|
||||
print "RAW RESULT=%s" % result
|
||||
assert 'md5sum' in result
|
||||
result = self._run('command', [ "/usr/bin/this_does_not_exist", "splat" ])
|
||||
assert 'msg' in result
|
||||
assert 'failed' in result
|
||||
assert 'rc' not in result
|
||||
|
||||
def test_async(self):
|
||||
# test async launch and job status
|
||||
# of any particular module
|
||||
result = self._run('command', [ get_binary("sleep"), "3" ], background=20)
|
||||
assert 'ansible_job_id' in result
|
||||
assert 'started' in result
|
||||
jid = result['ansible_job_id']
|
||||
# no real chance of this op taking a while, but whatever
|
||||
time.sleep(5)
|
||||
# CLI will abstract this (when polling), but this is how it works internally
|
||||
result = self._run('async_status', [ "jid=%s" % jid ])
|
||||
# TODO: would be nice to have tests for supervisory process
|
||||
# killing job after X seconds
|
||||
assert 'finished' in result
|
||||
assert 'failed' not in result
|
||||
assert 'rc' in result
|
||||
assert 'stdout' in result
|
||||
assert result['ansible_job_id'] == jid
|
||||
result = self._run('shell', [ "/bin/echo", "$HOME" ])
|
||||
assert 'failed' not in result
|
||||
assert result['rc'] == 0
|
||||
|
||||
def test_fetch(self):
|
||||
input = self._get_test_file('sample.j2')
|
||||
output = os.path.join(self.stage_dir, '127.0.0.2', input)
|
||||
result = self._run('fetch', [ "src=%s" % input, "dest=%s" % self.stage_dir ])
|
||||
assert os.path.exists(output)
|
||||
assert open(input).read() == open(output).read()
|
||||
def test_large_output(self):
|
||||
large_path = "/usr/share/dict/words"
|
||||
if not os.path.exists(large_path):
|
||||
large_path = "/usr/share/dict/cracklib-small"
|
||||
if not os.path.exists(large_path):
|
||||
raise SkipTest
|
||||
# Ensure reading a large amount of output from a command doesn't hang.
|
||||
result = self._run('command', [ "/bin/cat", large_path ])
|
||||
assert "failed" not in result
|
||||
assert "msg" not in result
|
||||
assert result['rc'] == 0
|
||||
assert len(result['stdout']) > 100000
|
||||
assert result['stderr'] == ''
|
||||
|
||||
def test_yum(self):
|
||||
if not get_binary("yum"):
|
||||
raise SkipTest
|
||||
result = self._run('yum', [ "list=repos" ])
|
||||
assert 'failed' not in result
|
||||
def test_setup(self):
|
||||
output = self._get_stage_file('output.json')
|
||||
result = self._run('setup', [ "metadata=%s" % output, "a=2", "b=3", "c=4" ])
|
||||
assert 'failed' not in result
|
||||
assert 'md5sum' in result
|
||||
assert result['changed'] == True
|
||||
outds = json.loads(file(output).read())
|
||||
assert outds['c'] == '4'
|
||||
# not bothering to test change hooks here since ohai/facter results change
|
||||
# almost every time so changed is always true, this just tests that
|
||||
# rewriting the file is ok
|
||||
result = self._run('setup', [ "metadata=%s" % output, "a=2", "b=3", "c=4" ])
|
||||
print "RAW RESULT=%s" % result
|
||||
assert 'md5sum' in result
|
||||
|
||||
def test_git(self):
|
||||
# TODO: tests for the git module
|
||||
pass
|
||||
def test_async(self):
|
||||
# test async launch and job status
|
||||
# of any particular module
|
||||
result = self._run('command', [ get_binary("sleep"), "3" ], background=20)
|
||||
assert 'ansible_job_id' in result
|
||||
assert 'started' in result
|
||||
jid = result['ansible_job_id']
|
||||
# no real chance of this op taking a while, but whatever
|
||||
time.sleep(5)
|
||||
# CLI will abstract this (when polling), but this is how it works internally
|
||||
result = self._run('async_status', [ "jid=%s" % jid ])
|
||||
# TODO: would be nice to have tests for supervisory process
|
||||
# killing job after X seconds
|
||||
assert 'finished' in result
|
||||
assert 'failed' not in result
|
||||
assert 'rc' in result
|
||||
assert 'stdout' in result
|
||||
assert result['ansible_job_id'] == jid
|
||||
|
||||
def test_service(self):
|
||||
# TODO: tests for the service module
|
||||
pass
|
||||
def test_fetch(self):
|
||||
input_ = self._get_test_file('sample.j2')
|
||||
output = os.path.join(self.stage_dir, '127.0.0.2', input_)
|
||||
result = self._run('fetch', [ "src=%s" % input_, "dest=%s" % self.stage_dir ])
|
||||
assert os.path.exists(output)
|
||||
assert open(input_).read() == open(output).read()
|
||||
|
||||
def test_yum(self):
|
||||
if not get_binary("yum"):
|
||||
raise SkipTest
|
||||
result = self._run('yum', [ "list=repos" ])
|
||||
assert 'failed' not in result
|
||||
|
||||
def test_git(self):
|
||||
# TODO: tests for the git module
|
||||
pass
|
||||
|
||||
def test_service(self):
|
||||
# TODO: tests for the service module
|
||||
pass
|
||||
|
||||
|
||||
|
||||
244
test/TestUtils.py
Normal file
244
test/TestUtils.py
Normal file
@ -0,0 +1,244 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import ansible.utils
|
||||
|
||||
class TestUtils(unittest.TestCase):
|
||||
|
||||
#####################################
|
||||
### varLookup function tests
|
||||
|
||||
def test_varLookup_list(self):
|
||||
vars = {
|
||||
'data': {
|
||||
'who': ['joe', 'jack', 'jeff']
|
||||
}
|
||||
}
|
||||
|
||||
res = ansible.utils.varLookup('data.who', vars)
|
||||
|
||||
assert sorted(res) == sorted(vars['data']['who'])
|
||||
|
||||
#####################################
|
||||
### varReplace function tests
|
||||
|
||||
def test_varReplace_simple(self):
|
||||
template = 'hello $who'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_varReplace_multiple(self):
|
||||
template = '$what $who'
|
||||
vars = {
|
||||
'what': 'hello',
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_varReplace_caps(self):
|
||||
template = 'hello $whoVar'
|
||||
vars = {
|
||||
'whoVar': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
print res
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_varReplace_middle(self):
|
||||
template = 'hello $who!'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world!'
|
||||
|
||||
def test_varReplace_alternative(self):
|
||||
template = 'hello ${who}'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_varReplace_almost_alternative(self):
|
||||
template = 'hello $who}'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world}'
|
||||
|
||||
def test_varReplace_almost_alternative2(self):
|
||||
template = 'hello ${who'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == template
|
||||
|
||||
def test_varReplace_alternative_greed(self):
|
||||
template = 'hello ${who} }'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world }'
|
||||
|
||||
def test_varReplace_notcomplex(self):
|
||||
template = 'hello $mydata.who'
|
||||
vars = {
|
||||
'data': {
|
||||
'who': 'world',
|
||||
},
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
print res
|
||||
assert res == template
|
||||
|
||||
def test_varReplace_nested(self):
|
||||
template = 'hello ${data.who}'
|
||||
vars = {
|
||||
'data': {
|
||||
'who': 'world'
|
||||
},
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_varReplace_nested_int(self):
|
||||
template = '$what ${data.who}'
|
||||
vars = {
|
||||
'data': {
|
||||
'who': 2
|
||||
},
|
||||
'what': 'hello',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello 2'
|
||||
|
||||
def test_varReplace_unicode(self):
|
||||
template = 'hello $who'
|
||||
vars = {
|
||||
'who': u'wórld',
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == u'hello wórld'
|
||||
|
||||
def test_varReplace_list(self):
|
||||
template = 'hello ${data[1]}'
|
||||
vars = {
|
||||
'data': [ 'no-one', 'world' ]
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_varReplace_invalid_list(self):
|
||||
template = 'hello ${data[1}'
|
||||
vars = {
|
||||
'data': [ 'no-one', 'world' ]
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == template
|
||||
|
||||
def test_varReplace_list_oob(self):
|
||||
template = 'hello ${data[2]}'
|
||||
vars = {
|
||||
'data': [ 'no-one', 'world' ]
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == template
|
||||
|
||||
def test_varReplace_list_nolist(self):
|
||||
template = 'hello ${data[1]}'
|
||||
vars = {
|
||||
'data': { 'no-one': 0, 'world': 1 }
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == template
|
||||
|
||||
def test_varReplace_nested_list(self):
|
||||
template = 'hello ${data[1].msg[0]}'
|
||||
vars = {
|
||||
'data': [ 'no-one', {'msg': [ 'world'] } ]
|
||||
}
|
||||
|
||||
res = ansible.utils.varReplace(template, vars)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
#####################################
|
||||
### Template function tests
|
||||
|
||||
def test_template_basic(self):
|
||||
template = 'hello {{ who }}'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.template(template, vars, {}, no_engine=False)
|
||||
|
||||
assert res == 'hello world'
|
||||
|
||||
def test_template_whitespace(self):
|
||||
template = 'hello {{ who }}\n'
|
||||
vars = {
|
||||
'who': 'world',
|
||||
}
|
||||
|
||||
res = ansible.utils.template(template, vars, {}, no_engine=False)
|
||||
|
||||
assert res == 'hello world\n'
|
||||
|
||||
def test_template_unicode(self):
|
||||
template = 'hello {{ who }}'
|
||||
vars = {
|
||||
'who': u'wórld',
|
||||
}
|
||||
|
||||
res = ansible.utils.template(template, vars, {}, no_engine=False)
|
||||
|
||||
assert res == u'hello wórld'
|
||||
|
||||
#####################################
|
||||
### key-value parsing
|
||||
|
||||
def test_parse_kv_basic(self):
|
||||
assert (ansible.utils.parse_kv('a=simple b="with space" c="this=that"') ==
|
||||
{'a': 'simple', 'b': 'with space', 'c': 'this=that'})
|
||||
@ -1,3 +1,4 @@
|
||||
---
|
||||
duck: quack
|
||||
cow: moo
|
||||
extguard: " '$favcolor' == 'blue' "
|
||||
|
||||
76
test/complex_hosts
Normal file
76
test/complex_hosts
Normal file
@ -0,0 +1,76 @@
|
||||
# order of groups, children, and vars is not signficant
|
||||
# so this example mixes them up for maximum testing
|
||||
|
||||
[nc:children]
|
||||
rtp
|
||||
triangle
|
||||
|
||||
[eastcoast:children]
|
||||
nc
|
||||
florida
|
||||
|
||||
[us:children]
|
||||
eastcoast
|
||||
|
||||
[redundantgroup]
|
||||
rtp_a
|
||||
|
||||
[redundantgroup2]
|
||||
rtp_a
|
||||
|
||||
[redundantgroup3:children]
|
||||
rtp
|
||||
|
||||
[redundantgroup:vars]
|
||||
rga=1
|
||||
|
||||
[redundantgroup2:vars]
|
||||
rgb=2
|
||||
|
||||
[redundantgroup3:vars]
|
||||
rgc=3
|
||||
|
||||
[nc:vars]
|
||||
b=10000
|
||||
c=10001
|
||||
d=10002
|
||||
|
||||
[rtp]
|
||||
rtp_a
|
||||
rtp_b
|
||||
rtb_c
|
||||
|
||||
[rtp:vars]
|
||||
a=1
|
||||
b=2
|
||||
c=3
|
||||
|
||||
[triangle]
|
||||
tri_a
|
||||
tri_b
|
||||
tri_c
|
||||
|
||||
[triangle:vars]
|
||||
a=11
|
||||
b=12
|
||||
c=13
|
||||
|
||||
[florida]
|
||||
orlando
|
||||
miami
|
||||
|
||||
[florida:vars]
|
||||
a=100
|
||||
b=101
|
||||
c=102
|
||||
|
||||
|
||||
[eastcoast:vars]
|
||||
b=100000
|
||||
c=100001
|
||||
d=100002
|
||||
|
||||
[us:vars]
|
||||
c=1000000
|
||||
|
||||
|
||||
@ -1,71 +0,0 @@
|
||||
---
|
||||
# this is an annotated example of some features available in playbooks
|
||||
# it shows how to make sure packages are updated, how to make sure
|
||||
# services are running, and how to template files. It also demos
|
||||
# change handlers that can restart things (or trigger other actions)
|
||||
# when resources change. For more advanced examples, see example2.yml
|
||||
|
||||
# on all hosts, run as the user root...
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
|
||||
# make these variables available inside of templates
|
||||
# for when we use the 'template' action/module later on...
|
||||
|
||||
vars:
|
||||
http_port: 80
|
||||
max_clients: 200
|
||||
|
||||
# define the tasks that are part of this play...
|
||||
|
||||
tasks:
|
||||
|
||||
# task #1 is to run an arbitrary command
|
||||
# we'll simulate a long running task, wait for up to 45 seconds, poll every 5
|
||||
# obviously this does nothing useful but you get the idea
|
||||
|
||||
- name: longrunner
|
||||
action: command /bin/sleep 15
|
||||
async: 45
|
||||
poll: 5
|
||||
|
||||
# let's demo file operations.
|
||||
#
|
||||
# We can 'copy' files or 'template' them instead, using jinja2
|
||||
# as the templating engine. This is done using the variables
|
||||
# from the vars section above mixed in with variables bubbled up
|
||||
# automatically from tools like facter and ohai. 'copy'
|
||||
# works just like 'template' but does not do variable subsitution.
|
||||
#
|
||||
# If and only if the file changes, restart apache at the very
|
||||
# end of the playbook run
|
||||
|
||||
- name: write some_random_foo configuration
|
||||
action: template src=templates/foo.j2 dest=/etc/some_random_foo.conf
|
||||
notify:
|
||||
- restart apache
|
||||
|
||||
# make sure httpd is installed at the latest version
|
||||
|
||||
- name: install httpd
|
||||
action: yum pkg=httpd state=latest
|
||||
|
||||
# make sure httpd is running
|
||||
|
||||
- name: httpd start
|
||||
action: service name=httpd state=running
|
||||
|
||||
# handlers are only run when things change, at the very end of each
|
||||
# play. Let's define some. The names are significant and must
|
||||
# match the 'notify' sections above
|
||||
|
||||
handlers:
|
||||
|
||||
# this particular handler is run when some_random_foo.conf
|
||||
# is changed, and only then
|
||||
|
||||
- name: restart apache
|
||||
action: service name=httpd state=restarted
|
||||
|
||||
|
||||
@ -1,71 +0,0 @@
|
||||
---
|
||||
# this is an annotated example of some features available in playbooks
|
||||
# it shows how to make sure packages are updated, how to make sure
|
||||
# services are running, and how to template files. It also demos
|
||||
# change handlers that can restart things (or trigger other actions)
|
||||
# when resources change. For more advanced examples, see example2.yml
|
||||
|
||||
# on all hosts, run as the user root...
|
||||
|
||||
- hosts: all
|
||||
user: root
|
||||
|
||||
# make these variables available inside of templates
|
||||
# for when we use the 'template' action/module later on...
|
||||
|
||||
vars:
|
||||
http_port: 80
|
||||
max_clients: 200
|
||||
|
||||
# define the tasks that are part of this play...
|
||||
|
||||
tasks:
|
||||
|
||||
# task #1 is to run an arbitrary command
|
||||
# we'll simulate a long running task, wait for up to 45 seconds, poll every 5
|
||||
# obviously this does nothing useful but you get the idea
|
||||
|
||||
- name: longrunner
|
||||
action: command /bin/sleep 15
|
||||
async: 45
|
||||
poll: 5
|
||||
|
||||
# let's demo file operations.
|
||||
#
|
||||
# We can 'copy' files or 'template' them instead, using jinja2
|
||||
# as the templating engine. This is done using the variables
|
||||
# from the vars section above mixed in with variables bubbled up
|
||||
# automatically from tools like facter and ohai. 'copy'
|
||||
# works just like 'template' but does not do variable subsitution.
|
||||
#
|
||||
# If and only if the file changes, restart apache at the very
|
||||
# end of the playbook run
|
||||
|
||||
- name: write some_random_foo configuration
|
||||
action: template src=templates/foo.j2 dest=/etc/some_random_foo.conf
|
||||
notify:
|
||||
- restart apache
|
||||
|
||||
# make sure httpd is installed at the latest version
|
||||
|
||||
- name: install httpd
|
||||
action: yum pkg=httpd state=latest
|
||||
|
||||
# make sure httpd is running
|
||||
|
||||
- name: httpd start
|
||||
action: service name=httpd state=running
|
||||
|
||||
# handlers are only run when things change, at the very end of each
|
||||
# play. Let's define some. The names are significant and must
|
||||
# match the 'notify' sections above
|
||||
|
||||
handlers:
|
||||
|
||||
# this particular handler is run when some_random_foo.conf
|
||||
# is changed, and only then
|
||||
|
||||
- name: restart apache
|
||||
action: service name=httpd state=restarted
|
||||
|
||||
|
||||
@ -6,7 +6,9 @@
|
||||
moon: titan
|
||||
moon2: enceladus
|
||||
|
||||
- zeus
|
||||
- host: zeus
|
||||
vars:
|
||||
- ansible_ssh_port: 3001
|
||||
|
||||
- group: greek
|
||||
hosts:
|
||||
|
||||
Reference in New Issue
Block a user