Moving ConnectionInformation -> PlayContext

Also making PlayContext a child class of the Playbook Base class,
which gives it access to all of the FieldAttribute code to ensure
field values are correctly typed after post_validation

Fixes #11381
This commit is contained in:
James Cammarata
2015-07-21 12:12:22 -04:00
parent 919aaa5c42
commit e64989beb4
36 changed files with 477 additions and 459 deletions

View File

@@ -31,7 +31,6 @@ from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.executor.module_common import modify_module
from ansible.parsing.utils.jsonify import jsonify
from ansible.utils.debug import debug
from ansible.utils.unicode import to_bytes
@@ -44,10 +43,10 @@ class ActionBase:
action in use.
'''
def __init__(self, task, connection, connection_info, loader, templar, shared_loader_obj):
def __init__(self, task, connection, play_context, loader, templar, shared_loader_obj):
self._task = task
self._connection = connection
self._connection_info = connection_info
self._play_context = play_context
self._loader = loader
self._templar = templar
self._shared_loader_obj = shared_loader_obj
@@ -82,16 +81,11 @@ class ActionBase:
Builds the environment string to be used when executing the remote task.
'''
enviro = {}
if self._task.environment:
if type(self._task.environment) != dict:
raise errors.AnsibleError("environment must be a dictionary, received %s" % self._task.environment)
# FIXME: not sure where this comes from, probably task but maybe also the play?
#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)
return self._connection._shell.env_prefix(**enviro)
return self._connection._shell.env_prefix(**self._task.environment)
def _early_needs_tmp_path(self):
'''
@@ -109,7 +103,7 @@ class ActionBase:
if tmp and "tmp" in tmp:
# tmp has already been created
return False
if not self._connection.__class__.has_pipelining or not C.ANSIBLE_SSH_PIPELINING or C.DEFAULT_KEEP_REMOTE_FILES or self._connection_info.become:
if not self._connection.__class__.has_pipelining or not C.ANSIBLE_SSH_PIPELINING or C.DEFAULT_KEEP_REMOTE_FILES or self._play_context.become:
# tmp is necessary to store module source code
return True
if not self._connection.__class__.has_pipelining:
@@ -131,11 +125,11 @@ class ActionBase:
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
use_system_tmp = False
if self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.become and self._play_context.become_user != 'root':
use_system_tmp = True
tmp_mode = None
if self._connection_info.remote_user != 'root' or self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.remote_user != 'root' or self._play_context.become and self._play_context.become_user != 'root':
tmp_mode = 'a+rx'
cmd = self._connection._shell.mkdtemp(basefile, use_system_tmp, tmp_mode)
@@ -149,7 +143,7 @@ class ActionBase:
output = 'Authentication failure.'
elif result['rc'] == 255 and self._connection.transport in ('ssh',):
if self._connection_info.verbosity > 3:
if self._play_context.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'
@@ -264,8 +258,8 @@ class ActionBase:
split_path = path.split(os.path.sep, 1)
expand_path = split_path[0]
if expand_path == '~':
if self._connection_info.become and self._connection_info.become_user:
expand_path = '~%s' % self._connection_info.become_user
if self._play_context.become and self._play_context.become_user:
expand_path = '~%s' % self._play_context.become_user
cmd = self._connection._shell.expand_user(expand_path)
debug("calling _low_level_execute_command to expand the remote user path")
@@ -314,13 +308,13 @@ class ActionBase:
module_args = self._task.args
# set check mode in the module arguments, if required
if self._connection_info.check_mode and not self._task.always_run:
if self._play_context.check_mode and not self._task.always_run:
if not self._supports_check_mode:
raise AnsibleError("check mode is not supported for this operation")
module_args['_ansible_check_mode'] = True
# set no log in the module arguments, if required
if self._connection_info.no_log:
if self._play_context.no_log:
module_args['_ansible_no_log'] = True
debug("in _execute_module (%s, %s)" % (module_name, module_args))
@@ -344,7 +338,7 @@ class ActionBase:
environment_string = self._compute_environment_string()
if tmp and "tmp" in tmp and self._connection_info.become and self._connection_info.become_user != 'root':
if tmp and "tmp" in tmp and self._play_context.become and self._play_context.become_user != 'root':
# deal with possible umask issues once sudo'ed to other user
self._remote_chmod(tmp, 'a+r', remote_module_path)
@@ -362,7 +356,7 @@ class ActionBase:
rm_tmp = None
if tmp and "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if not self._connection_info.become or self._connection_info.become_user == 'root':
if not self._play_context.become or self._play_context.become_user == 'root':
# not sudoing or sudoing to root, so can cleanup files in the same step
rm_tmp = tmp
@@ -380,7 +374,7 @@ class ActionBase:
debug("_low_level_execute_command returned ok")
if tmp and "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.become and self._play_context.become_user != 'root':
# not sudoing to root, so maybe can't delete files as that other user
# have to clean up temp files as original user in a second step
cmd2 = self._connection._shell.remove(tmp, recurse=True)
@@ -430,7 +424,7 @@ class ActionBase:
return dict(stdout='', stderr='')
if sudoable:
cmd = self._connection_info.make_become_cmd(cmd, executable=executable)
cmd = self._play_context.make_become_cmd(cmd, executable=executable)
debug("executing the command %s through the connection" % cmd)
rc, stdin, stdout, stderr = self._connection.exec_command(cmd, tmp, in_data=in_data, sudoable=sudoable)

View File

@@ -31,7 +31,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
if self._connection_info.check_mode:
if self._play_context.check_mode:
return dict(skipped=True, msg='check mode not supported for this module')
# Parse out any hostname:port patterns

View File

@@ -77,7 +77,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
if self._connection_info.check_mode:
if self._play_context.check_mode:
return dict(skipped=True, msg=("skipped, this module does not support check_mode."))
src = self._task.args.get('src', None)
@@ -124,7 +124,7 @@ class ActionModule(ActionBase):
xfered = self._transfer_data('src', resultant)
# fix file permissions when the copy is done as a different user
if self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.become and self._play_context.become_user != 'root':
self._remote_chmod('a+r', xfered, tmp)
# run the copy module

View File

@@ -28,7 +28,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
''' transfer the given module name, plus the async module, then run it '''
if self._connection_info.check_mode:
if self._play_context.check_mode:
return dict(skipped=True, msg='check mode not supported for this module')
if not tmp:

View File

@@ -179,7 +179,7 @@ class ActionModule(ActionBase):
# diff = {}
diff = {}
if self._connection_info.check_mode:
if self._play_context.check_mode:
self._remove_tempfile_if_content_defined(content, content_tempfile)
# FIXME: diff stuff
#diffs.append(diff)
@@ -199,7 +199,7 @@ class ActionModule(ActionBase):
self._remove_tempfile_if_content_defined(content, content_tempfile)
# fix file permissions when the copy is done as a different user
if self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.become and self._play_context.become_user != 'root':
self._remote_chmod('a+r', tmp_src, tmp)
if raw:

View File

@@ -36,7 +36,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
''' handler for fetch operations '''
if self._connection_info.check_mode:
if self._play_context.check_mode:
return dict(skipped=True, msg='check mode not (yet) supported for this module')
source = self._task.args.get('src', None)
@@ -59,7 +59,7 @@ class ActionModule(ActionBase):
# use slurp if sudo and permissions are lacking
remote_data = None
if remote_checksum in ('1', '2') or self._connection_info.become:
if remote_checksum in ('1', '2') or self._play_context.become:
slurpres = self._execute_module(module_name='slurp', module_args=dict(src=source), task_vars=task_vars, tmp=tmp)
if slurpres.get('rc') == 0:
if slurpres['encoding'] == 'base64':
@@ -97,7 +97,7 @@ class ActionModule(ActionBase):
if 'inventory_hostname' in task_vars:
target_name = task_vars['inventory_hostname']
else:
target_name = self._connection_info.remote_addr
target_name = self._play_context.remote_addr
dest = "%s/%s/%s" % (self._loader.path_dwim(dest), target_name, source_local)
dest = dest.replace("//","/")

View File

@@ -50,8 +50,8 @@ class ActionModule(ActionBase):
tmp_src = self._connection._shell.join_path(tmp, os.path.basename(src))
self._connection.put_file(src, tmp_src)
if self._connection_info.become and self._connection_info.become_user != 'root':
if not self._connection_info.check_mode:
if self._play_context.become and self._play_context.become_user != 'root':
if not self._play_context.check_mode:
self._remote_chmod('a+r', tmp_src, tmp)
new_module_args = self._task.args.copy()

View File

@@ -26,7 +26,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
if self._connection_info.check_mode:
if self._play_context.check_mode:
# in --check mode, always skip this module execution
return dict(skipped=True)

View File

@@ -28,7 +28,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
''' handler for file transfer operations '''
if self._connection_info.check_mode:
if self._play_context.check_mode:
return dict(skipped=True, msg='check mode not supported for this module')
if not tmp:
@@ -73,7 +73,7 @@ class ActionModule(ActionBase):
sudoable = True
# set file permissions, more permissive when the copy is done as a different user
if self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.become and self._play_context.become_user != 'root':
chmod_mode = 'a+rx'
sudoable = False
else:

View File

@@ -52,7 +52,7 @@ class ActionModule(ActionBase):
return path
def _process_remote(self, host, path, user):
transport = self._connection_info.connection
transport = self._play_context.connection
return_data = None
if not host in ['127.0.0.1', 'localhost'] or transport != "local":
if user:
@@ -71,7 +71,7 @@ class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=dict()):
''' generates params and passes them on to the rsync module '''
original_transport = task_vars.get('ansible_connection') or self._connection_info.connection
original_transport = task_vars.get('ansible_connection') or self._play_context.connection
transport_overridden = False
if task_vars.get('delegate_to') is None:
task_vars['delegate_to'] = '127.0.0.1'
@@ -79,7 +79,7 @@ class ActionModule(ActionBase):
if original_transport != 'local':
task_vars['ansible_connection'] = 'local'
transport_overridden = True
self._connection_info.become = False
self._play_context.become = False
src = self._task.args.get('src', None)
dest = self._task.args.get('dest', None)
@@ -130,13 +130,13 @@ class ActionModule(ActionBase):
user = task_vars['hostvars'][conn.delegate].get('ansible_ssh_user')
if not use_delegate or not user:
user = task_vars.get('ansible_ssh_user') or self._connection_info.remote_user
user = task_vars.get('ansible_ssh_user') or self._play_context.remote_user
if use_delegate:
# FIXME
private_key = task_vars.get('ansible_ssh_private_key_file') or self._connection_info.private_key_file
private_key = task_vars.get('ansible_ssh_private_key_file') or self._play_context.private_key_file
else:
private_key = task_vars.get('ansible_ssh_private_key_file') or self._connection_info.private_key_file
private_key = task_vars.get('ansible_ssh_private_key_file') or self._play_context.private_key_file
if private_key is not None:
private_key = os.path.expanduser(private_key)
@@ -159,7 +159,7 @@ class ActionModule(ActionBase):
rsync_path = self._task.args.get('rsync_path', None)
# If no rsync_path is set, sudo was originally set, and dest is remote then add 'sudo rsync' argument.
if not rsync_path and transport_overridden and self._connection_info.become and self._connection_info.become_method == 'sudo' and not dest_is_local:
if not rsync_path and transport_overridden and self._play_context.become and self._play_context.become_method == 'sudo' and not dest_is_local:
rsync_path = 'sudo rsync'
# make sure rsync path is quoted.

View File

@@ -142,7 +142,7 @@ class ActionModule(ActionBase):
xfered = self._transfer_data(self._connection._shell.join_path(tmp, 'source'), resultant)
# fix file permissions when the copy is done as a different user
if self._connection_info.become and self._connection_info.become_user != 'root':
if self._play_context.become and self._play_context.become_user != 'root':
self._remote_chmod('a+r', xfered, tmp)
# run the copy module

View File

@@ -78,8 +78,8 @@ class ActionModule(ActionBase):
# handle check mode client side
# fix file permissions when the copy is done as a different user
if copy:
if self._connection_info.become and self._connection_info.become_user != 'root':
if not self._connection_info.check_mode:
if self._play_context.become and self._play_context.become_user != 'root':
if not self._play_context.check_mode:
self._remote_chmod(tmp, 'a+r', tmp_src)
# Build temporary module_args.

View File

@@ -54,7 +54,7 @@ class CallbackBase:
for warning in res['warnings']:
self._display.warning(warning)
def set_connection_info(self, conn_info):
def set_play_context(self, play_context):
pass
def on_any(self, *args, **kwargs):

View File

@@ -58,14 +58,14 @@ class ConnectionBase(with_metaclass(ABCMeta, object)):
has_pipelining = False
become_methods = C.BECOME_METHODS
def __init__(self, connection_info, new_stdin, *args, **kwargs):
def __init__(self, play_context, new_stdin, *args, **kwargs):
# All these hasattrs allow subclasses to override these parameters
if not hasattr(self, '_connection_info'):
self._connection_info = connection_info
if not hasattr(self, '_play_context'):
self._play_context = play_context
if not hasattr(self, '_new_stdin'):
self._new_stdin = new_stdin
if not hasattr(self, '_display'):
self._display = Display(verbosity=connection_info.verbosity)
self._display = Display(verbosity=play_context.verbosity)
if not hasattr(self, '_connected'):
self._connected = False
@@ -73,8 +73,8 @@ class ConnectionBase(with_metaclass(ABCMeta, object)):
self.prompt = None
# load the shell plugin for this action/connection
if connection_info.shell:
shell_type = connection_info.shell
if play_context.shell:
shell_type = play_context.shell
elif hasattr(self, '_shell_type'):
shell_type = getattr(self, '_shell_type')
else:
@@ -87,7 +87,7 @@ class ConnectionBase(with_metaclass(ABCMeta, object)):
def _become_method_supported(self):
''' Checks if the current class supports this privilege escalation method '''
if self._connection_info.become_method in self.__class__.become_methods:
if self._play_context.become_method in self.__class__.become_methods:
return True
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method)
@@ -113,7 +113,7 @@ class ConnectionBase(with_metaclass(ABCMeta, object)):
"""Connect to the host we've been initialized with"""
# Check if PE is supported
if self._connection_info.become:
if self._play_context.become:
self.__become_method_supported()
@ensure_connect
@@ -140,18 +140,18 @@ class ConnectionBase(with_metaclass(ABCMeta, object)):
pass
def check_become_success(self, output):
return self._connection_info.success_key in output
return self._play_context.success_key in output
def check_password_prompt(self, output):
if self._connection_info.prompt is None:
if self._play_context.prompt is None:
return False
elif isinstance(self._connection_info.prompt, basestring):
return output.endswith(self._connection_info.prompt)
elif isinstance(self._play_context.prompt, basestring):
return output.endswith(self._play_context.prompt)
else:
return self._connection_info.prompt(output)
return self._play_context.prompt(output)
def check_incorrect_password(self, output):
incorrect_password = gettext.dgettext(self._connection_info.become_method, C.BECOME_ERROR_STRINGS[self._connection_info.become_method])
incorrect_password = gettext.dgettext(self._play_context.become_method, C.BECOME_ERROR_STRINGS[self._play_context.become_method])
if incorrect_password in output:
raise AnsibleError('Incorrect %s password' % self._connection_info.become_method)
raise AnsibleError('Incorrect %s password' % self._play_context.become_method)

View File

@@ -44,7 +44,7 @@ class Connection(ConnectionBase):
''' connect to the local host; nothing to do here '''
if not self._connected:
self._display.vvv("ESTABLISH LOCAL CONNECTION FOR USER: {0}".format(self._connection_info.remote_user, host=self._connection_info.remote_addr))
self._display.vvv("ESTABLISH LOCAL CONNECTION FOR USER: {0}".format(self._play_context.remote_user, host=self._play_context.remote_addr))
self._connected = True
return self
@@ -59,7 +59,7 @@ class Connection(ConnectionBase):
raise AnsibleError("Internal Error: this module does not support optimized module pipelining")
executable = C.DEFAULT_EXECUTABLE.split()[0] if C.DEFAULT_EXECUTABLE else None
self._display.vvv("{0} EXEC {1}".format(self._connection_info.remote_addr, cmd))
self._display.vvv("{0} EXEC {1}".format(self._play_context.remote_addr, cmd))
# FIXME: cwd= needs to be set to the basedir of the playbook
debug("opening command with Popen()")
p = subprocess.Popen(
@@ -72,13 +72,13 @@ class Connection(ConnectionBase):
)
debug("done running command with Popen()")
if self._connection_info.prompt and self._connection_info.become_pass:
if self._play_context.prompt and self._play_context.become_pass:
fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
fcntl.fcntl(p.stderr, fcntl.F_SETFL, fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
become_output = ''
while not self.check_become_success(become_output) and not self.check_password_prompt(become_output):
rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout, p.stderr], self._connection_info.timeout)
rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout, p.stderr], self._play_context.timeout)
if p.stdout in rfd:
chunk = p.stdout.read()
elif p.stderr in rfd:
@@ -91,7 +91,7 @@ class Connection(ConnectionBase):
raise AnsibleError('privilege output closed while waiting for password prompt:\n' + become_output)
become_output += chunk
if not self.check_become_success(become_output):
p.stdin.write(self._connection_info.become_pass + '\n')
p.stdin.write(self._play_context.become_pass + '\n')
fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)
fcntl.fcntl(p.stderr, fcntl.F_SETFL, fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK)
@@ -107,7 +107,7 @@ class Connection(ConnectionBase):
super(Connection, self).put_file(in_path, out_path)
self._display.vvv("{0} PUT {1} TO {2}".format(self._connection_info.remote_addr, in_path, out_path))
self._display.vvv("{0} PUT {1} TO {2}".format(self._play_context.remote_addr, in_path, out_path))
if not os.path.exists(in_path):
raise AnsibleFileNotFound("file or module does not exist: {0}".format(in_path))
try:
@@ -124,7 +124,7 @@ class Connection(ConnectionBase):
super(Connection, self).fetch_file(in_path, out_path)
self._display.vvv("{0} FETCH {1} TO {2}".format(self._connection_info.remote_addr, in_path, out_path))
self._display.vvv("{0} FETCH {1} TO {2}".format(self._play_context.remote_addr, in_path, out_path))
self.put_file(in_path, out_path)
def close(self):

View File

@@ -129,7 +129,7 @@ class Connection(ConnectionBase):
return 'paramiko'
def _cache_key(self):
return "%s__%s__" % (self._connection_info.remote_addr, self._connection_info.remote_user)
return "%s__%s__" % (self._play_context.remote_addr, self._play_context.remote_user)
def _connect(self):
cache_key = self._cache_key()
@@ -145,8 +145,8 @@ class Connection(ConnectionBase):
if not HAVE_PARAMIKO:
raise AnsibleError("paramiko is not installed")
port = self._connection_info.port or 22
self._display.vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (self._connection_info.remote_user, port, self._connection_info.remote_addr), host=self._connection_info.remote_addr)
port = self._play_context.port or 22
self._display.vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (self._play_context.remote_user, port, self._play_context.remote_addr), host=self._play_context.remote_addr)
ssh = paramiko.SSHClient()
@@ -159,22 +159,22 @@ class Connection(ConnectionBase):
allow_agent = True
if self._connection_info.password is not None:
if self._play_context.password is not None:
allow_agent = False
try:
key_filename = None
if self._connection_info.private_key_file:
key_filename = os.path.expanduser(self._connection_info.private_key_file)
if self._play_context.private_key_file:
key_filename = os.path.expanduser(self._play_context.private_key_file)
ssh.connect(
self._connection_info.remote_addr,
username=self._connection_info.remote_user,
self._play_context.remote_addr,
username=self._play_context.remote_user,
allow_agent=allow_agent,
look_for_keys=True,
key_filename=key_filename,
password=self._connection_info.password,
timeout=self._connection_info.timeout,
password=self._play_context.password,
timeout=self._play_context.timeout,
port=port,
)
except Exception as e:
@@ -183,7 +183,7 @@ class Connection(ConnectionBase):
raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
elif "Private key file is encrypted" in msg:
msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
self._connection_info.remote_user, self._connection_info.remote_addr, port, msg)
self._play_context.remote_user, self._play_context.remote_addr, port, msg)
raise AnsibleConnectionFailure(msg)
else:
raise AnsibleConnectionFailure(msg)
@@ -215,7 +215,7 @@ class Connection(ConnectionBase):
if C.PARAMIKO_PTY:
chan.get_pty(term=os.getenv('TERM', 'vt100'), width=int(os.getenv('COLUMNS', 0)), height=int(os.getenv('LINES', 0)))
self._display.vvv("EXEC %s" % cmd, host=self._connection_info.remote_addr)
self._display.vvv("EXEC %s" % cmd, host=self._play_context.remote_addr)
no_prompt_out = ''
no_prompt_err = ''
@@ -223,8 +223,8 @@ class Connection(ConnectionBase):
try:
chan.exec_command(cmd)
if self._connection_info.prompt:
if self._connection_info.become and self._connection_info.become_pass:
if self._play_context.prompt:
if self._play_context.become and self._play_context.become_pass:
while True:
debug('Waiting for Privilege Escalation input')
if self.check_become_success(become_output) or self.check_password_prompt(become_output):
@@ -240,8 +240,8 @@ class Connection(ConnectionBase):
'closed waiting for password prompt')
become_output += chunk
if not self.check_become_success(become_output):
if self._connection_info.become:
chan.sendall(self._connection_info.become_pass + '\n')
if self._play_context.become:
chan.sendall(self._play_context.become_pass + '\n')
else:
no_prompt_out += become_output
no_prompt_err += become_output
@@ -258,7 +258,7 @@ class Connection(ConnectionBase):
super(Connection, self).put_file(in_path, out_path)
self._display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._connection_info.remote_addr)
self._display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr)
if not os.path.exists(in_path):
raise AnsibleFileNotFound("file or module does not exist: %s" % in_path)
@@ -275,7 +275,7 @@ class Connection(ConnectionBase):
def _connect_sftp(self):
cache_key = "%s__%s__" % (self._connection_info.remote_addr, self._connection_info.remote_user)
cache_key = "%s__%s__" % (self._play_context.remote_addr, self._play_context.remote_user)
if cache_key in SFTP_CONNECTION_CACHE:
return SFTP_CONNECTION_CACHE[cache_key]
else:
@@ -287,7 +287,7 @@ class Connection(ConnectionBase):
super(Connection, self).fetch_file(in_path, out_path)
self._display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._connection_info.remote_addr)
self._display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr)
try:
self.sftp = self._connect_sftp()

View File

@@ -60,7 +60,7 @@ class Connection(ConnectionBase):
# FIXME: make this work, should be set from connection info
self._ipv6 = False
self.host = self._connection_info.remote_addr
self.host = self._play_context.remote_addr
if self._ipv6:
self.host = '[%s]' % self.host
@@ -72,7 +72,7 @@ class Connection(ConnectionBase):
def _connect(self):
''' connect to the remote host '''
self._display.vvv("ESTABLISH SSH CONNECTION FOR USER: {0}".format(self._connection_info.remote_user), host=self._connection_info.remote_addr)
self._display.vvv("ESTABLISH SSH CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self._play_context.remote_addr)
if self._connected:
return self
@@ -104,20 +104,20 @@ class Connection(ConnectionBase):
if not C.HOST_KEY_CHECKING:
self._common_args += ("-o", "StrictHostKeyChecking=no")
if self._connection_info.port is not None:
self._common_args += ("-o", "Port={0}".format(self._connection_info.port))
if self._connection_info.private_key_file is not None:
self._common_args += ("-o", "IdentityFile=\"{0}\"".format(os.path.expanduser(self._connection_info.private_key_file)))
if self._connection_info.password:
if self._play_context.port is not None:
self._common_args += ("-o", "Port={0}".format(self._play_context.port))
if self._play_context.private_key_file is not None:
self._common_args += ("-o", "IdentityFile=\"{0}\"".format(os.path.expanduser(self._play_context.private_key_file)))
if self._play_context.password:
self._common_args += ("-o", "GSSAPIAuthentication=no",
"-o", "PubkeyAuthentication=no")
else:
self._common_args += ("-o", "KbdInteractiveAuthentication=no",
"-o", "PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey",
"-o", "PasswordAuthentication=no")
if self._connection_info.remote_user is not None and self._connection_info.remote_user != pwd.getpwuid(os.geteuid())[0]:
self._common_args += ("-o", "User={0}".format(self._connection_info.remote_user))
self._common_args += ("-o", "ConnectTimeout={0}".format(self._connection_info.timeout))
if self._play_context.remote_user is not None and self._play_context.remote_user != pwd.getpwuid(os.geteuid())[0]:
self._common_args += ("-o", "User={0}".format(self._play_context.remote_user))
self._common_args += ("-o", "ConnectTimeout={0}".format(self._play_context.timeout))
self._connected = True
@@ -143,7 +143,7 @@ class Connection(ConnectionBase):
return (p, stdin)
def _password_cmd(self):
if self._connection_info.password:
if self._play_context.password:
try:
p = subprocess.Popen(["sshpass"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
@@ -154,9 +154,9 @@ class Connection(ConnectionBase):
return []
def _send_password(self):
if self._connection_info.password:
if self._play_context.password:
os.close(self.rfd)
os.write(self.wfd, "{0}\n".format(self._connection_info.password))
os.write(self.wfd, "{0}\n".format(self._play_context.password))
os.close(self.wfd)
def _communicate(self, p, stdin, indata, sudoable=True):
@@ -177,11 +177,11 @@ class Connection(ConnectionBase):
rfd, wfd, efd = select.select(rpipes, [], rpipes, 1)
# fail early if the become password is wrong
if self._connection_info.become and sudoable:
if self._connection_info.become_pass:
if self._play_context.become and sudoable:
if self._play_context.become_pass:
self.check_incorrect_password(stdout)
elif self.check_password_prompt(stdout):
raise AnsibleError('Missing %s password' % self._connection_info.become_method)
raise AnsibleError('Missing %s password' % self._play_context.become_method)
if p.stderr in rfd:
dat = os.read(p.stderr.fileno(), 9000)
@@ -335,7 +335,7 @@ class Connection(ConnectionBase):
# inside a tty automatically invokes the python interactive-mode but the modules are not
# compatible with the interactive-mode ("unexpected indent" mainly because of empty lines)
ssh_cmd.append("-tt")
if self._connection_info.verbosity > 3:
if self._play_context.verbosity > 3:
ssh_cmd.append("-vvv")
else:
ssh_cmd.append("-q")
@@ -358,7 +358,7 @@ class Connection(ConnectionBase):
no_prompt_out = ''
no_prompt_err = ''
if self._connection_info.prompt:
if self._play_context.prompt:
'''
Several cases are handled for privileges with password
* NOPASSWD (tty & no-tty): detect success_key on stdout
@@ -369,7 +369,7 @@ class Connection(ConnectionBase):
debug("Handling privilege escalation password prompt.")
if self._connection_info.become and self._connection_info.become_pass:
if self._play_context.become and self._play_context.become_pass:
fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
fcntl.fcntl(p.stderr, fcntl.F_SETFL, fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
@@ -381,7 +381,7 @@ class Connection(ConnectionBase):
if self.check_become_success(become_output) or self.check_password_prompt(become_output):
break
rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout], self._connection_info.timeout)
rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout], self._play_context.timeout)
if not rfd:
# timeout. wrap up process communication
stdout, stderr = p.communicate()
@@ -401,7 +401,7 @@ class Connection(ConnectionBase):
if not self.check_become_success(become_output):
debug("Sending privilege escalation password.")
stdin.write(self._connection_info.become_pass + '\n')
stdin.write(self._play_context.become_pass + '\n')
else:
no_prompt_out = become_output
no_prompt_err = become_errput
@@ -491,7 +491,7 @@ class Connection(ConnectionBase):
if 'ControlMaster' in self._common_args:
cmd = ['ssh','-O','stop']
cmd.extend(self._common_args)
cmd.append(self._connection_info.remote_addr)
cmd.append(self._play_context.remote_addr)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

View File

@@ -78,28 +78,28 @@ class Connection(ConnectionBase):
'''
Establish a WinRM connection over HTTP/HTTPS.
'''
port = self._connection_info.port or 5986
port = self._play_context.port or 5986
self._display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" % \
(self._connection_info.remote_user, port, self._connection_info.remote_addr), host=self._connection_info.remote_addr)
netloc = '%s:%d' % (self._connection_info.remote_addr, port)
(self._play_context.remote_user, port, self._play_context.remote_addr), host=self._play_context.remote_addr)
netloc = '%s:%d' % (self._play_context.remote_addr, port)
exc = None
for transport, scheme in self.transport_schemes['http' if port == 5985 else 'https']:
if transport == 'kerberos' and (not HAVE_KERBEROS or not '@' in self._connection_info.remote_user):
if transport == 'kerberos' and (not HAVE_KERBEROS or not '@' in self._play_context.remote_user):
continue
if transport == 'kerberos':
realm = self._connection_info.remote_user.split('@', 1)[1].strip() or None
realm = self._play_context.remote_user.split('@', 1)[1].strip() or None
else:
realm = None
endpoint = parse.urlunsplit((scheme, netloc, '/wsman', '', ''))
self._display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._connection_info.remote_addr)
self._display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._play_context.remote_addr)
protocol = Protocol(
endpoint,
transport=transport,
username=self._connection_info.remote_user,
password=self._connection_info.password,
username=self._play_context.remote_user,
password=self._play_context.password,
realm=realm
)
@@ -117,16 +117,16 @@ class Connection(ConnectionBase):
raise AnsibleError("the username/password specified for this server was incorrect")
elif code == 411:
return protocol
self._display.vvvvv('WINRM CONNECTION ERROR: %s' % err_msg, host=self._connection_info.remote_addr)
self._display.vvvvv('WINRM CONNECTION ERROR: %s' % err_msg, host=self._play_context.remote_addr)
continue
if exc:
raise AnsibleError(str(exc))
def _winrm_exec(self, command, args=(), from_exec=False):
if from_exec:
self._display.vvvvv("WINRM EXEC %r %r" % (command, args), host=self._connection_info.remote_addr)
self._display.vvvvv("WINRM EXEC %r %r" % (command, args), host=self._play_context.remote_addr)
else:
self._display.vvvvvv("WINRM EXEC %r %r" % (command, args), host=self._connection_info.remote_addr)
self._display.vvvvvv("WINRM EXEC %r %r" % (command, args), host=self._play_context.remote_addr)
if not self.protocol:
self.protocol = self._winrm_connect()
if not self.shell_id:
@@ -136,11 +136,11 @@ class Connection(ConnectionBase):
command_id = self.protocol.run_command(self.shell_id, command, args)
response = Response(self.protocol.get_command_output(self.shell_id, command_id))
if from_exec:
self._display.vvvvv('WINRM RESULT %r' % response, host=self._connection_info.remote_addr)
self._display.vvvvv('WINRM RESULT %r' % response, host=self._play_context.remote_addr)
else:
self._display.vvvvvv('WINRM RESULT %r' % response, host=self._connection_info.remote_addr)
self._display.vvvvvv('WINRM STDOUT %s' % response.std_out, host=self._connection_info.remote_addr)
self._display.vvvvvv('WINRM STDERR %s' % response.std_err, host=self._connection_info.remote_addr)
self._display.vvvvvv('WINRM RESULT %r' % response, host=self._play_context.remote_addr)
self._display.vvvvvv('WINRM STDOUT %s' % response.std_out, host=self._play_context.remote_addr)
self._display.vvvvvv('WINRM STDERR %s' % response.std_err, host=self._play_context.remote_addr)
return response
finally:
if command_id:
@@ -159,9 +159,9 @@ class Connection(ConnectionBase):
if '-EncodedCommand' in cmd_parts:
encoded_cmd = cmd_parts[cmd_parts.index('-EncodedCommand') + 1]
decoded_cmd = base64.b64decode(encoded_cmd)
self._display.vvv("EXEC %s" % decoded_cmd, host=self._connection_info.remote_addr)
self._display.vvv("EXEC %s" % decoded_cmd, host=self._play_context.remote_addr)
else:
self._display.vvv("EXEC %s" % cmd, host=self._connection_info.remote_addr)
self._display.vvv("EXEC %s" % cmd, host=self._play_context.remote_addr)
# For script/raw support.
if cmd_parts and cmd_parts[0].lower().endswith('.ps1'):
script = self._shell._build_file_cmd(cmd_parts, quote_args=False)
@@ -178,7 +178,7 @@ class Connection(ConnectionBase):
def put_file(self, in_path, out_path):
super(Connection, self).put_file(in_path, out_path)
self._display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._connection_info.remote_addr)
self._display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr)
if not os.path.exists(in_path):
raise AnsibleFileNotFound("file or module does not exist: %s" % in_path)
with open(in_path) as in_file:
@@ -206,7 +206,7 @@ class Connection(ConnectionBase):
out_path = out_path + '.ps1'
b64_data = base64.b64encode(out_data)
script = script_template % (self._shell._escape(out_path), offset, b64_data, in_size)
self._display.vvvvv("WINRM PUT %s to %s (offset=%d size=%d)" % (in_path, out_path, offset, len(out_data)), host=self._connection_info.remote_addr)
self._display.vvvvv("WINRM PUT %s to %s (offset=%d size=%d)" % (in_path, out_path, offset, len(out_data)), host=self._play_context.remote_addr)
cmd_parts = self._shell._encode_script(script, as_list=True)
result = self._winrm_exec(cmd_parts[0], cmd_parts[1:])
if result.status_code != 0:
@@ -219,7 +219,7 @@ class Connection(ConnectionBase):
super(Connection, self).fetch_file(in_path, out_path)
out_path = out_path.replace('\\', '/')
self._display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._connection_info.remote_addr)
self._display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr)
buffer_size = 2**19 # 0.5MB chunks
makedirs_safe(os.path.dirname(out_path))
out_file = None
@@ -248,7 +248,7 @@ class Connection(ConnectionBase):
Exit 1;
}
''' % dict(buffer_size=buffer_size, path=self._shell._escape(in_path), offset=offset)
self._display.vvvvv("WINRM FETCH %s to %s (offset=%d)" % (in_path, out_path, offset), host=self._connection_info.remote_addr)
self._display.vvvvv("WINRM FETCH %s to %s (offset=%d)" % (in_path, out_path, offset), host=self._play_context.remote_addr)
cmd_parts = self._shell._encode_script(script, as_list=True)
result = self._winrm_exec(cmd_parts[0], cmd_parts[1:])
if result.status_code != 0:

View File

@@ -74,14 +74,14 @@ class StrategyBase:
# outstanding tasks still in queue
self._blocked_hosts = dict()
def run(self, iterator, connection_info, result=True):
def run(self, iterator, play_context, result=True):
# save the failed/unreachable hosts, as the run_handlers()
# method will clear that information during its execution
failed_hosts = self._tqm._failed_hosts.keys()
unreachable_hosts = self._tqm._unreachable_hosts.keys()
debug("running handlers")
result &= self.run_handlers(iterator, connection_info)
result &= self.run_handlers(iterator, play_context)
# now update with the hosts (if any) that failed or were
# unreachable during the handler execution phase
@@ -117,7 +117,7 @@ class StrategyBase:
new_vars['ansible_failed_hosts'] = self.get_failed_hosts(play)
return new_vars
def _queue_task(self, host, task, task_vars, connection_info):
def _queue_task(self, host, task, task_vars, play_context):
''' handles queueing the task up to be sent to a worker '''
debug("entering _queue_task() for %s/%s" % (host, task))
@@ -136,7 +136,7 @@ class StrategyBase:
# way to share them with the forked processes
shared_loader_obj = SharedPluginLoaderObj()
main_q.put((host, task, self._loader.get_basedir(), task_vars, connection_info, shared_loader_obj), block=False)
main_q.put((host, task, self._loader.get_basedir(), task_vars, play_context, shared_loader_obj), block=False)
self._pending_results += 1
except (EOFError, IOError, AssertionError) as e:
# most likely an abort
@@ -406,7 +406,7 @@ class StrategyBase:
return block_list
def run_handlers(self, iterator, connection_info):
def run_handlers(self, iterator, play_context):
'''
Runs handlers on those hosts which have been notified.
'''
@@ -427,10 +427,10 @@ class StrategyBase:
# break
self._tqm.send_callback('v2_playbook_on_handler_task_start', handler)
for host in self._notified_handlers[handler_name]:
if not handler.has_triggered(host) and (host.name not in self._tqm._failed_hosts or connection_info.force_handlers):
if not handler.has_triggered(host) and (host.name not in self._tqm._failed_hosts or play_context.force_handlers):
task_vars = self._variable_manager.get_vars(loader=self._loader, play=iterator._play, host=host, task=handler)
task_vars = self.add_tqm_variables(task_vars, play=iterator._play)
self._queue_task(host, handler, task_vars, connection_info)
self._queue_task(host, handler, task_vars, play_context)
#handler.flag_for_host(host)
self._process_pending_results(iterator)
self._wait_on_pending_results(iterator)

View File

@@ -26,7 +26,7 @@ from ansible.utils.debug import debug
class StrategyModule(StrategyBase):
def run(self, iterator, connection_info):
def run(self, iterator, play_context):
'''
The "free" strategy is a bit more complex, in that it allows tasks to
be sent to hosts as quickly as they can be processed. This means that
@@ -97,7 +97,7 @@ class StrategyModule(StrategyBase):
debug("'%s' skipped because role has already run" % task)
continue
if not task.evaluate_tags(connection_info.only_tags, connection_info.skip_tags, task_vars) and task.action != 'setup':
if not task.evaluate_tags(play_context.only_tags, play_context.skip_tags, task_vars) and task.action != 'setup':
debug("'%s' failed tag evaluation" % task)
continue
@@ -111,14 +111,14 @@ class StrategyModule(StrategyBase):
elif meta_action == 'flush_handlers':
# FIXME: in the 'free' mode, flushing handlers should result in
# only those handlers notified for the host doing the flush
self.run_handlers(iterator, connection_info)
self.run_handlers(iterator, play_context)
else:
raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds)
self._blocked_hosts[host_name] = False
else:
self._tqm.send_callback('v2_playbook_on_task_start', task, is_conditional=False)
self._queue_task(host, task, task_vars, connection_info)
self._queue_task(host, task, task_vars, play_context)
# move on to the next host and make sure we
# haven't gone past the end of our hosts list
@@ -147,5 +147,5 @@ class StrategyModule(StrategyBase):
# run the base class run() method, which executes the cleanup function
# and runs any outstanding handlers which have been triggered
super(StrategyModule, self).run(iterator, connection_info)
super(StrategyModule, self).run(iterator, play_context)

View File

@@ -116,7 +116,7 @@ class StrategyModule(StrategyBase):
# return None for all hosts in the list
return [(host, None) for host in hosts]
def run(self, iterator, connection_info):
def run(self, iterator, play_context):
'''
The linear strategy is simple - get the next task and queue
it for all hosts, then wait for the queue to drain before
@@ -177,7 +177,7 @@ class StrategyModule(StrategyBase):
# FIXME: issue a callback for the noop here?
continue
elif meta_action == 'flush_handlers':
self.run_handlers(iterator, connection_info)
self.run_handlers(iterator, play_context)
else:
raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds)
else:
@@ -194,7 +194,7 @@ class StrategyModule(StrategyBase):
callback_sent = True
self._blocked_hosts[host.get_name()] = True
self._queue_task(host, task, task_vars, connection_info)
self._queue_task(host, task, task_vars, play_context)
results = self._process_pending_results(iterator)
host_results.extend(results)
@@ -245,7 +245,7 @@ class StrategyModule(StrategyBase):
for host in hosts_left:
if host in included_file._hosts:
task_vars = self._variable_manager.get_vars(loader=self._loader, play=iterator._play, host=host, task=included_file._task)
final_block = new_block.filter_tagged_tasks(connection_info, task_vars)
final_block = new_block.filter_tagged_tasks(play_context, task_vars)
all_blocks[host].append(final_block)
else:
all_blocks[host].append(noop_block)
@@ -262,5 +262,5 @@ class StrategyModule(StrategyBase):
# run the base class run() method, which executes the cleanup function
# and runs any outstanding handlers which have been triggered
return super(StrategyModule, self).run(iterator, connection_info, result)
return super(StrategyModule, self).run(iterator, play_context, result)