Coverage for lib/ansible/playbook/play_context.py : 53%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*-
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
# TODO: needs to be configurable to_bytes('Password'), to_bytes('암호'), to_bytes('パスワード'), to_bytes('Adgangskode'), to_bytes('Contraseña'), to_bytes('Contrasenya'), to_bytes('Hasło'), to_bytes('Heslo'), to_bytes('Jelszó'), to_bytes('Lösenord'), to_bytes('Mật khẩu'), to_bytes('Mot de passe'), to_bytes('Parola'), to_bytes('Parool'), to_bytes('Pasahitza'), to_bytes('Passord'), to_bytes('Passwort'), to_bytes('Salasana'), to_bytes('Sandi'), to_bytes('Senha'), to_bytes('Wachtwoord'), to_bytes('ססמה'), to_bytes('Лозинка'), to_bytes('Парола'), to_bytes('Пароль'), to_bytes('गुप्तशब्द'), to_bytes('शब्दकूट'), to_bytes('సంకేతపదము'), to_bytes('හස්පදය'), to_bytes('密码'), to_bytes('密碼'), to_bytes('口令'), ]
'become', 'become_user', 'become_pass', 'become_method', 'become_flags', 'connection', 'docker_extra_args', # TODO: remove 'delegate_to', 'no_log', 'remote_user', )
'ansible_connection', 'ansible_user', 'ansible_host', 'ansible_port',
# TODO: ??? 'ansible_docker_extra_args', 'ansible_ssh_host', 'ansible_ssh_pass', 'ansible_ssh_port', 'ansible_ssh_user', 'ansible_ssh_private_key_file', 'ansible_ssh_pipelining', 'ansible_ssh_executable', )
'ssh_common_args', 'docker_extra_args', 'sftp_extra_args', 'scp_extra_args', 'ssh_extra_args')
''' This class is used to consolidate the connection information for hosts in a play and child tasks, where the task may override some connection/authentication information. '''
# base
# connection fields, some are inherited from Base: # (connection, port, remote_user, environment, no_log)
# networking modules
# docker FIXME: remove these
# ssh # FIXME: remove these
# ???
# privilege escalation fields
# DEPRECATED: backwards compatibility fields for sudo/su
# general flags
# Fact gathering settings
# a file descriptor to be used during locking operations
# set options before play to allow play to override them
''' Configures this connection information instance with data from the play class. '''
self.connection = play.connection
self.remote_user = play.remote_user
self.port = int(play.port)
self.become = play.become self.become_method = play.become_method self.become_user = play.become_user
self.force_handlers = play.force_handlers
# generic derived from connection plugin, temporary for backwards compat, in the end we should not set play_context properties
# get options for plugins setattr(self, flag, self.connection.get_option(flag))
# TODO: made irrelavent by above # get ssh options # for flag in ('ssh_common_args', 'docker_extra_args', 'sftp_extra_args', 'scp_extra_args', 'ssh_extra_args'): # setattr(self, flag, getattr(options, flag, ''))
''' Configures this connection information instance with data from options specified by the user on the command line. These have a lower precedence than those set on the play or host. '''
# privilege escalation
# general flags (should we move out?) # should only be 'non plugin' flags
# get the tag info from options. We check to see if the options have # the attribute, as it is not always added via the CLI
self.only_tags = set(['all'])
''' Sets attributes from the task if they are set, which will override those from the play.
:arg task: the task object with the parameters that were set on it :arg variables: variables from inventory :arg templar: templar instance if templating variables is needed '''
# loop through a subset of attributes on the task object and set # connection fields based on their values
# next, use the MAGIC_VARIABLE_MAPPING dictionary to update this # connection info object with 'magic' variables from the variable list. # If the value 'ansible_delegated_vars' is in the variables, it means # we have a delegated-to host, so we check there first before looking # at the variables in general # In the case of a loop, the delegated_to host may have been # templated based on the loop variable, so we try and locate # the host name in the delegated variable dictionary here delegated_host_name = templar.template(task.delegate_to) delegated_vars = variables.get('ansible_delegated_vars', dict()).get(delegated_host_name, dict())
delegated_transport = C.DEFAULT_TRANSPORT for transport_var in C.MAGIC_VARIABLE_MAPPING.get('connection'): if transport_var in delegated_vars: delegated_transport = delegated_vars[transport_var] break
# make sure this delegated_to host has something set for its remote # address, otherwise we default to connecting to it by name. This # may happen when users put an IP entry into their inventory, or if # they rely on DNS for a non-inventory hostname for address_var in ('ansible_%s_host' % delegated_transport,) + C.MAGIC_VARIABLE_MAPPING.get('remote_addr'): if address_var in delegated_vars: break else: display.debug("no remote address found for delegated host %s\nusing its name, so success depends on DNS resolution" % delegated_host_name) delegated_vars['ansible_host'] = delegated_host_name
# reset the port back to the default if none was specified, to prevent # the delegated host from inheriting the original host's setting for port_var in ('ansible_%s_port' % delegated_transport,) + C.MAGIC_VARIABLE_MAPPING.get('port'): if port_var in delegated_vars: break else: if delegated_transport == 'winrm': delegated_vars['ansible_port'] = 5986 else: delegated_vars['ansible_port'] = C.DEFAULT_REMOTE_PORT
# and likewise for the remote user for user_var in ('ansible_%s_user' % delegated_transport,) + C.MAGIC_VARIABLE_MAPPING.get('remote_user'): if user_var in delegated_vars and delegated_vars[user_var]: break else: delegated_vars['ansible_user'] = task.remote_user or self.remote_user else:
# setup shell
# if delegation task ONLY use delegated host vars, avoid delegated FOR host vars if isinstance(delegated_vars, dict) and variable_name in delegated_vars: setattr(new_info, attr, delegated_vars[variable_name]) attrs_considered.append(attr) # no else, as no other vars should be considered
# become legacy updates -- from commandline new_info.become_pass = new_info.sudo_pass new_info.become_pass = new_info.su_pass
# become legacy updates -- from inventory file (inventory overrides # commandline) break else: # This is a for-else setattr(new_info, 'become_pass', variables[sudo_pass_name]) break elif new_info.become_method == 'su': for su_pass_name in C.MAGIC_VARIABLE_MAPPING.get('su_pass'): if su_pass_name in variables: setattr(new_info, 'become_pass', variables[su_pass_name]) break
# make sure we get port defaults if needed new_info.port = int(C.DEFAULT_REMOTE_PORT)
# special overrides for the connection setting # in the event that we were using local before make sure to reset the # connection type to the default transport for the delegated-to host, # if not otherwise specified for connection_type in C.MAGIC_VARIABLE_MAPPING.get('connection'): if connection_type in delegated_vars: break else: remote_addr_local = new_info.remote_addr in C.LOCALHOST inv_hostname_local = delegated_vars.get('inventory_hostname') in C.LOCALHOST if remote_addr_local and inv_hostname_local: setattr(new_info, 'connection', 'local') elif getattr(new_info, 'connection', None) == 'local' and (not remote_addr_local or not inv_hostname_local): setattr(new_info, 'connection', C.DEFAULT_TRANSPORT)
# if the final connection type is local, reset the remote_user value to that of the currently logged in user # this ensures any become settings are obeyed correctly # we store original in 'connection_user' for use of network/other modules that fallback to it as login user # connection_user to be deprecated once connection=local is removed for # network modules
# set no_log to default if it was not previously set
display.deprecated("always_run is deprecated. Use check_mode = no instead.", version="2.4", removed=False) new_info.check_mode = False
# check_mode replaces always_run, overwrite always_run if both are given new_info.check_mode = task.check_mode
new_info.diff = task.diff
""" helper function to create privilege escalation commands """
prompt = None success_key = None self.prompt = None
if self.become:
if not executable: executable = self.executable
becomecmd = None randbits = ''.join(random.choice(string.ascii_lowercase) for x in range(32)) success_key = 'BECOME-SUCCESS-%s' % randbits success_cmd = shlex_quote('echo %s; %s' % (success_key, cmd))
if executable: command = '%s -c %s' % (executable, success_cmd) else: command = success_cmd
# set executable to use for the privilege escalation method, with various overrides exe = self.become_exe or getattr(self, '%s_exe' % self.become_method, self.become_method)
# set flags to use for the privilege escalation method, with various overrides flags = self.become_flags or getattr(self, '%s_flags' % self.become_method, '')
if self.become_method == 'sudo': # If we have a password, we run sudo with a randomly-generated # prompt set using -p. Otherwise we run it with default -n, which makes # it fail if it would have prompted for a password. # Cannot rely on -n as it can be removed from defaults, which should be # done for older versions of sudo that do not support the option. # # Passing a quoted compound command to sudo (or sudo -s) # directly doesn't work, so we shellquote it with shlex_quote() # and pass the quoted string to the user's shell.
# force quick error if password is required but not supplied, should prevent sudo hangs. if self.become_pass: prompt = '[sudo via ansible, key=%s] password: ' % randbits becomecmd = '%s %s -p "%s" -u %s %s' % (exe, flags.replace('-n', ''), prompt, self.become_user, command) else: becomecmd = '%s %s -u %s %s' % (exe, flags, self.become_user, command)
elif self.become_method == 'su':
# passing code ref to examine prompt as simple string comparisson isn't good enough with su def detect_su_prompt(b_data): b_password_string = b"|".join([br'(\w+\'s )?' + x for x in b_SU_PROMPT_LOCALIZATIONS]) # Colon or unicode fullwidth colon b_password_string = b_password_string + to_bytes(u' ?(:|:) ?') b_SU_PROMPT_LOCALIZATIONS_RE = re.compile(b_password_string, flags=re.IGNORECASE) return bool(b_SU_PROMPT_LOCALIZATIONS_RE.match(b_data)) prompt = detect_su_prompt
becomecmd = '%s %s %s -c %s' % (exe, flags, self.become_user, shlex_quote(command))
elif self.become_method == 'pbrun':
prompt = 'Password:' becomecmd = '%s %s -u %s %s' % (exe, flags, self.become_user, success_cmd)
elif self.become_method == 'ksu': def detect_ksu_prompt(b_data): return re.match(b"Kerberos password for .*@.*:", b_data)
prompt = detect_ksu_prompt becomecmd = '%s %s %s -e %s' % (exe, self.become_user, flags, command)
elif self.become_method == 'pfexec':
# No user as it uses it's own exec_attr to figure it out becomecmd = '%s %s "%s"' % (exe, flags, success_cmd)
elif self.become_method == 'runas': # become is handled inside the WinRM connection plugin if not self.become_user: raise AnsibleError(("The 'runas' become method requires a username " "(specify with the '--become-user' CLI arg, the 'become_user' keyword, or the 'ansible_become_user' variable)")) becomecmd = cmd
elif self.become_method == 'doas':
prompt = 'doas (%s@' % self.remote_user exe = self.become_exe or 'doas'
if not self.become_pass: flags += ' -n '
if self.become_user: flags += ' -u %s ' % self.become_user
# FIXME: make shell independent becomecmd = '%s %s echo %s && %s %s env ANSIBLE=true %s' % (exe, flags, success_key, exe, flags, cmd)
elif self.become_method == 'dzdo':
exe = self.become_exe or 'dzdo' if self.become_pass: prompt = '[dzdo via ansible, key=%s] password: ' % randbits becomecmd = '%s -p %s -u %s %s' % (exe, shlex_quote(prompt), self.become_user, command) else: becomecmd = '%s -u %s %s' % (exe, self.become_user, command)
elif self.become_method == 'pmrun':
exe = self.become_exe or 'pmrun'
prompt = 'Enter UPM user password:' becomecmd = '%s %s %s' % (exe, flags, shlex_quote(command))
else: raise AnsibleError("Privilege escalation method not found: %s" % self.become_method)
if self.become_pass: self.prompt = prompt self.success_key = success_key return becomecmd
return cmd
''' Adds 'magic' variables relating to connections to the variable dictionary provided. In case users need to access from the play, this is a legacy from runner. '''
''' connections are special, this takes care of responding correctly ''' # 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 conn_type = "paramiko" else: # see if SSH can support ControlPersist if not use paramiko conn_type = "paramiko"
# if someone did `connection: persistent`, default it to using a persistent paramiko connection to avoid problems conn_type = 'paramiko'
|