2014-01-04 18:31:44 +00:00
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
2012-02-24 04:28:58 +00:00
#
2012-02-29 00:08:09 +00:00
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
2012-03-03 03:03:03 +00:00
2012-02-24 04:28:58 +00:00
import multiprocessing
2012-02-27 05:43:02 +00:00
import signal
2012-02-24 04:28:58 +00:00
import os
2012-04-10 23:27:19 +00:00
import pwd
2012-02-28 05:45:37 +00:00
import Queue
2012-03-03 17:25:56 +00:00
import random
2012-03-14 00:59:05 +00:00
import traceback
2012-03-14 04:34:00 +00:00
import tempfile
2012-04-26 18:34:49 +00:00
import time
2012-07-15 14:57:22 +00:00
import collections
2012-08-09 01:19:20 +00:00
import socket
2012-09-27 03:50:54 +00:00
import base64
2012-10-11 11:43:56 +00:00
import sys
2013-02-17 20:01:49 +00:00
import pipes
2013-06-18 17:24:30 +00:00
import jinja2
2013-07-04 20:47:17 +00:00
import subprocess
2014-04-03 16:02:40 +00:00
import getpass
2012-03-13 03:11:54 +00:00
2012-08-07 00:07:02 +00:00
import ansible . constants as C
2012-04-13 12:39:54 +00:00
import ansible . inventory
2012-03-18 21:04:07 +00:00
from ansible import utils
2013-04-10 21:52:35 +00:00
from ansible . utils import template
2013-08-20 21:09:44 +00:00
from ansible . utils import check_conditional
2014-01-10 20:08:45 +00:00
from ansible . utils import string_functions
2012-03-18 21:16:12 +00:00
from ansible import errors
2012-07-18 02:33:36 +00:00
from ansible import module_common
2012-06-01 01:44:30 +00:00
import poller
import connection
2012-08-18 13:30:33 +00:00
from return_data import ReturnData
2012-08-10 04:25:13 +00:00
from ansible . callbacks import DefaultRunnerCallbacks , vv
2013-10-31 20:52:37 +00:00
from ansible . module_common import ModuleReplacer
2014-08-27 16:51:03 +00:00
from ansible . module_utils . splitter import split_args , unquote
2014-08-11 16:22:47 +00:00
from ansible . cache import FactCache
from ansible . utils import update_hash
2013-10-31 20:52:37 +00:00
module_replacer = ModuleReplacer ( strip_comments = False )
2012-08-07 00:07:02 +00:00
2014-08-05 17:20:10 +00:00
try :
2014-11-07 05:28:04 +00:00
from hashlib import sha1
2014-08-05 17:20:10 +00:00
except ImportError :
2014-11-07 05:28:04 +00:00
from sha import sha as sha1
2014-08-05 17:20:10 +00:00
2012-03-29 00:32:04 +00:00
HAS_ATFORK = True
try :
2014-10-06 20:05:52 +00:00
from Crypto . Random import atfork
2012-03-29 00:32:04 +00:00
except ImportError :
2014-10-06 20:05:52 +00:00
HAS_ATFORK = False
2012-03-14 23:57:56 +00:00
2012-10-23 12:04:32 +00:00
multiprocessing_runner = None
2014-08-11 16:22:47 +00:00
2013-07-04 22:17:45 +00:00
OUTPUT_LOCKFILE = tempfile . TemporaryFile ( )
PROCESS_LOCKFILE = tempfile . TemporaryFile ( )
2012-09-18 12:41:27 +00:00
2012-03-03 03:03:03 +00:00
################################################
2012-02-24 04:28:58 +00:00
2014-02-08 01:38:20 +00:00
def _executor_hook ( job_queue , result_queue , new_stdin ) :
2012-10-26 22:11:38 +00:00
2012-10-23 12:19:15 +00:00
# attempt workaround of https://github.com/newsapps/beeswithmachineguns/issues/17
# this function also not present in CentOS 6
2014-02-08 01:38:20 +00:00
if HAS_ATFORK :
2012-10-23 12:19:15 +00:00
atfork ( )
2012-10-26 22:11:38 +00:00
2014-02-08 01:38:20 +00:00
signal . signal ( signal . SIGINT , signal . SIG_IGN )
while not job_queue . empty ( ) :
try :
host = job_queue . get ( block = False )
return_data = multiprocessing_runner . _executor ( host , new_stdin )
result_queue . put ( return_data )
except Queue . Empty :
pass
except :
traceback . print_exc ( )
2012-10-23 12:19:15 +00:00
2013-09-07 01:18:41 +00:00
class HostVars ( dict ) :
2014-04-01 14:48:14 +00:00
''' A special view of vars_cache that adds values from the inventory when needed. '''
2012-10-13 00:07:05 +00:00
2014-04-04 17:05:33 +00:00
def __init__ ( self , vars_cache , inventory , vault_password = None ) :
2014-04-01 14:48:14 +00:00
self . vars_cache = vars_cache
2012-10-08 18:26:58 +00:00
self . inventory = inventory
2014-08-11 16:22:47 +00:00
self . lookup = { }
2014-04-01 14:48:14 +00:00
self . update ( vars_cache )
2014-04-04 17:05:33 +00:00
self . vault_password = vault_password
2013-09-06 04:04:16 +00:00
2012-10-08 18:26:58 +00:00
def __getitem__ ( self , host ) :
2013-09-07 01:18:41 +00:00
if host not in self . lookup :
2014-05-27 23:38:03 +00:00
result = self . inventory . get_variables ( host , vault_password = self . vault_password ) . copy ( )
2014-09-17 16:03:36 +00:00
result . update ( self . vars_cache . get ( host , { } ) )
2014-09-11 20:01:34 +00:00
self . lookup [ host ] = template . template ( ' . ' , result , self . vars_cache )
2012-10-13 00:07:05 +00:00
return self . lookup [ host ]
2012-10-08 18:26:58 +00:00
2013-02-07 17:40:41 +00:00
2012-02-24 04:28:58 +00:00
class Runner ( object ) :
2012-07-15 14:22:15 +00:00
''' core API interface to ansible '''
2012-02-24 04:28:58 +00:00
2012-07-21 20:51:31 +00:00
# see bin/ansible for how this is used...
2012-03-22 03:39:09 +00:00
2012-08-07 00:07:02 +00:00
def __init__ ( self ,
2012-07-21 20:51:31 +00:00
host_list = C . DEFAULT_HOST_LIST , # ex: /etc/ansible/hosts, legacy usage
2012-11-18 17:37:30 +00:00
module_path = None , # ex: /usr/share/ansible
2012-07-21 20:51:31 +00:00
module_name = C . DEFAULT_MODULE_NAME , # ex: copy
module_args = C . DEFAULT_MODULE_ARGS , # ex: "src=/tmp/a dest=/tmp/b"
forks = C . DEFAULT_FORKS , # parallelism level
2012-07-24 00:06:18 +00:00
timeout = C . DEFAULT_TIMEOUT , # SSH timeout
2012-07-21 20:51:31 +00:00
pattern = C . DEFAULT_PATTERN , # which hosts? ex: 'all', 'acme.example.org'
remote_user = C . DEFAULT_REMOTE_USER , # ex: 'username'
remote_pass = C . DEFAULT_REMOTE_PASS , # ex: 'password123' or None if using key
2012-10-08 23:03:37 +00:00
remote_port = None , # if SSH on different ports
2012-08-07 00:07:02 +00:00
private_key_file = C . DEFAULT_PRIVATE_KEY_FILE , # if not using keys/passwords
2012-07-21 20:51:31 +00:00
background = 0 , # async poll every X seconds, else 0 for non-async
basedir = None , # directory of playbook, if applicable
setup_cache = None , # used to share fact data w/ other tasks
2014-04-01 14:48:14 +00:00
vars_cache = None , # used to store variables about hosts
2012-07-21 20:51:31 +00:00
transport = C . DEFAULT_TRANSPORT , # 'ssh', 'paramiko', 'local'
conditional = ' True ' , # run only if this fact expression evals to true
callbacks = None , # used for output
2012-08-07 00:07:02 +00:00
module_vars = None , # a playbooks internals thing
2014-11-17 21:30:22 +00:00
play_vars = None , #
play_file_vars = None , #
role_vars = None , #
2014-11-20 18:20:32 +00:00
role_params = None , #
2014-11-17 21:30:22 +00:00
default_vars = None , #
2014-08-15 20:57:02 +00:00
extra_vars = None , # extra vars specified with he playbook(s)
2012-07-21 20:51:31 +00:00
is_playbook = False , # running from playbook or not?
2012-08-11 18:05:24 +00:00
inventory = None , # reference to Inventory object
2013-02-04 00:46:25 +00:00
subset = None , # subset pattern
2013-02-08 03:51:33 +00:00
check = False , # don't make any changes, just try to probe for potential changes
2013-02-10 18:05:58 +00:00
diff = False , # whether to show diffs for template files that change
2013-02-17 20:01:49 +00:00
environment = None , # environment variables (as dict) to use inside the command
2013-06-18 17:24:30 +00:00
complex_args = None , # structured data in addition to module_args, must be a dict
2013-08-11 05:41:18 +00:00
error_on_undefined_vars = C . DEFAULT_UNDEFINED_VAR_BEHAVIOR , # ex. False
2013-08-30 18:24:24 +00:00
accelerate = False , # use accelerated connection
2013-11-04 22:20:03 +00:00
accelerate_ipv6 = False , # accelerated connection w/ IPv6
2013-08-30 18:24:24 +00:00
accelerate_port = None , # port to use with accelerated connection
2014-02-11 17:03:11 +00:00
vault_pass = None ,
2014-01-07 04:13:39 +00:00
run_hosts = None , # an optional list of pre-calculated hosts to run on
2014-01-31 22:09:10 +00:00
no_log = False , # option to enable/disable logging for a given task
2014-05-15 15:47:17 +00:00
run_once = False , # option to enable/disable host bypass loop for a given task
2014-11-24 21:36:31 +00:00
become = False , # whether to run privelege escalation or not
become_method = C . DEFAULT_BECOME_METHOD ,
become_user = C . DEFAULT_BECOME_USER , # ex: 'root'
become_pass = C . DEFAULT_BECOME_PASS , # ex: 'password123' or None
become_exe = C . DEFAULT_BECOME_EXE , # ex: /usr/local/bin/sudo
2012-07-21 20:51:31 +00:00
) :
2013-07-04 22:17:45 +00:00
# used to lock multiprocess inputs and outputs at various levels
self . output_lockfile = OUTPUT_LOCKFILE
self . process_lockfile = PROCESS_LOCKFILE
2013-07-04 18:05:41 +00:00
2013-02-17 20:01:49 +00:00
if not complex_args :
complex_args = { }
2012-07-21 20:51:31 +00:00
# storage & defaults
2013-02-04 00:46:25 +00:00
self . check = check
2013-02-08 03:51:33 +00:00
self . diff = diff
2014-08-11 16:22:47 +00:00
self . setup_cache = utils . default ( setup_cache , lambda : ansible . cache . FactCache ( ) )
2014-04-01 14:48:14 +00:00
self . vars_cache = utils . default ( vars_cache , lambda : collections . defaultdict ( dict ) )
2012-07-21 20:51:31 +00:00
self . basedir = utils . default ( basedir , lambda : os . getcwd ( ) )
2012-08-09 01:13:31 +00:00
self . callbacks = utils . default ( callbacks , lambda : DefaultRunnerCallbacks ( ) )
2012-07-21 20:51:31 +00:00
self . generated_jid = str ( random . randint ( 0 , 999999999999 ) )
self . transport = transport
self . inventory = utils . default ( inventory , lambda : ansible . inventory . Inventory ( host_list ) )
2012-08-11 18:05:24 +00:00
2012-07-21 20:51:31 +00:00
self . module_vars = utils . default ( module_vars , lambda : { } )
2014-11-17 21:30:22 +00:00
self . play_vars = utils . default ( play_vars , lambda : { } )
self . play_file_vars = utils . default ( play_file_vars , lambda : { } )
self . role_vars = utils . default ( role_vars , lambda : { } )
2014-11-20 18:20:32 +00:00
self . role_params = utils . default ( role_params , lambda : { } )
2013-08-29 22:21:28 +00:00
self . default_vars = utils . default ( default_vars , lambda : { } )
2014-08-15 20:57:02 +00:00
self . extra_vars = utils . default ( extra_vars , lambda : { } )
2013-08-20 21:09:44 +00:00
self . always_run = None
2014-06-17 20:15:18 +00:00
self . connector = connection . Connector ( self )
2012-07-15 15:54:39 +00:00
self . conditional = conditional
2014-09-17 01:51:00 +00:00
self . delegate_to = None
2012-07-15 15:54:39 +00:00
self . module_name = module_name
self . forks = int ( forks )
self . pattern = pattern
self . module_args = module_args
self . timeout = timeout
self . remote_user = remote_user
self . remote_pass = remote_pass
self . remote_port = remote_port
2012-05-14 20:14:38 +00:00
self . private_key_file = private_key_file
2012-07-15 15:54:39 +00:00
self . background = background
2014-11-24 21:36:31 +00:00
self . become = become
self . become_method = become_method
self . become_user_var = become_user
self . become_user = None
self . become_pass = become_pass
self . become_exe = become_exe
2012-07-15 15:54:39 +00:00
self . is_playbook = is_playbook
2013-02-10 18:05:58 +00:00
self . environment = environment
2013-02-17 20:01:49 +00:00
self . complex_args = complex_args
2013-06-18 17:24:30 +00:00
self . error_on_undefined_vars = error_on_undefined_vars
2013-08-11 05:41:18 +00:00
self . accelerate = accelerate
2013-08-27 20:25:54 +00:00
self . accelerate_port = accelerate_port
2013-11-04 22:20:03 +00:00
self . accelerate_ipv6 = accelerate_ipv6
2013-03-26 02:47:06 +00:00
self . callbacks . runner = self
2014-11-07 05:28:04 +00:00
self . omit_token = ' __omit_place_holder__ %s ' % sha1 ( os . urandom ( 64 ) ) . hexdigest ( )
2014-02-11 17:03:11 +00:00
self . vault_pass = vault_pass
2014-01-31 22:09:10 +00:00
self . no_log = no_log
2014-05-15 15:47:17 +00:00
self . run_once = run_once
2013-03-26 02:47:06 +00:00
2014-06-17 20:59:02 +00:00
if self . transport == ' smart ' :
2014-09-26 00:22:35 +00:00
# If the transport is 'smart', check to see if certain conditions
# would prevent us from using ssh, and fallback to paramiko.
2013-08-11 05:41:18 +00:00
# 'smart' is the default since 1.2.1/1.3
2014-09-26 00:22:35 +00:00
self . transport = " ssh "
2014-11-03 20:32:15 +00:00
if sys . platform . startswith ( ' darwin ' ) and self . remote_pass :
# due to a current bug in sshpass on OSX, which can trigger
# a kernel panic even for non-privileged users, we revert to
# paramiko on that OS when a SSH password is specified
2013-07-04 20:47:17 +00:00
self . transport = " paramiko "
else :
2014-09-26 00:22:35 +00:00
# see if SSH can support ControlPersist if not use paramiko
cmd = subprocess . Popen ( [ ' ssh ' , ' -o ' , ' ControlPersist ' ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
( out , err ) = cmd . communicate ( )
if " Bad configuration option " in err :
self . transport = " paramiko "
2013-07-04 20:47:17 +00:00
2014-02-27 16:29:38 +00:00
# save the original transport, in case it gets
# changed later via options like accelerate
self . original_transport = self . transport
2013-07-04 20:47:17 +00:00
2012-07-21 20:51:31 +00:00
# misc housekeeping
2012-08-11 18:05:24 +00:00
if subset and self . inventory . _subset is None :
# don't override subset when passed from playbook
self . inventory . subset ( subset )
2014-01-07 04:13:39 +00:00
# If we get a pre-built list of hosts to run on, from say a playbook, use them.
# Also where we will store the hosts to run on once discovered
self . run_hosts = run_hosts
2012-07-21 20:51:31 +00:00
if self . transport == ' local ' :
self . remote_user = pwd . getpwuid ( os . geteuid ( ) ) [ 0 ]
2012-08-07 00:07:02 +00:00
2012-11-18 17:37:30 +00:00
if module_path is not None :
for i in module_path . split ( os . pathsep ) :
utils . plugins . module_finder . add_directory ( i )
2012-11-18 17:36:37 +00:00
utils . plugins . push_basedir ( self . basedir )
2012-07-21 20:51:31 +00:00
# ensure we are using unique tmp paths
2012-03-03 17:25:56 +00:00
random . seed ( )
2014-10-22 15:53:58 +00:00
# *****************************************************
def _complex_args_hack ( self , complex_args , module_args ) :
"""
ansible - playbook both allows specifying key = value string arguments and complex arguments
however not all modules use our python common module system and cannot
access these . An example might be a Bash module . This hack allows users to still pass " args "
as a hash of simple scalars to those arguments and is short term . We could technically
just feed JSON to the module , but that makes it hard on Bash consumers . The way this is implemented
it does mean values in ' args ' have LOWER priority than those on the key = value line , allowing
args to provide yet another way to have pluggable defaults .
"""
if complex_args is None :
return module_args
if not isinstance ( complex_args , dict ) :
raise errors . AnsibleError ( " complex arguments are not a dictionary: %s " % complex_args )
for ( k , v ) in complex_args . iteritems ( ) :
if isinstance ( v , basestring ) :
module_args = " %s = %s %s " % ( k , pipes . quote ( v ) , module_args )
return module_args
2012-03-22 03:39:09 +00:00
2012-03-14 00:59:05 +00:00
# *****************************************************
2012-04-19 02:19:25 +00:00
def _transfer_str ( self , conn , tmp , name , data ) :
''' transfer string to remote file '''
2012-03-20 23:55:04 +00:00
2012-04-19 02:19:25 +00:00
if type ( data ) == dict :
2012-07-15 14:12:49 +00:00
data = utils . jsonify ( data )
2012-03-31 02:28:10 +00:00
2012-04-19 02:19:25 +00:00
afd , afile = tempfile . mkstemp ( )
afo = os . fdopen ( afd , ' w ' )
2012-10-13 00:07:05 +00:00
try :
2013-03-09 03:27:45 +00:00
if not isinstance ( data , unicode ) :
#ensure the data is valid UTF-8
data . decode ( ' utf-8 ' )
else :
data = data . encode ( ' utf-8 ' )
afo . write ( data )
2012-10-13 00:07:05 +00:00
except :
raise errors . AnsibleError ( " failure encoding into utf-8 " )
2012-04-19 02:19:25 +00:00
afo . flush ( )
afo . close ( )
2012-03-31 02:28:10 +00:00
2014-06-17 20:15:18 +00:00
remote = conn . shell . join_path ( tmp , name )
2012-07-15 16:29:53 +00:00
try :
conn . put_file ( afile , remote )
finally :
os . unlink ( afile )
2012-04-19 02:19:25 +00:00
return remote
2012-03-06 03:23:56 +00:00
2012-03-22 03:39:09 +00:00
# *****************************************************
2012-07-14 23:18:33 +00:00
2014-06-17 21:04:50 +00:00
def _compute_environment_string ( self , conn , inject = None ) :
2013-02-10 18:05:58 +00:00
''' what environment variables to use when running the command? '''
2014-06-17 20:15:18 +00:00
enviro = { }
2014-05-01 15:34:53 +00:00
if self . environment :
enviro = template . template ( self . basedir , self . environment , inject , convert_bare = True )
enviro = utils . safe_eval ( enviro )
if type ( enviro ) != dict :
raise errors . AnsibleError ( " environment must be a dictionary, received %s " % enviro )
2014-06-17 20:15:18 +00:00
return conn . shell . env_prefix ( * * enviro )
2013-02-10 18:05:58 +00:00
# *****************************************************
2014-09-17 01:51:00 +00:00
def _compute_delegate ( self , password , remote_inject ) :
2014-02-03 21:59:30 +00:00
""" Build a dictionary of all attributes for the delegate host """
2014-02-21 20:54:09 +00:00
2014-02-03 21:59:30 +00:00
delegate = { }
2014-02-27 17:06:34 +00:00
# allow delegated host to be templated
2014-02-03 21:59:30 +00:00
delegate [ ' inject ' ] = remote_inject . copy ( )
# set any interpreters
interpreters = [ ]
for i in delegate [ ' inject ' ] :
if i . startswith ( " ansible_ " ) and i . endswith ( " _interpreter " ) :
interpreters . append ( i )
for i in interpreters :
del delegate [ ' inject ' ] [ i ]
port = C . DEFAULT_REMOTE_PORT
2014-05-03 16:40:05 +00:00
# get the vars for the delegate by its name
2014-02-25 16:18:06 +00:00
try :
2014-09-17 01:51:00 +00:00
this_info = delegate [ ' inject ' ] [ ' hostvars ' ] [ self . delegate_to ]
2014-02-25 16:18:06 +00:00
except :
2014-02-21 20:54:09 +00:00
# make sure the inject is empty for non-inventory hosts
this_info = { }
2014-02-03 21:59:30 +00:00
2014-08-11 16:22:47 +00:00
# get the real ssh_address for the delegate
2014-02-27 17:06:34 +00:00
# and allow ansible_ssh_host to be templated
2014-09-17 01:51:00 +00:00
delegate [ ' ssh_host ' ] = template . template (
self . basedir ,
this_info . get ( ' ansible_ssh_host ' , self . delegate_to ) ,
this_info ,
fail_on_undefined = True
)
2014-02-03 21:59:30 +00:00
delegate [ ' port ' ] = this_info . get ( ' ansible_ssh_port ' , port )
2014-09-17 01:51:00 +00:00
delegate [ ' user ' ] = self . _compute_delegate_user ( self . delegate_to , delegate [ ' inject ' ] )
2014-02-03 21:59:30 +00:00
delegate [ ' pass ' ] = this_info . get ( ' ansible_ssh_pass ' , password )
2014-09-17 01:51:00 +00:00
delegate [ ' private_key_file ' ] = this_info . get ( ' ansible_ssh_private_key_file ' , self . private_key_file )
2014-02-03 21:59:30 +00:00
delegate [ ' transport ' ] = this_info . get ( ' ansible_connection ' , self . transport )
2014-11-24 21:36:31 +00:00
delegate [ ' become_pass ' ] = this_info . get ( ' ansible_become_pass ' , this_info . get ( ' ansible_ssh_pass ' , self . become_pass ) )
2014-02-03 21:59:30 +00:00
2014-04-17 23:48:02 +00:00
# Last chance to get private_key_file from global variables.
2014-05-03 16:40:05 +00:00
# this is useful if delegated host is not defined in the inventory
2014-04-17 23:48:02 +00:00
if delegate [ ' private_key_file ' ] is None :
2014-09-17 01:51:00 +00:00
delegate [ ' private_key_file ' ] = remote_inject . get ( ' ansible_ssh_private_key_file ' , None )
2014-04-17 23:48:02 +00:00
2014-02-03 21:59:30 +00:00
if delegate [ ' private_key_file ' ] is not None :
delegate [ ' private_key_file ' ] = os . path . expanduser ( delegate [ ' private_key_file ' ] )
for i in this_info :
if i . startswith ( " ansible_ " ) and i . endswith ( " _interpreter " ) :
delegate [ ' inject ' ] [ i ] = this_info [ i ]
return delegate
def _compute_delegate_user ( self , host , inject ) :
2014-05-03 16:40:05 +00:00
""" Calculate the remote user based on an order of preference """
2014-02-03 21:59:30 +00:00
# inventory > playbook > original_host
actual_user = inject . get ( ' ansible_ssh_user ' , self . remote_user )
thisuser = None
2014-12-03 12:26:42 +00:00
try :
if host in inject [ ' hostvars ' ] :
if inject [ ' hostvars ' ] [ host ] . get ( ' ansible_ssh_user ' ) :
# user for delegate host in inventory
thisuser = inject [ ' hostvars ' ] [ host ] . get ( ' ansible_ssh_user ' )
2015-04-14 18:41:31 +00:00
else :
# look up the variables for the host directly from inventory
host_vars = self . inventory . get_variables ( host , vault_password = self . vault_pass )
if ' ansible_ssh_user ' in host_vars :
thisuser = host_vars [ ' ansible_ssh_user ' ]
2014-12-03 19:19:11 +00:00
except errors . AnsibleError , e :
2014-12-03 12:26:42 +00:00
# the hostname was not found in the inventory, so
# we just ignore this and try the next method
pass
2014-02-21 20:54:09 +00:00
2014-02-03 21:59:30 +00:00
if thisuser is None and self . remote_user :
# user defined by play/runner
thisuser = self . remote_user
if thisuser is not None :
actual_user = thisuser
else :
# fallback to the inventory user of the play host
#actual_user = inject.get('ansible_ssh_user', actual_user)
actual_user = inject . get ( ' ansible_ssh_user ' , self . remote_user )
return actual_user
2014-07-24 02:37:57 +00:00
def _count_module_args ( self , args , allow_dupes = False ) :
2014-07-21 16:20:49 +00:00
'''
Count the number of k = v pairs in the supplied module args . This is
basically a specialized version of parse_kv ( ) from utils with a few
minor changes .
'''
options = { }
if args is not None :
try :
2014-07-24 18:57:35 +00:00
vargs = split_args ( args )
except Exception , e :
if " unbalanced jinja2 block or quotes " in str ( e ) :
2014-07-21 16:20:49 +00:00
raise errors . AnsibleError ( " error parsing argument string ' %s ' , try quoting the entire line. " % args )
else :
raise
for x in vargs :
2014-07-24 02:37:57 +00:00
quoted = x . startswith ( ' " ' ) and x . endswith ( ' " ' ) or x . startswith ( " ' " ) and x . endswith ( " ' " )
if " = " in x and not quoted :
2014-07-21 16:20:49 +00:00
k , v = x . split ( " = " , 1 )
2014-07-24 02:37:57 +00:00
is_shell_module = self . module_name in ( ' command ' , ' shell ' )
is_shell_param = k in ( ' creates ' , ' removes ' , ' chdir ' , ' executable ' )
if k in options and not allow_dupes :
if not ( is_shell_module and not is_shell_param ) :
raise errors . AnsibleError ( " a duplicate parameter was found in the argument string ( %s ) " % k )
if is_shell_module and is_shell_param or not is_shell_module :
options [ k ] = v
2014-07-21 16:20:49 +00:00
return len ( options )
2014-02-03 21:59:30 +00:00
# *****************************************************
2012-08-07 00:07:02 +00:00
def _execute_module ( self , conn , tmp , module_name , args ,
2014-02-04 18:44:10 +00:00
async_jid = None , async_module = None , async_limit = None , inject = None , persist_files = False , complex_args = None , delete_remote_tmp = True ) :
2012-07-14 23:18:33 +00:00
2013-12-11 09:55:56 +00:00
''' transfer and run a module along with its arguments on the remote side '''
2012-03-22 03:39:09 +00:00
2012-09-27 03:50:54 +00:00
# hack to support fireball mode
if module_name == ' fireball ' :
2012-10-08 23:03:37 +00:00
args = " %s password= %s " % ( args , base64 . b64encode ( str ( utils . key_for_hostname ( conn . host ) ) ) )
if ' port ' not in args :
args + = " port= %s " % C . ZEROMQ_PORT
2012-09-27 03:50:54 +00:00
2013-12-11 09:55:56 +00:00
(
module_style ,
shebang ,
module_data
) = self . _configure_module ( conn , module_name , args , inject , complex_args )
# a remote tmp path may be necessary and not already created
if self . _late_needs_tmp_path ( conn , tmp , module_style ) :
tmp = self . _make_tmp_path ( conn )
2014-06-17 20:15:18 +00:00
remote_module_path = conn . shell . join_path ( tmp , module_name )
2013-12-11 09:55:56 +00:00
if ( module_style != ' new '
or async_jid is not None
2014-01-15 22:01:03 +00:00
or not conn . has_pipelining
2014-01-16 18:40:28 +00:00
or not C . ANSIBLE_SSH_PIPELINING
2014-01-21 01:19:03 +00:00
or C . DEFAULT_KEEP_REMOTE_FILES
2014-11-24 21:36:31 +00:00
or self . become_method == ' su ' ) :
2013-12-11 09:55:56 +00:00
self . _transfer_str ( conn , tmp , module_name , module_data )
2012-10-21 02:51:36 +00:00
2014-06-17 20:15:18 +00:00
environment_string = self . _compute_environment_string ( conn , inject )
2013-02-10 18:05:58 +00:00
2014-11-24 21:36:31 +00:00
if " tmp " in tmp and ( self . become and self . become_user != ' root ' ) :
# deal with possible umask issues once you become another user
2014-06-23 10:09:08 +00:00
self . _remote_chmod ( conn , ' a+r ' , remote_module_path , tmp )
2012-04-11 00:58:40 +00:00
2012-07-23 23:14:37 +00:00
cmd = " "
2013-12-11 09:55:56 +00:00
in_data = None
2013-04-24 22:32:53 +00:00
if module_style != ' new ' :
2013-02-04 00:46:25 +00:00
if ' CHECKMODE=True ' in args :
# if module isn't using AnsibleModuleCommon infrastructure we can't be certain it knows how to
# do --check mode, so to be safe we will not run it.
2013-12-03 21:42:34 +00:00
return ReturnData ( conn = conn , result = dict ( skipped = True , msg = " cannot yet run check mode against old-style modules " ) )
2014-01-31 22:09:10 +00:00
elif ' NO_LOG ' in args :
return ReturnData ( conn = conn , result = dict ( skipped = True , msg = " cannot use no_log: with old-style modules " ) )
2013-02-04 00:46:25 +00:00
2013-04-10 21:52:35 +00:00
args = template . template ( self . basedir , args , inject )
2013-04-24 22:32:53 +00:00
# decide whether we need to transfer JSON or key=value
argsfile = None
if module_style == ' non_native_want_json ' :
if complex_args :
complex_args . update ( utils . parse_kv ( args ) )
argsfile = self . _transfer_str ( conn , tmp , ' arguments ' , utils . jsonify ( complex_args ) )
else :
argsfile = self . _transfer_str ( conn , tmp , ' arguments ' , utils . jsonify ( utils . parse_kv ( args ) ) )
else :
argsfile = self . _transfer_str ( conn , tmp , ' arguments ' , args )
2014-11-24 21:36:31 +00:00
if self . become and self . become_user != ' root ' :
# deal with possible umask issues once become another user
2014-06-23 10:09:08 +00:00
self . _remote_chmod ( conn , ' a+r ' , argsfile , tmp )
2013-10-16 01:15:00 +00:00
2012-07-23 23:14:37 +00:00
if async_jid is None :
cmd = " %s %s " % ( remote_module_path , argsfile )
else :
cmd = " " . join ( [ str ( x ) for x in [ remote_module_path , async_jid , async_limit , async_module , argsfile ] ] )
2012-03-14 23:57:56 +00:00
else :
2012-07-23 23:14:37 +00:00
if async_jid is None :
2014-11-24 21:36:31 +00:00
if conn . has_pipelining and C . ANSIBLE_SSH_PIPELINING and not C . DEFAULT_KEEP_REMOTE_FILES and not self . become_method == ' su ' :
2013-12-11 09:55:56 +00:00
in_data = module_data
else :
cmd = " %s " % ( remote_module_path )
2012-07-23 23:14:37 +00:00
else :
cmd = " " . join ( [ str ( x ) for x in [ remote_module_path , async_jid , async_limit , async_module ] ] )
2012-04-02 17:29:12 +00:00
2012-10-21 02:51:36 +00:00
if not shebang :
raise errors . AnsibleError ( " module is missing interpreter line " )
2014-06-17 20:15:18 +00:00
rm_tmp = None
2014-01-23 15:02:17 +00:00
if " tmp " in tmp and not C . DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp :
2014-11-24 21:36:31 +00:00
if not self . become or self . become_user == ' root ' :
2013-04-23 03:43:13 +00:00
# not sudoing or sudoing to root, so can cleanup files in the same step
2014-06-17 20:15:18 +00:00
rm_tmp = tmp
cmd = conn . shell . build_module_command ( environment_string , shebang , cmd , rm_tmp )
cmd = cmd . strip ( )
2013-09-05 17:04:48 +00:00
sudoable = True
if module_name == " accelerate " :
# always run the accelerate module as the user
2014-11-24 21:36:31 +00:00
# specified in the play, not the become_user
2013-09-05 17:04:48 +00:00
sudoable = False
2014-11-24 21:36:31 +00:00
res = self . _low_level_exec_command ( conn , cmd , tmp , become = self . become , sudoable = sudoable , in_data = in_data )
2013-04-23 03:43:13 +00:00
2014-01-23 15:02:17 +00:00
if " tmp " in tmp and not C . DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp :
2014-11-24 21:36:31 +00:00
if self . become and self . become_user != ' root ' :
# not becoming root, so maybe can't delete files as that other user
2013-04-23 03:43:13 +00:00
# have to clean up temp files as original user in a second step
2014-06-17 20:15:18 +00:00
cmd2 = conn . shell . remove ( tmp , recurse = True )
2013-04-23 03:43:13 +00:00
self . _low_level_exec_command ( conn , cmd2 , tmp , sudoable = False )
2014-09-11 16:26:54 +00:00
data = utils . parse_json ( res [ ' stdout ' ] , from_remote = True , no_exceptions = True )
2013-02-07 22:43:33 +00:00
if ' parsed ' in data and data [ ' parsed ' ] == False :
data [ ' msg ' ] + = res [ ' stderr ' ]
return ReturnData ( conn = conn , result = data )
2012-03-22 03:39:09 +00:00
# *****************************************************
2013-07-04 18:05:41 +00:00
def _executor ( self , host , new_stdin ) :
2012-07-15 14:57:22 +00:00
''' handler for multiprocessing library '''
2012-03-25 23:05:27 +00:00
try :
2014-01-03 14:46:16 +00:00
fileno = sys . stdin . fileno ( )
except ValueError :
fileno = None
try :
2014-03-31 18:37:43 +00:00
self . _new_stdin = new_stdin
2014-01-03 14:46:16 +00:00
if not new_stdin and fileno is not None :
2014-03-31 18:37:43 +00:00
try :
self . _new_stdin = os . fdopen ( os . dup ( fileno ) )
2014-03-31 18:50:23 +00:00
except OSError , e :
2014-03-31 18:37:43 +00:00
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
2013-07-04 18:05:41 +00:00
exec_rc = self . _executor_internal ( host , new_stdin )
2012-05-25 22:44:29 +00:00
if type ( exec_rc ) != ReturnData :
raise Exception ( " unexpected return type: %s " % type ( exec_rc ) )
2012-07-20 12:56:33 +00:00
# redundant, right?
2012-07-20 15:15:57 +00:00
if not exec_rc . comm_ok :
self . callbacks . on_unreachable ( host , exec_rc . result )
2012-05-25 22:44:29 +00:00
return exec_rc
2012-03-25 23:05:27 +00:00
except errors . AnsibleError , ae :
msg = str ( ae )
self . callbacks . on_unreachable ( host , msg )
2014-02-28 23:38:45 +00:00
return ReturnData ( host = host , comm_ok = False , result = dict ( failed = True , msg = msg ) )
2012-03-25 23:05:27 +00:00
except Exception :
msg = traceback . format_exc ( )
self . callbacks . on_unreachable ( host , msg )
2014-02-28 23:38:45 +00:00
return ReturnData ( host = host , comm_ok = False , result = dict ( failed = True , msg = msg ) )
2012-03-25 23:05:27 +00:00
2012-07-15 14:22:15 +00:00
# *****************************************************
2014-09-11 20:01:34 +00:00
def get_combined_cache ( self ) :
2014-04-01 14:48:14 +00:00
# merge the VARS and SETUP caches for this host
combined_cache = self . setup_cache . copy ( )
2014-09-11 20:01:34 +00:00
return utils . merge_hash ( combined_cache , self . vars_cache )
2014-08-11 16:22:47 +00:00
2014-09-11 20:01:34 +00:00
def get_inject_vars ( self , host ) :
host_variables = self . inventory . get_variables ( host , vault_password = self . vault_pass )
combined_cache = self . get_combined_cache ( )
2014-04-01 14:48:14 +00:00
2014-04-15 15:54:43 +00:00
# use combined_cache and host_variables to template the module_vars
2014-05-08 18:09:36 +00:00
# we update the inject variables with the data we're about to template
# since some of the variables we'll be replacing may be contained there too
2014-06-04 15:50:41 +00:00
module_vars_inject = utils . combine_vars ( host_variables , combined_cache . get ( host , { } ) )
2014-05-23 18:36:45 +00:00
module_vars_inject = utils . combine_vars ( self . module_vars , module_vars_inject )
2014-04-15 15:54:43 +00:00
module_vars = template . template ( self . basedir , self . module_vars , module_vars_inject )
2014-09-30 20:50:46 +00:00
# remove bad variables from the module vars, which may be in there due
# the way role declarations are specified in playbooks
if ' tags ' in module_vars :
del module_vars [ ' tags ' ]
if ' when ' in module_vars :
del module_vars [ ' when ' ]
# start building the dictionary of injected variables
2012-08-18 23:49:49 +00:00
inject = { }
2014-08-15 20:57:02 +00:00
2014-09-11 20:01:34 +00:00
# default vars are the lowest priority
2013-08-29 22:21:28 +00:00
inject = utils . combine_vars ( inject , self . default_vars )
2014-09-11 20:01:34 +00:00
# next come inventory variables for the host
2013-03-09 23:30:18 +00:00
inject = utils . combine_vars ( inject , host_variables )
2014-09-11 20:01:34 +00:00
# then the setup_cache which contains facts gathered
2014-08-15 20:57:02 +00:00
inject = utils . combine_vars ( inject , self . setup_cache . get ( host , { } ) )
2014-11-17 21:30:22 +00:00
# next come variables from vars and vars files
inject = utils . combine_vars ( inject , self . play_vars )
inject = utils . combine_vars ( inject , self . play_file_vars )
# next come variables from role vars/main.yml files
inject = utils . combine_vars ( inject , self . role_vars )
2014-09-30 20:50:46 +00:00
# then come the module variables
inject = utils . combine_vars ( inject , module_vars )
2014-11-17 21:30:22 +00:00
# followed by vars_cache things (set_fact, include_vars, and
# vars_files which had host-specific templating done)
inject = utils . combine_vars ( inject , self . vars_cache . get ( host , { } ) )
2014-11-20 18:20:32 +00:00
# role parameters next
inject = utils . combine_vars ( inject , self . role_params )
2014-09-11 20:01:34 +00:00
# and finally -e vars are the highest priority
2014-08-15 20:57:02 +00:00
inject = utils . combine_vars ( inject , self . extra_vars )
2014-09-11 20:01:34 +00:00
# and then special vars
2013-06-18 15:53:52 +00:00
inject . setdefault ( ' ansible_ssh_user ' , self . remote_user )
2014-09-11 20:01:34 +00:00
inject [ ' group_names ' ] = host_variables . get ( ' group_names ' , [ ] )
inject [ ' groups ' ] = self . inventory . groups_list ( )
inject [ ' vars ' ] = self . module_vars
inject [ ' defaults ' ] = self . default_vars
inject [ ' environment ' ] = self . environment
2014-08-12 14:51:21 +00:00
inject [ ' playbook_dir ' ] = os . path . abspath ( self . basedir )
2014-09-11 20:01:34 +00:00
inject [ ' omit ' ] = self . omit_token
2014-09-17 16:03:36 +00:00
inject [ ' combined_cache ' ] = combined_cache
2014-09-11 20:01:34 +00:00
return inject
def _executor_internal ( self , host , new_stdin ) :
''' executes any module one or more times '''
2014-12-02 03:25:35 +00:00
# We build the proper injected dictionary for all future
# templating operations in this run
2014-09-11 20:01:34 +00:00
inject = self . get_inject_vars ( host )
2014-12-02 03:25:35 +00:00
# Then we selectively merge some variable dictionaries down to a
# single dictionary, used to template the HostVars for this host
temp_vars = self . inventory . get_variables ( host , vault_password = self . vault_pass )
2015-03-09 16:12:37 +00:00
temp_vars = utils . combine_vars ( temp_vars , inject [ ' combined_cache ' ] )
2015-03-09 14:27:59 +00:00
temp_vars = utils . combine_vars ( temp_vars , { ' groups ' : inject [ ' groups ' ] } )
2015-02-24 10:05:27 +00:00
temp_vars = utils . combine_vars ( temp_vars , self . play_vars )
temp_vars = utils . combine_vars ( temp_vars , self . play_file_vars )
temp_vars = utils . combine_vars ( temp_vars , self . extra_vars )
2014-12-02 03:25:35 +00:00
hostvars = HostVars ( temp_vars , self . inventory , vault_password = self . vault_pass )
# and we save the HostVars in the injected dictionary so they
# may be referenced from playbooks/templates
2014-09-11 20:01:34 +00:00
inject [ ' hostvars ' ] = hostvars
host_connection = inject . get ( ' ansible_connection ' , self . transport )
if host_connection in [ ' paramiko ' , ' ssh ' , ' accelerate ' ] :
port = hostvars . get ( ' ansible_ssh_port ' , self . remote_port )
if port is None :
port = C . DEFAULT_REMOTE_PORT
else :
# fireball, local, etc
port = self . remote_port
2013-04-10 19:22:08 +00:00
2013-03-26 02:32:01 +00:00
if self . inventory . basedir ( ) is not None :
inject [ ' inventory_dir ' ] = self . inventory . basedir ( )
2012-07-20 12:29:44 +00:00
2013-08-10 10:59:17 +00:00
if self . inventory . src ( ) is not None :
inject [ ' inventory_file ' ] = self . inventory . src ( )
2014-03-21 17:08:55 +00:00
# could be already set by playbook code
inject . setdefault ( ' ansible_version ' , utils . version_info ( gitinfo = False ) )
2012-10-25 13:10:33 +00:00
# allow with_foo to work in playbooks...
2012-10-31 15:37:26 +00:00
items = None
2012-10-13 00:07:05 +00:00
items_plugin = self . module_vars . get ( ' items_lookup_plugin ' , None )
2013-04-10 19:22:08 +00:00
2012-11-01 23:41:50 +00:00
if items_plugin is not None and items_plugin in utils . plugins . lookup_loader :
2013-04-10 19:22:08 +00:00
2013-06-01 22:22:56 +00:00
basedir = self . basedir
if ' _original_file ' in inject :
basedir = os . path . dirname ( inject [ ' _original_file ' ] )
filesdir = os . path . join ( basedir , ' .. ' , ' files ' )
if os . path . exists ( filesdir ) :
basedir = filesdir
2014-10-10 17:23:58 +00:00
try :
items_terms = self . module_vars . get ( ' items_lookup_terms ' , ' ' )
items_terms = template . template ( basedir , items_terms , inject )
items = utils . plugins . lookup_loader . get ( items_plugin , runner = self , basedir = basedir ) . run ( items_terms , inject = inject )
except errors . AnsibleUndefinedVariable , e :
if ' has no attribute ' in str ( e ) :
# the undefined variable was an attribute of a variable that does
# exist, so try and run this through the conditional check to see
# if the user wanted to skip something on being undefined
if utils . check_conditional ( self . conditional , self . basedir , inject , fail_on_undefined = True ) :
# the conditional check passed, so we have to fail here
raise
else :
# the conditional failed, so we skip this task
result = utils . jsonify ( dict ( changed = False , skipped = True ) )
self . callbacks . on_skipped ( host , None )
return ReturnData ( host = host , result = result )
2014-12-02 15:58:14 +00:00
except errors . AnsibleError , e :
raise
except Exception , e :
raise errors . AnsibleError ( " Unexpected error while executing task: %s " % str ( e ) )
2014-10-10 17:23:58 +00:00
2014-07-21 16:20:49 +00:00
# strip out any jinja2 template syntax within
# the data returned by the lookup plugin
items = utils . _clean_data_struct ( items , from_remote = True )
2014-11-25 16:23:22 +00:00
if items is None :
items = [ ]
else :
if type ( items ) != list :
raise errors . AnsibleError ( " lookup plugins have to return a list: %r " % items )
if len ( items ) and utils . is_list_of_strings ( items ) and self . module_name in [ ' apt ' , ' yum ' , ' pkgng ' , ' zypper ' ] :
# hack for apt, yum, and pkgng so that with_items maps back into a single module call
use_these_items = [ ]
for x in items :
inject [ ' item ' ] = x
if not self . conditional or utils . check_conditional ( self . conditional , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars ) :
use_these_items . append ( x )
inject [ ' item ' ] = " , " . join ( use_these_items )
items = None
2012-08-07 00:07:02 +00:00
2014-09-04 21:00:02 +00:00
def _safe_template_complex_args ( args , inject ) :
# Ensure the complex args here are a dictionary, but
# first template them if they contain a variable
2014-09-08 13:44:37 +00:00
2014-09-04 21:00:02 +00:00
returned_args = args
if isinstance ( args , basestring ) :
# If the complex_args were evaluated to a dictionary and there are
# more keys in the templated version than the evaled version, some
# param inserted additional keys (the template() call also runs
# safe_eval on the var if it looks like it's a datastructure). If the
# evaled_args are not a dict, it's most likely a whole variable (ie.
# args: {{var}}), in which case there's no way to detect the proper
# count of params in the dictionary.
templated_args = template . template ( self . basedir , args , inject , convert_bare = True )
evaled_args = utils . safe_eval ( args )
if isinstance ( evaled_args , dict ) and len ( evaled_args ) > 0 and len ( evaled_args ) != len ( templated_args ) :
raise errors . AnsibleError ( " a variable tried to insert extra parameters into the args for this task " )
# set the returned_args to the templated_args
returned_args = templated_args
# and a final check to make sure the complex args are a dict
2014-09-08 13:44:37 +00:00
if returned_args is not None and not isinstance ( returned_args , dict ) :
2014-09-04 21:00:02 +00:00
raise errors . AnsibleError ( " args must be a dictionary, received %s " % returned_args )
return returned_args
2012-08-18 12:46:51 +00:00
2013-04-23 02:17:55 +00:00
# logic to decide how to run things depends on whether with_items is used
2012-10-31 15:37:26 +00:00
if items is None :
2014-09-04 21:00:02 +00:00
complex_args = _safe_template_complex_args ( self . complex_args , inject )
2013-04-23 02:17:55 +00:00
return self . _executor_internal_inner ( host , self . module_name , self . module_args , inject , port , complex_args = complex_args )
2012-10-31 15:37:26 +00:00
elif len ( items ) > 0 :
2013-04-10 19:22:08 +00:00
2012-07-15 16:51:56 +00:00
# executing using with_items, so make multiple calls
# TODO: refactor
2013-04-10 19:22:08 +00:00
2013-08-21 21:43:12 +00:00
if self . background > 0 :
raise errors . AnsibleError ( " lookup plugins (with_*) cannot be used with async tasks " )
2012-07-15 16:51:56 +00:00
all_comm_ok = True
all_changed = False
all_failed = False
results = [ ]
for x in items :
2014-03-04 17:20:01 +00:00
# use a fresh inject for each item
2014-02-25 01:54:26 +00:00
this_inject = inject . copy ( )
this_inject [ ' item ' ] = x
2013-04-26 01:10:54 +00:00
2014-09-04 21:00:02 +00:00
complex_args = _safe_template_complex_args ( self . complex_args , this_inject )
2013-04-10 19:22:08 +00:00
result = self . _executor_internal_inner (
2013-06-18 17:24:30 +00:00
host ,
self . module_name ,
self . module_args ,
2014-02-25 01:54:26 +00:00
this_inject ,
2013-06-18 17:24:30 +00:00
port ,
2013-04-23 02:17:55 +00:00
complex_args = complex_args
2013-04-10 19:22:08 +00:00
)
2015-01-13 19:26:52 +00:00
if ' stdout ' in result . result and ' stdout_lines ' not in result . result :
result . result [ ' stdout_lines ' ] = result . result [ ' stdout ' ] . splitlines ( )
2012-07-15 16:51:56 +00:00
results . append ( result . result )
if result . comm_ok == False :
all_comm_ok = False
2012-10-13 00:07:05 +00:00
all_failed = True
2012-07-15 16:51:56 +00:00
break
for x in results :
if x . get ( ' changed ' ) == True :
all_changed = True
2013-09-09 23:34:01 +00:00
if ( x . get ( ' failed ' ) == True ) or ( ' failed_when_result ' in x and [ x [ ' failed_when_result ' ] ] or [ ( ' rc ' in x ) and ( x [ ' rc ' ] != 0 ) ] ) [ 0 ] :
2012-07-15 16:51:56 +00:00
all_failed = True
break
2012-10-13 00:07:05 +00:00
msg = ' All items completed '
2012-07-15 16:51:56 +00:00
if all_failed :
msg = " One or more items failed. "
rd_result = dict ( failed = all_failed , changed = all_changed , results = results , msg = msg )
if not all_failed :
del rd_result [ ' failed ' ]
return ReturnData ( host = host , comm_ok = all_comm_ok , result = rd_result )
2012-10-31 15:37:26 +00:00
else :
self . callbacks . on_skipped ( host , None )
2013-04-28 14:13:58 +00:00
return ReturnData ( host = host , comm_ok = True , result = dict ( changed = False , skipped = True ) )
2012-07-15 16:51:56 +00:00
# *****************************************************
2013-03-07 10:05:17 +00:00
def _executor_internal_inner ( self , host , module_name , module_args , inject , port , is_chained = False , complex_args = None ) :
2012-07-15 16:51:56 +00:00
''' decides how to invoke a module '''
2012-03-20 02:42:31 +00:00
2014-11-24 21:36:31 +00:00
# late processing of parameterized become_user (with_items,..)
if self . become_user_var is not None :
self . become_user = template . template ( self . basedir , self . become_user_var , inject )
2013-02-17 20:01:49 +00:00
2013-05-23 05:19:02 +00:00
# module_name may be dynamic (but cannot contain {{ ansible_ssh_user }})
2013-04-10 21:52:35 +00:00
module_name = template . template ( self . basedir , module_name , inject )
2012-11-28 15:22:35 +00:00
if module_name in utils . plugins . action_loader :
if self . background != 0 :
raise errors . AnsibleError ( " async mode is not supported with the %s module " % module_name )
handler = utils . plugins . action_loader . get ( module_name , self )
elif self . background == 0 :
handler = utils . plugins . action_loader . get ( ' normal ' , self )
else :
handler = utils . plugins . action_loader . get ( ' async ' , self )
2013-06-20 01:17:39 +00:00
if type ( self . conditional ) != list :
self . conditional = [ self . conditional ]
for cond in self . conditional :
2013-07-21 14:34:47 +00:00
if not utils . check_conditional ( cond , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars ) :
2015-03-05 04:45:24 +00:00
result = dict ( changed = False , skipped = True )
if self . no_log :
result = utils . censor_unlogged_data ( result )
self . callbacks . on_skipped ( host , result )
else :
self . callbacks . on_skipped ( host , inject . get ( ' item ' , None ) )
return ReturnData ( host = host , result = utils . jsonify ( result ) )
2012-06-11 13:06:23 +00:00
2013-07-29 21:56:46 +00:00
if getattr ( handler , ' setup ' , None ) is not None :
handler . setup ( module_name , inject )
2012-04-17 01:52:15 +00:00
conn = None
2012-10-17 23:17:01 +00:00
actual_host = inject . get ( ' ansible_ssh_host ' , host )
2013-07-05 16:05:26 +00:00
# allow ansible_ssh_host to be templated
actual_host = template . template ( self . basedir , actual_host , inject , fail_on_undefined = True )
2012-10-18 02:50:17 +00:00
actual_port = port
2013-02-10 22:22:18 +00:00
actual_user = inject . get ( ' ansible_ssh_user ' , self . remote_user )
actual_pass = inject . get ( ' ansible_ssh_pass ' , self . remote_pass )
2013-02-22 16:11:08 +00:00
actual_transport = inject . get ( ' ansible_connection ' , self . transport )
2013-11-22 05:09:37 +00:00
actual_private_key_file = inject . get ( ' ansible_ssh_private_key_file ' , self . private_key_file )
2014-01-16 13:14:40 +00:00
actual_private_key_file = template . template ( self . basedir , actual_private_key_file , inject , fail_on_undefined = True )
2015-03-17 22:23:40 +00:00
2014-11-24 21:36:31 +00:00
self . become = utils . boolean ( inject . get ( ' ansible_become ' , inject . get ( ' ansible_sudo ' , inject . get ( ' ansible_su ' , self . become ) ) ) )
self . become_user = inject . get ( ' ansible_become_user ' , inject . get ( ' ansible_sudo_user ' , inject . get ( ' ansible_su_user ' , self . become_user ) ) )
self . become_pass = inject . get ( ' ansible_become_pass ' , inject . get ( ' ansible_sudo_pass ' , inject . get ( ' ansible_su_pass ' , self . become_pass ) ) )
self . become_exe = inject . get ( ' ansible_become_exe ' , inject . get ( ' ansible_sudo_exe ' , self . become_exe ) )
2015-03-17 22:23:40 +00:00
self . become_method = inject . get ( ' ansible_become_method ' , self . become_method )
2014-11-24 21:36:31 +00:00
# select default root user in case self.become requested
2013-12-20 12:22:17 +00:00
# but no user specified; happens e.g. in host vars when
2014-11-24 21:36:31 +00:00
# just ansible_become=True is specified
if self . become and self . become_user is None :
self . become_user = ' root '
2013-12-20 12:22:17 +00:00
2013-11-22 02:06:10 +00:00
if actual_private_key_file is not None :
2013-11-22 02:20:14 +00:00
actual_private_key_file = os . path . expanduser ( actual_private_key_file )
2013-11-22 02:06:10 +00:00
2013-09-06 01:20:25 +00:00
if self . accelerate and actual_transport != ' local ' :
2013-09-25 13:54:54 +00:00
#Fix to get the inventory name of the host to accelerate plugin
if inject . get ( ' ansible_ssh_host ' , None ) :
self . accelerate_inventory_host = host
else :
self . accelerate_inventory_host = None
2013-09-06 01:20:25 +00:00
# if we're using accelerated mode, force the
# transport to accelerate
actual_transport = " accelerate "
if not self . accelerate_port :
self . accelerate_port = C . ACCELERATE_PORT
2014-06-17 21:04:50 +00:00
actual_port = inject . get ( ' ansible_ssh_port ' , port )
2012-10-17 23:17:01 +00:00
# the delegated host may have different SSH port configured, etc
# and we need to transfer those, and only those, variables
2014-09-17 01:51:00 +00:00
self . delegate_to = inject . get ( ' delegate_to ' , None )
if self . delegate_to :
self . delegate_to = template . template ( self . basedir , self . delegate_to , inject )
if self . delegate_to is not None :
delegate = self . _compute_delegate ( actual_pass , inject )
2014-02-03 21:59:30 +00:00
actual_transport = delegate [ ' transport ' ]
actual_host = delegate [ ' ssh_host ' ]
actual_port = delegate [ ' port ' ]
actual_user = delegate [ ' user ' ]
actual_pass = delegate [ ' pass ' ]
actual_private_key_file = delegate [ ' private_key_file ' ]
2014-11-24 21:36:31 +00:00
self . become_pass = delegate . get ( ' become_pass ' , delegate . get ( ' sudo_pass ' ) )
2014-02-03 21:59:30 +00:00
inject = delegate [ ' inject ' ]
2015-01-30 20:04:52 +00:00
# set resolved delegate_to into inject so modules can call _remote_checksum
inject [ ' delegate_to ' ] = self . delegate_to
2012-10-17 00:57:37 +00:00
2013-05-23 05:19:02 +00:00
# user/pass may still contain variables at this stage
2013-04-10 21:52:35 +00:00
actual_user = template . template ( self . basedir , actual_user , inject )
2015-03-21 06:02:59 +00:00
try :
actual_pass = template . template ( self . basedir , actual_pass , inject )
self . become_pass = template . template ( self . basedir , self . become_pass , inject )
except :
# ignore password template errors, could be triggered by password charaters #10468
pass
2013-02-10 22:22:18 +00:00
2013-05-23 05:19:02 +00:00
# make actual_user available as __magic__ ansible_ssh_user variable
inject [ ' ansible_ssh_user ' ] = actual_user
2012-10-17 23:17:01 +00:00
try :
2013-09-06 01:20:25 +00:00
if actual_transport == ' accelerate ' :
2013-08-30 18:24:24 +00:00
# for accelerate, we stuff both ports into a single
2013-08-27 20:25:54 +00:00
# variable so that we don't have to mangle other function
2014-05-03 16:40:05 +00:00
# calls just to accommodate this one case
2013-08-29 00:27:18 +00:00
actual_port = [ actual_port , self . accelerate_port ]
2013-08-27 20:25:54 +00:00
elif actual_port is not None :
2013-09-23 09:33:36 +00:00
actual_port = int ( template . template ( self . basedir , actual_port , inject ) )
2012-11-20 18:04:37 +00:00
except ValueError , e :
result = dict ( failed = True , msg = " FAILED: Configured port \" %s \" is not a valid port, expected integer " % actual_port )
return ReturnData ( host = host , comm_ok = False , result = result )
try :
2014-09-17 01:51:00 +00:00
if self . delegate_to or host != actual_host :
2014-11-24 02:49:33 +00:00
delegate_host = host
else :
delegate_host = None
conn = self . connector . connect ( actual_host , actual_port , actual_user , actual_pass , actual_transport , actual_private_key_file , delegate_host )
2012-10-17 00:57:37 +00:00
2014-06-17 20:15:18 +00:00
default_shell = getattr ( conn , ' default_shell ' , ' ' )
shell_type = inject . get ( ' ansible_shell_type ' )
if not shell_type :
if default_shell :
shell_type = default_shell
else :
shell_type = os . path . basename ( C . DEFAULT_EXECUTABLE )
shell_plugin = utils . plugins . shell_loader . get ( shell_type )
if shell_plugin is None :
shell_plugin = utils . plugins . shell_loader . get ( ' sh ' )
conn . shell = shell_plugin
2012-10-19 00:14:15 +00:00
2012-04-17 01:52:15 +00:00
except errors . AnsibleConnectionFailed , e :
2012-05-25 22:44:29 +00:00
result = dict ( failed = True , msg = " FAILED: %s " % str ( e ) )
return ReturnData ( host = host , comm_ok = False , result = result )
2012-04-17 01:52:15 +00:00
2012-08-10 04:45:00 +00:00
tmp = ' '
2013-12-11 09:55:56 +00:00
# action plugins may DECLARE via TRANSFERS_FILES = True that they need a remote tmp path working dir
if self . _early_needs_tmp_path ( module_name , handler ) :
2012-08-10 04:45:00 +00:00
tmp = self . _make_tmp_path ( conn )
2013-03-09 23:30:18 +00:00
2014-07-29 01:21:31 +00:00
# allow module args to work as a dictionary
# though it is usually a string
2014-08-02 05:11:42 +00:00
if isinstance ( module_args , dict ) :
module_args = utils . serialize_args ( module_args )
2014-07-29 01:21:31 +00:00
2013-05-23 05:19:02 +00:00
# render module_args and complex_args templates
2013-06-18 17:24:30 +00:00
try :
2014-07-21 16:20:49 +00:00
# When templating module_args, we need to be careful to ensure
2014-12-04 22:23:35 +00:00
# that no variables inadvertently (or maliciously) add params
2014-07-21 16:20:49 +00:00
# to the list of args. We do this by counting the number of k=v
# pairs before and after templating.
2014-07-24 02:37:57 +00:00
num_args_pre = self . _count_module_args ( module_args , allow_dupes = True )
2013-06-18 17:24:30 +00:00
module_args = template . template ( self . basedir , module_args , inject , fail_on_undefined = self . error_on_undefined_vars )
2014-07-21 16:20:49 +00:00
num_args_post = self . _count_module_args ( module_args )
if num_args_pre != num_args_post :
raise errors . AnsibleError ( " A variable inserted a new parameter into the module args. " + \
" Be sure to quote variables if they contain equal signs (for example: \" {{ var}} \" ). " )
# And we also make sure nothing added in special flags for things
# like the command/shell module (ie. #USE_SHELL)
if ' #USE_SHELL ' in module_args :
raise errors . AnsibleError ( " A variable tried to add #USE_SHELL to the module arguments. " )
2013-06-18 17:24:30 +00:00
complex_args = template . template ( self . basedir , complex_args , inject , fail_on_undefined = self . error_on_undefined_vars )
except jinja2 . exceptions . UndefinedError , e :
2013-06-18 17:30:02 +00:00
raise errors . AnsibleUndefinedVariable ( " One or more undefined variables: %s " % str ( e ) )
2013-06-18 17:24:30 +00:00
2014-08-27 16:51:03 +00:00
# filter omitted arguments out from complex_args
if complex_args :
complex_args = dict ( filter ( lambda x : x [ 1 ] != self . omit_token , complex_args . iteritems ( ) ) )
# Filter omitted arguments out from module_args.
# We do this with split_args instead of parse_kv to ensure
# that things are not unquoted/requoted incorrectly
args = split_args ( module_args )
final_args = [ ]
for arg in args :
if ' = ' in arg :
k , v = arg . split ( ' = ' , 1 )
if unquote ( v ) != self . omit_token :
final_args . append ( arg )
else :
# not a k=v param, append it
final_args . append ( arg )
module_args = ' ' . join ( final_args )
2013-05-23 05:19:02 +00:00
2013-03-07 10:05:17 +00:00
result = handler . run ( conn , tmp , module_name , module_args , inject , complex_args )
2013-09-24 08:29:38 +00:00
# Code for do until feature
until = self . module_vars . get ( ' until ' , None )
2013-10-28 16:56:46 +00:00
if until is not None and result . comm_ok :
2013-09-24 08:29:38 +00:00
inject [ self . module_vars . get ( ' register ' ) ] = result . result
2014-08-11 16:22:47 +00:00
2013-09-24 08:29:38 +00:00
cond = template . template ( self . basedir , until , inject , expand_lists = False )
if not utils . check_conditional ( cond , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars ) :
2014-12-10 21:54:58 +00:00
retries = template . template ( self . basedir , self . module_vars . get ( ' retries ' ) , inject , expand_lists = False )
2013-09-24 08:29:38 +00:00
delay = self . module_vars . get ( ' delay ' )
2013-12-07 09:35:14 +00:00
for x in range ( 1 , int ( retries ) + 1 ) :
2013-11-25 15:13:55 +00:00
# template the delay, cast to float and sleep
delay = template . template ( self . basedir , delay , inject , expand_lists = False )
delay = float ( delay )
2013-09-24 08:29:38 +00:00
time . sleep ( delay )
tmp = ' '
2013-12-11 09:55:56 +00:00
if self . _early_needs_tmp_path ( module_name , handler ) :
2013-09-24 08:29:38 +00:00
tmp = self . _make_tmp_path ( conn )
result = handler . run ( conn , tmp , module_name , module_args , inject , complex_args )
2013-09-25 04:26:14 +00:00
result . result [ ' attempts ' ] = x
2013-09-24 08:29:38 +00:00
vv ( " Result from run %i is: %s " % ( x , result . result ) )
inject [ self . module_vars . get ( ' register ' ) ] = result . result
cond = template . template ( self . basedir , until , inject , expand_lists = False )
if utils . check_conditional ( cond , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars ) :
2013-09-25 20:50:24 +00:00
break
2013-10-07 14:02:21 +00:00
if result . result [ ' attempts ' ] == retries and not utils . check_conditional ( cond , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars ) :
2014-08-11 16:22:47 +00:00
result . result [ ' failed ' ] = True
2013-10-07 14:02:21 +00:00
result . result [ ' msg ' ] = " Task failed as maximum retries was encountered "
2013-09-25 04:26:14 +00:00
else :
result . result [ ' attempts ' ] = 0
2012-03-03 03:38:55 +00:00
conn . close ( )
2012-03-25 23:05:27 +00:00
2012-05-25 22:44:29 +00:00
if not result . comm_ok :
# connection or parsing errors...
2012-06-11 13:07:37 +00:00
self . callbacks . on_unreachable ( host , result . result )
2012-03-25 23:05:27 +00:00
else :
2012-05-25 22:44:29 +00:00
data = result . result
2014-01-10 20:08:45 +00:00
# https://github.com/ansible/ansible/issues/4958
2014-01-10 22:42:43 +00:00
if hasattr ( sys . stdout , " isatty " ) :
if " stdout " in data and sys . stdout . isatty ( ) :
if not string_functions . isprintable ( data [ ' stdout ' ] ) :
2014-05-22 02:24:28 +00:00
data [ ' stdout ' ] = ' ' . join ( c for c in data [ ' stdout ' ] if string_functions . isprintable ( c ) )
2014-01-10 20:08:45 +00:00
2012-07-20 12:29:44 +00:00
if ' item ' in inject :
result . result [ ' item ' ] = inject [ ' item ' ]
2012-08-21 00:41:28 +00:00
result . result [ ' invocation ' ] = dict (
2012-09-21 08:42:27 +00:00
module_args = module_args ,
module_name = module_name
2012-08-21 00:41:28 +00:00
)
2013-07-14 19:07:45 +00:00
changed_when = self . module_vars . get ( ' changed_when ' )
2013-09-09 23:34:01 +00:00
failed_when = self . module_vars . get ( ' failed_when ' )
2014-03-25 18:59:57 +00:00
if ( changed_when is not None or failed_when is not None ) and self . background == 0 :
2013-07-14 19:07:45 +00:00
register = self . module_vars . get ( ' register ' )
2014-03-25 18:59:57 +00:00
if register is not None :
2013-07-14 19:07:45 +00:00
if ' stdout ' in data :
data [ ' stdout_lines ' ] = data [ ' stdout ' ] . splitlines ( )
inject [ register ] = data
2014-03-25 18:59:57 +00:00
# only run the final checks if the async_status has finished,
# or if we're not running an async_status check at all
if ( module_name == ' async_status ' and " finished " in data ) or module_name != ' async_status ' :
2014-04-07 14:51:04 +00:00
if changed_when is not None and ' skipped ' not in data :
2014-03-25 18:59:57 +00:00
data [ ' changed ' ] = utils . check_conditional ( changed_when , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars )
2014-05-14 21:04:37 +00:00
if failed_when is not None and ' skipped ' not in data :
2014-03-25 18:59:57 +00:00
data [ ' failed_when_result ' ] = data [ ' failed ' ] = utils . check_conditional ( failed_when , self . basedir , inject , fail_on_undefined = self . error_on_undefined_vars )
2013-07-14 19:07:45 +00:00
2014-08-12 17:35:38 +00:00
2012-07-24 02:12:26 +00:00
if is_chained :
# no callbacks
return result
if ' skipped ' in data :
2014-04-16 14:40:01 +00:00
self . callbacks . on_skipped ( host , inject . get ( ' item ' , None ) )
2014-08-12 17:35:38 +00:00
if self . no_log :
data = utils . censor_unlogged_data ( data )
if not result . is_successful ( ) :
2012-08-01 19:17:16 +00:00
ignore_errors = self . module_vars . get ( ' ignore_errors ' , False )
2012-08-18 12:46:51 +00:00
self . callbacks . on_failed ( host , data , ignore_errors )
2012-07-24 02:12:26 +00:00
else :
2013-02-10 04:24:03 +00:00
if self . diff :
2013-02-25 22:32:52 +00:00
self . callbacks . on_file_diff ( conn . host , result . diff )
2012-08-18 12:46:51 +00:00
self . callbacks . on_ok ( host , data )
2014-08-11 16:22:47 +00:00
2012-03-03 03:38:55 +00:00
return result
2013-12-11 09:55:56 +00:00
def _early_needs_tmp_path ( self , module_name , handler ) :
''' detect if a tmp path should be created before the handler is called '''
if module_name in utils . plugins . action_loader :
return getattr ( handler , ' TRANSFERS_FILES ' , False )
# other modules never need tmp path at early stage
return False
def _late_needs_tmp_path ( self , conn , tmp , module_style ) :
2014-01-23 15:02:17 +00:00
if " tmp " in tmp :
2013-12-11 09:55:56 +00:00
# tmp has already been created
return False
2014-11-24 21:36:31 +00:00
if not conn . has_pipelining or not C . ANSIBLE_SSH_PIPELINING or C . DEFAULT_KEEP_REMOTE_FILES or self . become_method == ' su ' :
2014-01-21 01:19:03 +00:00
# tmp is necessary to store module source code
return True
if not conn . has_pipelining :
2013-12-11 09:55:56 +00:00
# tmp is necessary to store the module source code
2014-01-15 22:01:03 +00:00
# or we want to keep the files on the target system
2013-12-11 09:55:56 +00:00
return True
if module_style != " new " :
# even when conn has pipelining, old style modules need tmp to store arguments
return True
return False
2014-08-11 16:22:47 +00:00
2013-12-11 09:55:56 +00:00
2012-03-14 00:59:05 +00:00
# *****************************************************
2014-01-21 01:19:03 +00:00
def _low_level_exec_command ( self , conn , cmd , tmp , sudoable = False ,
2014-11-24 21:36:31 +00:00
executable = None , become = False , in_data = None ) :
2012-02-27 01:29:27 +00:00
''' execute a command string over SSH, return the output '''
2014-11-24 21:36:31 +00:00
# this can be skipped with powershell modules when there is no analog to a Windows command (like chmod)
if cmd :
2012-07-15 14:57:22 +00:00
2014-11-24 21:36:31 +00:00
if executable is None :
executable = C . DEFAULT_EXECUTABLE
2014-06-17 20:15:18 +00:00
2014-11-24 21:36:31 +00:00
become_user = self . become_user
2012-12-23 18:17:07 +00:00
2014-11-24 21:36:31 +00:00
# compare connection user to (su|sudo)_user and disable if the same
# assume connection type is local if no user attribute
this_user = getattr ( conn , ' user ' , getpass . getuser ( ) )
if ( not become and this_user == become_user ) :
sudoable = False
become = False
2013-11-27 22:01:53 +00:00
2014-01-21 01:19:03 +00:00
rc , stdin , stdout , stderr = conn . exec_command ( cmd ,
tmp ,
2014-11-24 21:36:31 +00:00
become_user = become_user ,
2014-01-21 01:19:03 +00:00
sudoable = sudoable ,
executable = executable ,
in_data = in_data )
2012-05-25 22:44:29 +00:00
2014-11-24 21:36:31 +00:00
if type ( stdout ) not in [ str , unicode ] :
out = ' ' . join ( stdout . readlines ( ) )
else :
out = stdout
2012-08-07 00:07:02 +00:00
2014-11-24 21:36:31 +00:00
if type ( stderr ) not in [ str , unicode ] :
err = ' ' . join ( stderr . readlines ( ) )
else :
err = stderr
if rc is not None :
return dict ( rc = rc , stdout = out , stderr = err )
else :
return dict ( stdout = out , stderr = err )
return dict ( rc = None , stdout = ' ' , stderr = ' ' )
2012-07-31 20:59:45 +00:00
2012-04-27 05:25:38 +00:00
2012-03-14 00:59:05 +00:00
# *****************************************************
2014-11-24 21:36:31 +00:00
def _remote_chmod ( self , conn , mode , path , tmp , sudoable = False , become = False ) :
2014-06-17 20:15:18 +00:00
''' issue a remote chmod command '''
cmd = conn . shell . chmod ( mode , path )
2014-11-24 21:36:31 +00:00
return self . _low_level_exec_command ( conn , cmd , tmp , sudoable = sudoable , become = become )
2014-06-17 20:15:18 +00:00
# *****************************************************
2014-11-11 20:28:19 +00:00
def _remote_expand_user ( self , conn , path , tmp ) :
''' takes a remote path and performs tilde expansion on the remote host '''
if not path . startswith ( ' ~ ' ) :
return path
2014-12-03 18:45:54 +00:00
2014-11-11 20:28:19 +00:00
split_path = path . split ( os . path . sep , 1 )
2014-12-03 18:45:54 +00:00
expand_path = split_path [ 0 ]
if expand_path == ' ~ ' :
2014-11-24 21:36:31 +00:00
if self . become and self . become_user :
expand_path = ' ~ %s ' % self . become_user
2014-12-03 18:45:54 +00:00
cmd = conn . shell . expand_user ( expand_path )
2014-11-24 21:36:31 +00:00
data = self . _low_level_exec_command ( conn , cmd , tmp , sudoable = False , become = False )
2014-11-11 20:28:19 +00:00
initial_fragment = utils . last_non_blank_line ( data [ ' stdout ' ] )
if not initial_fragment :
# Something went wrong trying to expand the path remotely. Return
# the original string
return path
if len ( split_path ) > 1 :
2014-12-02 03:18:35 +00:00
return conn . shell . join_path ( initial_fragment , * split_path [ 1 : ] )
2014-11-11 20:28:19 +00:00
else :
return initial_fragment
# *****************************************************
2014-11-10 17:15:46 +00:00
def _remote_checksum ( self , conn , tmp , path , inject ) :
2014-11-07 05:28:04 +00:00
''' takes a remote checksum and returns 1 if no file '''
2014-12-08 20:44:44 +00:00
# Lookup the python interp from the host or delegate
# host == inven_host when there is no delegate
host = inject [ ' inventory_hostname ' ]
if ' delegate_to ' in inject :
delegate = inject [ ' delegate_to ' ]
if delegate :
# host == None when the delegate is not in inventory
host = None
# delegate set, check whether the delegate has inventory vars
delegate = template . template ( self . basedir , delegate , inject )
if delegate in inject [ ' hostvars ' ] :
# host == delegate if we need to lookup the
# python_interpreter from the delegate's inventory vars
host = delegate
if host :
python_interp = inject [ ' hostvars ' ] [ host ] . get ( ' ansible_python_interpreter ' , ' python ' )
2014-12-03 22:42:01 +00:00
else :
2014-12-08 20:44:44 +00:00
python_interp = ' python '
2014-11-07 05:28:04 +00:00
cmd = conn . shell . checksum ( path , python_interp )
2015-03-19 18:31:00 +00:00
#TODO: remove this horrible hack and find way to get checksum to work with other privilege escalation methods
if self . become_method == ' sudo ' :
sudoable = True
else :
sudoable = False
data = self . _low_level_exec_command ( conn , cmd , tmp , sudoable = sudoable )
2012-12-23 00:44:00 +00:00
data2 = utils . last_non_blank_line ( data [ ' stdout ' ] )
2012-10-11 11:43:56 +00:00
try :
2014-02-28 18:49:25 +00:00
if data2 == ' ' :
# this may happen if the connection to the remote server
2014-11-07 05:28:04 +00:00
# failed, so just return "INVALIDCHECKSUM" to avoid errors
return " INVALIDCHECKSUM "
2014-02-28 18:49:25 +00:00
else :
return data2 . split ( ) [ 0 ]
2012-10-11 11:56:01 +00:00
except IndexError :
2014-11-07 05:28:04 +00:00
sys . stderr . write ( " warning: Calculating checksum failed unusually, please report this to the list so it can be fixed \n " )
sys . stderr . write ( " command: %s \n " % cmd )
2012-10-11 11:43:56 +00:00
sys . stderr . write ( " ---- \n " )
sys . stderr . write ( " output: %s \n " % data )
sys . stderr . write ( " ---- \n " )
# this will signal that it changed and allow things to keep going
2014-11-07 05:28:04 +00:00
return " INVALIDCHECKSUM "
2012-07-07 12:45:06 +00:00
# *****************************************************
2012-06-06 12:47:47 +00:00
def _make_tmp_path ( self , conn ) :
''' make and return a temporary path on a remote box '''
2014-01-07 20:56:12 +00:00
basefile = ' ansible-tmp- %s - %s ' % ( time . time ( ) , random . randint ( 0 , 2 * * 48 ) )
2014-06-17 20:15:18 +00:00
use_system_tmp = False
2014-11-24 21:36:31 +00:00
if self . become and self . become_user != ' root ' :
2014-06-17 20:15:18 +00:00
use_system_tmp = True
2012-06-06 12:47:47 +00:00
2014-06-17 20:15:18 +00:00
tmp_mode = None
2014-11-24 21:36:31 +00:00
if self . remote_user != ' root ' or ( self . become and self . become_user != ' root ' ) :
2014-06-17 20:15:18 +00:00
tmp_mode = ' a+rx '
2012-04-21 15:38:39 +00:00
2014-06-17 20:15:18 +00:00
cmd = conn . shell . mkdtemp ( basefile , use_system_tmp , tmp_mode )
2012-05-25 22:44:29 +00:00
result = self . _low_level_exec_command ( conn , cmd , None , sudoable = False )
2013-07-22 12:25:35 +00:00
# error handling on this seems a little aggressive?
2013-07-15 07:11:24 +00:00
if result [ ' rc ' ] != 0 :
2013-08-10 22:58:45 +00:00
if result [ ' rc ' ] == 5 :
output = ' Authentication failure. '
2014-02-28 17:28:04 +00:00
elif result [ ' rc ' ] == 255 and self . transport in [ ' ssh ' ] :
2013-09-19 10:58:54 +00:00
if utils . VERBOSITY > 3 :
output = ' SSH encountered an unknown error. The output was: \n %s ' % ( result [ ' stdout ' ] + result [ ' stderr ' ] )
else :
output = ' SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue '
2014-08-05 19:18:49 +00:00
elif ' No space left on device ' in result [ ' stderr ' ] :
output = result [ ' stderr ' ]
2013-08-10 22:58:45 +00:00
else :
output = ' Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in " /tmp " . Failed command was: %s , exited with result %d ' % ( cmd , result [ ' rc ' ] )
2013-07-22 12:35:31 +00:00
if ' stdout ' in result and result [ ' stdout ' ] != ' ' :
output = output + " : %s " % result [ ' stdout ' ]
raise errors . AnsibleError ( output )
2013-07-22 12:25:35 +00:00
2014-06-19 21:20:09 +00:00
rc = conn . shell . join_path ( utils . last_non_blank_line ( result [ ' stdout ' ] ) . strip ( ) , ' ' )
2013-07-22 12:25:35 +00:00
# Catch failure conditions, files should never be
# written to locations in /.
2014-08-11 16:22:47 +00:00
if rc == ' / ' :
2013-07-19 13:22:17 +00:00
raise errors . AnsibleError ( ' failed to resolve remote temporary directory from %s : ` %s ` returned empty string ' % ( basetmp , cmd ) )
2012-09-27 03:50:54 +00:00
return rc
2012-03-14 00:59:05 +00:00
# *****************************************************
2014-02-04 18:44:10 +00:00
def _remove_tmp_path ( self , conn , tmp_path ) :
''' Remove a tmp_path. '''
if " -tmp- " in tmp_path :
2014-06-17 20:15:18 +00:00
cmd = conn . shell . remove ( tmp_path , recurse = True )
2014-02-05 17:39:22 +00:00
self . _low_level_exec_command ( conn , cmd , None , sudoable = False )
# If we have gotten here we have a working ssh configuration.
# If ssh breaks we could leave tmp directories out on the remote system.
2014-02-04 18:44:10 +00:00
# *****************************************************
2013-02-17 20:01:49 +00:00
def _copy_module ( self , conn , tmp , module_name , module_args , inject , complex_args = None ) :
2012-02-27 01:29:27 +00:00
''' transfer a module over SFTP, does not run it '''
2013-12-11 09:55:56 +00:00
(
module_style ,
module_shebang ,
module_data
) = self . _configure_module ( conn , module_name , module_args , inject , complex_args )
2014-06-17 20:15:18 +00:00
module_remote_path = conn . shell . join_path ( tmp , module_name )
2014-08-11 16:22:47 +00:00
2013-12-11 09:55:56 +00:00
self . _transfer_str ( conn , tmp , module_name , module_data )
2014-08-11 16:22:47 +00:00
2013-12-11 09:55:56 +00:00
return ( module_remote_path , module_style , module_shebang )
# *****************************************************
def _configure_module ( self , conn , module_name , module_args , inject , complex_args = None ) :
''' find module and configure it '''
2012-03-14 00:59:05 +00:00
2012-06-06 20:42:29 +00:00
# Search module path(s) for named module.
2014-06-17 20:15:18 +00:00
module_suffixes = getattr ( conn , ' default_suffixes ' , None )
2014-10-08 15:53:06 +00:00
module_path = utils . plugins . module_finder . find_plugin ( module_name , module_suffixes )
2013-12-11 09:55:56 +00:00
if module_path is None :
2014-09-28 15:31:51 +00:00
module_path2 = utils . plugins . module_finder . find_plugin ( ' ping ' , module_suffixes )
if module_path2 is not None :
raise errors . AnsibleFileNotFound ( " module %s not found in configured module paths " % ( module_name ) )
else :
raise errors . AnsibleFileNotFound ( " module %s not found in configured module paths. Additionally, core modules are missing. If this is a checkout, run ' git submodule update --init --recursive ' to correct this problem. " % ( module_name ) )
2013-10-30 14:50:16 +00:00
2012-06-04 08:15:12 +00:00
2013-10-31 20:52:37 +00:00
# insert shared code and arguments into the module
2013-12-11 09:55:56 +00:00
( module_data , module_style , module_shebang ) = module_replacer . modify_module (
module_path , complex_args , module_args , inject
2013-10-31 20:52:37 +00:00
)
2012-11-27 16:18:57 +00:00
2013-12-11 09:55:56 +00:00
return ( module_style , module_shebang , module_data )
2013-10-30 14:50:16 +00:00
2012-02-25 22:16:23 +00:00
2012-03-14 00:59:05 +00:00
# *****************************************************
2014-02-08 01:38:20 +00:00
2014-02-08 01:38:18 +00:00
def _parallel_exec ( self , hosts ) :
2012-03-22 03:39:09 +00:00
''' handles mulitprocessing when more than 1 fork is required '''
2012-04-04 14:27:24 +00:00
2014-02-08 01:38:20 +00:00
manager = multiprocessing . Manager ( )
job_queue = manager . Queue ( )
for host in hosts :
job_queue . put ( host )
result_queue = manager . Queue ( )
2014-03-04 20:58:12 +00:00
try :
fileno = sys . stdin . fileno ( )
except ValueError :
fileno = None
2014-02-08 01:38:20 +00:00
workers = [ ]
for i in range ( self . forks ) :
2014-03-31 18:37:43 +00:00
new_stdin = None
2014-03-04 20:58:12 +00:00
if fileno is not None :
2014-03-31 18:37:43 +00:00
try :
new_stdin = os . fdopen ( os . dup ( fileno ) )
2014-03-31 18:50:23 +00:00
except OSError , e :
2014-03-31 18:37:43 +00:00
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
2014-02-08 01:38:20 +00:00
prc = multiprocessing . Process ( target = _executor_hook ,
args = ( job_queue , result_queue , new_stdin ) )
prc . start ( )
workers . append ( prc )
try :
for worker in workers :
worker . join ( )
except KeyboardInterrupt :
for worker in workers :
worker . terminate ( )
worker . join ( )
2014-08-11 16:22:47 +00:00
2014-02-08 01:38:20 +00:00
results = [ ]
try :
while not result_queue . empty ( ) :
results . append ( result_queue . get ( block = False ) )
except socket . error :
raise errors . AnsibleError ( " <interrupted> " )
return results
2012-03-22 03:39:09 +00:00
# *****************************************************
def _partition_results ( self , results ) :
2013-03-06 18:41:19 +00:00
''' separate results by ones we contacted & ones we didn ' t '''
2012-03-22 03:39:09 +00:00
2012-03-25 23:05:27 +00:00
if results is None :
return None
2012-07-15 14:57:22 +00:00
results2 = dict ( contacted = { } , dark = { } )
2012-03-25 23:05:27 +00:00
2012-03-22 03:39:09 +00:00
for result in results :
2012-05-25 22:44:29 +00:00
host = result . host
if host is None :
raise Exception ( " internal error, host not set " )
if result . communicated_ok ( ) :
results2 [ " contacted " ] [ host ] = result . result
2012-03-22 03:39:09 +00:00
else :
2012-05-25 22:44:29 +00:00
results2 [ " dark " ] [ host ] = result . result
2012-03-22 03:39:09 +00:00
# hosts which were contacted but never got a chance to return
2014-01-07 04:13:39 +00:00
for host in self . run_hosts :
2012-03-22 03:39:09 +00:00
if not ( host in results2 [ ' dark ' ] or host in results2 [ ' contacted ' ] ) :
2012-02-27 05:43:02 +00:00
results2 [ " dark " ] [ host ] = { }
2012-02-25 22:16:23 +00:00
return results2
2012-02-24 04:28:58 +00:00
2012-03-22 03:39:09 +00:00
# *****************************************************
def run ( self ) :
''' xfer & run module on all matched hosts '''
2012-08-07 00:07:02 +00:00
2012-03-22 03:39:09 +00:00
# find hosts that match the pattern
2014-01-07 04:13:39 +00:00
if not self . run_hosts :
self . run_hosts = self . inventory . list_hosts ( self . pattern )
hosts = self . run_hosts
2012-03-22 03:39:09 +00:00
if len ( hosts ) == 0 :
2012-04-12 01:05:46 +00:00
self . callbacks . on_no_hosts ( )
2012-03-22 03:39:09 +00:00
return dict ( contacted = { } , dark = { } )
2012-08-07 00:07:02 +00:00
2012-10-23 12:04:32 +00:00
global multiprocessing_runner
multiprocessing_runner = self
2012-03-25 23:05:27 +00:00
results = None
2012-09-22 06:07:49 +00:00
# Check if this is an action plugin. Some of them are designed
# to be ran once per group of hosts. Example module: pause,
# run once per hostgroup, rather than pausing once per each
# host.
2012-11-01 23:41:50 +00:00
p = utils . plugins . action_loader . get ( self . module_name , self )
2013-03-09 23:30:18 +00:00
2013-07-24 00:43:14 +00:00
if self . forks == 0 or self . forks > len ( hosts ) :
self . forks = len ( hosts )
2014-05-15 15:47:17 +00:00
if ( p and ( getattr ( p , ' BYPASS_HOST_LOOP ' , None ) ) or self . run_once ) :
2013-02-17 20:01:49 +00:00
2012-09-22 06:07:49 +00:00
# Expose the current hostgroup to the bypassing plugins
self . host_set = hosts
# We aren't iterating over all the hosts in this
2014-12-11 16:47:24 +00:00
# group. So, just choose the "delegate_to" host if that is defined and is
# one of the targeted hosts, otherwise pick the first host in our group to
2012-09-22 06:07:49 +00:00
# construct the conn object with.
2014-12-11 16:47:24 +00:00
if self . delegate_to is not None and self . delegate_to in hosts :
host = self . delegate_to
else :
host = hosts [ 0 ]
result_data = self . _executor ( host , None ) . result
2012-09-22 06:07:49 +00:00
# Create a ResultData item for each host in this group
# using the returned result. If we didn't do this we would
# get false reports of dark hosts.
2012-10-23 12:04:32 +00:00
results = [ ReturnData ( host = h , result = result_data , comm_ok = True ) \
2012-09-22 06:07:49 +00:00
for h in hosts ]
del self . host_set
2013-02-17 20:01:49 +00:00
2012-09-22 06:07:49 +00:00
elif self . forks > 1 :
2012-10-24 11:46:24 +00:00
try :
results = self . _parallel_exec ( hosts )
except IOError , ie :
print ie . errno
if ie . errno == 32 :
# broken pipe from Ctrl+C
2013-06-02 20:03:41 +00:00
raise errors . AnsibleError ( " interrupted " )
2012-10-24 11:46:24 +00:00
raise
2012-03-22 03:39:09 +00:00
else :
2013-07-04 18:05:41 +00:00
results = [ self . _executor ( h , None ) for h in hosts ]
2013-07-05 05:24:08 +00:00
2012-03-22 03:39:09 +00:00
return self . _partition_results ( results )
2012-07-15 14:22:15 +00:00
# *****************************************************
2012-05-25 23:18:02 +00:00
def run_async ( self , time_limit ) :
2012-04-26 18:34:49 +00:00
''' Run this module asynchronously and return a poller. '''
2012-07-15 14:57:22 +00:00
2012-04-26 18:34:49 +00:00
self . background = time_limit
results = self . run ( )
2012-05-25 23:18:02 +00:00
return results , poller . AsyncPoller ( results , self )
2013-08-20 21:09:44 +00:00
# *****************************************************
def noop_on_check ( self , inject ) :
''' Should the runner run in check mode or not ? '''
# initialize self.always_run on first call
if self . always_run is None :
self . always_run = self . module_vars . get ( ' always_run ' , False )
self . always_run = check_conditional (
2014-01-04 00:13:21 +00:00
self . always_run , self . basedir , inject , fail_on_undefined = True )
2013-08-20 21:09:44 +00:00
return ( self . check and not self . always_run )