community.general/lib/ansible/playbook/play_context.py

435 lines
17 KiB
Python
Raw Normal View History

# -*- 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
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pipes
import random
import re
import string
from six import iteritems, string_types
from six.moves import range
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.playbook.attribute import Attribute, FieldAttribute
from ansible.playbook.base import Base
from ansible.template import Templar
from ansible.utils.boolean import boolean
from ansible.utils.unicode import to_unicode
__all__ = ['PlayContext']
# the magic variable mapping dictionary below is used to translate
# host/inventory variables to fields in the PlayContext
# object. The dictionary values are tuples, to account for aliases
# in variable names.
MAGIC_VARIABLE_MAPPING = dict(
connection = ('ansible_connection',),
remote_addr = ('ansible_ssh_host', 'ansible_host'),
remote_user = ('ansible_ssh_user', 'ansible_user'),
port = ('ansible_ssh_port', 'ansible_port'),
password = ('ansible_ssh_pass', 'ansible_password'),
private_key_file = ('ansible_ssh_private_key_file', 'ansible_private_key_file'),
shell = ('ansible_shell_type',),
become = ('ansible_become',),
become_method = ('ansible_become_method',),
become_user = ('ansible_become_user',),
become_pass = ('ansible_become_password','ansible_become_pass'),
become_exe = ('ansible_become_exe',),
become_flags = ('ansible_become_flags',),
sudo = ('ansible_sudo',),
sudo_user = ('ansible_sudo_user',),
sudo_pass = ('ansible_sudo_password', 'ansible_sudo_pass'),
sudo_exe = ('ansible_sudo_exe',),
sudo_flags = ('ansible_sudo_flags',),
su = ('ansible_su',),
su_user = ('ansible_su_user',),
su_pass = ('ansible_su_password', 'ansible_su_pass'),
su_exe = ('ansible_su_exe',),
su_flags = ('ansible_su_flags',),
)
SU_PROMPT_LOCALIZATIONS = [
'Password',
'암호',
'パスワード',
'Adgangskode',
'Contraseña',
'Contrasenya',
'Hasło',
'Heslo',
'Jelszó',
'Lösenord',
'Mật khẩu',
'Mot de passe',
'Parola',
'Parool',
'Pasahitza',
'Passord',
'Passwort',
'Salasana',
'Sandi',
'Senha',
'Wachtwoord',
'ססמה',
'Лозинка',
'Парола',
'Пароль',
'गुप्तशब्द',
'शब्दकूट',
'సంకేతపదము',
'හස්පදය',
'密码',
'密碼',
]
2015-07-31 21:51:26 +00:00
TASK_ATTRIBUTE_OVERRIDES = (
'become',
'become_user',
'become_pass',
'become_method',
'connection',
'delegate_to',
'no_log',
'remote_user',
)
class PlayContext(Base):
'''
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.
'''
# connection fields, some are inherited from Base:
# (connection, port, remote_user, environment, no_log)
_remote_addr = FieldAttribute(isa='string')
_password = FieldAttribute(isa='string')
_private_key_file = FieldAttribute(isa='string', default=C.DEFAULT_PRIVATE_KEY_FILE)
_timeout = FieldAttribute(isa='int', default=C.DEFAULT_TIMEOUT)
_shell = FieldAttribute(isa='string')
Squashed commit of the following: commit 9921bb9d2002e136c030ff337c14f8b7eab0fc72 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 20:19:44 2015 +0530 Document --ssh-extra-args command-line option commit 8b25595e7b1cc3658803d0821fbf498c18ee608a Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Thu Aug 13 13:24:57 2015 +0530 Don't disable GSSAPI/Pubkey authentication when using --ask-pass This commit is based on a bug report and PR by kolbyjack (#6846) which was subsequently closed and rebased as #11690. The original problem was: «The password on the delegated host is different from the one I provided on the command line, so it had to use the pubkey, and the main host doesn't have a pubkey on it yet, so it had to use the password.» (This commit is revised and included here because #11690 would conflict with the changes in #11908 otherwise.) Closes #11690 commit 119d0323892c65e8169ae57e42bbe8e3517551a3 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Thu Aug 13 11:16:42 2015 +0530 Be more explicit about why SSH arguments are added This adds vvvvv log messages that spell out in detail where each SSH command-line argument is obtained from. Unfortunately, we can't be sure if, say, self._play_context.remote_user is obtained from ANSIBLE_REMOTE_USER in the environment, remote_user in ansible.cfg, -u on the command line, or an ansible_ssh_user setting in the inventory or on a task or play. In some cases, e.g. timeout, we can't even be sure if it was set by the user or just a default. Nevertheless, on the theory that at five v's you can use all the hints available, I've mentioned the possible sources in the log messages. Note that this caveat applies only to the arguments that ssh.py adds by itself. In the case of ssh_args and ssh_extra_args, we know where they are from, and say so, though we can't say WHERE in the inventory they may be set (e.g. in host_vars or group_vars etc.). commit b605c285baf505f75f0b7d73cb76b00d4723d02e Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Tue Aug 11 15:19:43 2015 +0530 Add a FAQ entry about ansible_ssh_extra_args commit 49f8edd035cd28dd1cf8945f44ec3d55212910bd Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 20:48:50 2015 +0530 Allow ansible_ssh_args to be set as an inventory variable Before this change, ssh_args could be set only in the [ssh_connection] section of ansible.cfg, and was applied to all hosts. Now it's possible to set ansible_ssh_args as an inventory variable (directly, or through group_vars or host_vars) to selectively override the global setting. Note that the default ControlPath settings are applied only if ssh_args is not set, and this is true of ansible_ssh_args as well. So if you want to override ssh_args but continue to set ControlPath, you'll need to repeat the appropriate options when setting ansible_ssh_args. (If you only need to add options to the default ssh_args, you may be able to use the ansible_ssh_extra_args inventory variable instead.) commit 37c1a5b6794cee29a7809ad056a86365a2c0f886 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 19:42:30 2015 +0530 Allow overriding ansible_ssh_extra_args on the command-line This patch makes it possible to do: ansible somehost -m setup \ --ssh-extra-args '-o ProxyCommand="ssh -W %h:%p -q user@bouncer.example.com"' This overrides the inventory setting, if any, of ansible_ssh_extra_args. Based on a patch originally by @Richard2ndQuadrant. commit b023ace8a8a7ce6800e29129a27ebe8bf6bd38e0 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 19:06:19 2015 +0530 Add an ansible_ssh_extra_args inventory variable This can be used to configure a per-host or per-group ProxyCommand to connect to hosts through a jumphost, e.g.: inventory: [gatewayed] foo ansible_ssh_host=192.0.2.1 group_vars/gatewayed.yml: ansible_ssh_extra_args: '-o ProxyCommand="ssh -W %h:%p -q bounceuser@gateway.example.com"' Note that this variable is used in addition to any ssh_args configured in the [ssh_connection] section of ansible.cfg (so you don't need to repeat the ControlPath settings in ansible_ssh_extra_args).
2015-09-03 15:26:56 +00:00
_ssh_extra_args = FieldAttribute(isa='string')
2015-09-03 05:07:29 +00:00
_connection_lockfd= FieldAttribute(isa='int')
# privilege escalation fields
_become = FieldAttribute(isa='bool')
_become_method = FieldAttribute(isa='string')
_become_user = FieldAttribute(isa='string')
_become_pass = FieldAttribute(isa='string')
_become_exe = FieldAttribute(isa='string')
_become_flags = FieldAttribute(isa='string')
_prompt = FieldAttribute(isa='string')
# backwards compatibility fields for sudo/su
_sudo_exe = FieldAttribute(isa='string')
_sudo_flags = FieldAttribute(isa='string')
_sudo_pass = FieldAttribute(isa='string')
_su_exe = FieldAttribute(isa='string')
_su_flags = FieldAttribute(isa='string')
_su_pass = FieldAttribute(isa='string')
# general flags
_verbosity = FieldAttribute(isa='int', default=0)
_only_tags = FieldAttribute(isa='set', default=set())
_skip_tags = FieldAttribute(isa='set', default=set())
_check_mode = FieldAttribute(isa='bool', default=False)
_force_handlers = FieldAttribute(isa='bool', default=False)
_start_at_task = FieldAttribute(isa='string')
_step = FieldAttribute(isa='bool', default=False)
_diff = FieldAttribute(isa='bool', default=False)
def __init__(self, play=None, options=None, passwords=None, connection_lockfd=None):
super(PlayContext, self).__init__()
if passwords is None:
passwords = {}
self.password = passwords.get('conn_pass','')
self.become_pass = passwords.get('become_pass','')
self.prompt = ''
self.success_key = ''
2015-09-03 05:07:29 +00:00
# a file descriptor to be used during locking operations
self.connection_lockfd = connection_lockfd
# set options before play to allow play to override them
if options:
self.set_options(options)
if play:
self.set_play(play)
def set_play(self, play):
'''
Configures this connection information instance with data from
the play class.
'''
if play.connection:
self.connection = play.connection
if play.remote_user:
self.remote_user = play.remote_user
if play.port:
self.port = int(play.port)
if play.become is not None:
self.become = play.become
if play.become_method:
self.become_method = play.become_method
if play.become_user:
self.become_user = play.become_user
# non connection related
self.no_log = play.no_log
if play.force_handlers is not None:
self.force_handlers = play.force_handlers
def set_options(self, options):
'''
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.
'''
if options.connection:
self.connection = options.connection
self.remote_user = options.remote_user
self.private_key_file = options.private_key_file
Squashed commit of the following: commit 9921bb9d2002e136c030ff337c14f8b7eab0fc72 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 20:19:44 2015 +0530 Document --ssh-extra-args command-line option commit 8b25595e7b1cc3658803d0821fbf498c18ee608a Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Thu Aug 13 13:24:57 2015 +0530 Don't disable GSSAPI/Pubkey authentication when using --ask-pass This commit is based on a bug report and PR by kolbyjack (#6846) which was subsequently closed and rebased as #11690. The original problem was: «The password on the delegated host is different from the one I provided on the command line, so it had to use the pubkey, and the main host doesn't have a pubkey on it yet, so it had to use the password.» (This commit is revised and included here because #11690 would conflict with the changes in #11908 otherwise.) Closes #11690 commit 119d0323892c65e8169ae57e42bbe8e3517551a3 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Thu Aug 13 11:16:42 2015 +0530 Be more explicit about why SSH arguments are added This adds vvvvv log messages that spell out in detail where each SSH command-line argument is obtained from. Unfortunately, we can't be sure if, say, self._play_context.remote_user is obtained from ANSIBLE_REMOTE_USER in the environment, remote_user in ansible.cfg, -u on the command line, or an ansible_ssh_user setting in the inventory or on a task or play. In some cases, e.g. timeout, we can't even be sure if it was set by the user or just a default. Nevertheless, on the theory that at five v's you can use all the hints available, I've mentioned the possible sources in the log messages. Note that this caveat applies only to the arguments that ssh.py adds by itself. In the case of ssh_args and ssh_extra_args, we know where they are from, and say so, though we can't say WHERE in the inventory they may be set (e.g. in host_vars or group_vars etc.). commit b605c285baf505f75f0b7d73cb76b00d4723d02e Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Tue Aug 11 15:19:43 2015 +0530 Add a FAQ entry about ansible_ssh_extra_args commit 49f8edd035cd28dd1cf8945f44ec3d55212910bd Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 20:48:50 2015 +0530 Allow ansible_ssh_args to be set as an inventory variable Before this change, ssh_args could be set only in the [ssh_connection] section of ansible.cfg, and was applied to all hosts. Now it's possible to set ansible_ssh_args as an inventory variable (directly, or through group_vars or host_vars) to selectively override the global setting. Note that the default ControlPath settings are applied only if ssh_args is not set, and this is true of ansible_ssh_args as well. So if you want to override ssh_args but continue to set ControlPath, you'll need to repeat the appropriate options when setting ansible_ssh_args. (If you only need to add options to the default ssh_args, you may be able to use the ansible_ssh_extra_args inventory variable instead.) commit 37c1a5b6794cee29a7809ad056a86365a2c0f886 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 19:42:30 2015 +0530 Allow overriding ansible_ssh_extra_args on the command-line This patch makes it possible to do: ansible somehost -m setup \ --ssh-extra-args '-o ProxyCommand="ssh -W %h:%p -q user@bouncer.example.com"' This overrides the inventory setting, if any, of ansible_ssh_extra_args. Based on a patch originally by @Richard2ndQuadrant. commit b023ace8a8a7ce6800e29129a27ebe8bf6bd38e0 Author: Abhijit Menon-Sen <ams@2ndQuadrant.com> Date: Mon Aug 10 19:06:19 2015 +0530 Add an ansible_ssh_extra_args inventory variable This can be used to configure a per-host or per-group ProxyCommand to connect to hosts through a jumphost, e.g.: inventory: [gatewayed] foo ansible_ssh_host=192.0.2.1 group_vars/gatewayed.yml: ansible_ssh_extra_args: '-o ProxyCommand="ssh -W %h:%p -q bounceuser@gateway.example.com"' Note that this variable is used in addition to any ssh_args configured in the [ssh_connection] section of ansible.cfg (so you don't need to repeat the ControlPath settings in ansible_ssh_extra_args).
2015-09-03 15:26:56 +00:00
self.ssh_extra_args = options.ssh_extra_args
# privilege escalation
self.become = options.become
self.become_method = options.become_method
self.become_user = options.become_user
# general flags (should we move out?)
if options.verbosity:
self.verbosity = options.verbosity
#if options.no_log:
# self.no_log = boolean(options.no_log)
if options.check:
self.check_mode = boolean(options.check)
if hasattr(options, 'force_handlers') and options.force_handlers:
self.force_handlers = boolean(options.force_handlers)
if hasattr(options, 'step') and options.step:
self.step = boolean(options.step)
if hasattr(options, 'start_at_task') and options.start_at_task:
self.start_at_task = to_unicode(options.start_at_task)
if hasattr(options, 'diff') and options.diff:
self.diff = boolean(options.diff)
if hasattr(options, 'timeout') and options.timeout:
self.timeout = int(options.timeout)
# get the tag info from options, converting a comma-separated list
# of values into a proper list if need be. We check to see if the
# options have the attribute, as it is not always added via the CLI
if hasattr(options, 'tags'):
if isinstance(options.tags, list):
self.only_tags.update(options.tags)
elif isinstance(options.tags, string_types):
self.only_tags.update(options.tags.split(','))
if len(self.only_tags) == 0:
self.only_tags = set(['all'])
if hasattr(options, 'skip_tags'):
if isinstance(options.skip_tags, list):
self.skip_tags.update(options.skip_tags)
elif isinstance(options.skip_tags, string_types):
self.skip_tags.update(options.skip_tags.split(','))
def set_task_and_variable_override(self, task, variables, templar):
'''
Sets attributes from the task if they are set, which will override
those from the play.
'''
new_info = self.copy()
# loop through a subset of attributes on the task object and set
# connection fields based on their values
2015-07-31 21:51:26 +00:00
for attr in TASK_ATTRIBUTE_OVERRIDES:
if hasattr(task, attr):
attr_val = getattr(task, attr)
if attr_val is not None:
setattr(new_info, attr, attr_val)
# 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
if task.delegate_to is not None:
# 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())
else:
delegated_vars = dict()
for (attr, variable_names) in iteritems(MAGIC_VARIABLE_MAPPING):
for variable_name in variable_names:
if isinstance(delegated_vars, dict) and variable_name in delegated_vars:
setattr(new_info, attr, delegated_vars[variable_name])
elif variable_name in variables:
setattr(new_info, attr, variables[variable_name])
# make sure we get port defaults if needed
2015-07-31 17:49:48 +00:00
if new_info.port is None and C.DEFAULT_REMOTE_PORT is not None:
new_info.port = int(C.DEFAULT_REMOTE_PORT)
# become legacy updates
if not new_info.become_pass:
if new_info.become_method == 'sudo' and new_info.sudo_pass:
setattr(new_info, 'become_pass', new_info.sudo_pass)
elif new_info.become_method == 'su' and new_info.su_pass:
setattr(new_info, 'become_pass', new_info.su_pass)
# finally, in the special instance that the task was specified
# as a local action, override the connection in case it was changed
# during some other step in the process
if task._local_action:
setattr(new_info, 'connection', 'local')
return new_info
def make_become_cmd(self, cmd, executable=None):
""" helper function to create privilege escalation commands """
2015-03-13 16:57:27 +00:00
prompt = None
success_key = None
self.prompt = None
2015-03-13 16:57:27 +00:00
if executable is None:
executable = C.DEFAULT_EXECUTABLE
2015-03-13 20:31:20 +00:00
if self.become:
becomecmd = None
randbits = ''.join(random.choice(string.ascii_lowercase) for x in range(32))
success_key = 'BECOME-SUCCESS-%s' % randbits
success_cmd = pipes.quote('echo %s; %s' % (success_key, 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, None) or \
2015-09-02 13:52:26 +00:00
C.DEFAULT_BECOME_EXE or \
getattr(C, 'DEFAULT_%s_EXE' % self.become_method.upper(), None) or \
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, None) or \
C.DEFAULT_BECOME_FLAGS or \
getattr(C, 'DEFAULT_%s_FLAGS' % self.become_method.upper(), None) or \
''
2015-03-13 20:31:20 +00:00
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 -n, which makes
# it fail if it would have prompted for a password.
#
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell.
# 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" -S -u %s %s -c %s' % (exe, flags, prompt, self.become_user, executable, success_cmd)
else:
becomecmd = '%s %s -n -S -u %s %s -c %s' % (exe, flags, self.become_user, executable, success_cmd)
2015-03-13 20:31:20 +00:00
elif self.become_method == 'su':
def detect_su_prompt(data):
SU_PROMPT_LOCALIZATIONS_RE = re.compile("|".join(['(\w+\'s )?' + x + ' ?: ?' for x in SU_PROMPT_LOCALIZATIONS]), flags=re.IGNORECASE)
return bool(SU_PROMPT_LOCALIZATIONS_RE.match(data))
2015-06-15 05:07:02 +00:00
prompt = detect_su_prompt
becomecmd = '%s %s %s -c "%s -c %s"' % (exe, flags, self.become_user, executable, success_cmd)
2015-03-13 20:31:20 +00:00
elif self.become_method == 'pbrun':
prompt='assword:'
becomecmd = '%s -b %s -u %s %s' % (exe, flags, self.become_user, success_cmd)
2015-03-13 20:31:20 +00:00
elif self.become_method == 'pfexec':
2015-03-13 20:31:20 +00:00
# No user as it uses it's own exec_attr to figure it out
becomecmd = '%s %s "%s"' % (exe, flags, success_cmd)
2015-03-13 20:31:20 +00:00
2015-08-15 22:48:23 +00:00
elif self.become_method == 'runas':
raise AnsibleError("'runas' is not yet implemented")
#TODO: figure out prompt
# this is not for use with winrm plugin but if they ever get ssh native on windoez
becomecmd = '%s %s /user:%s "%s"' % (exe, flags, self.become_user, success_cmd)
2015-08-18 01:31:18 +00:00
elif self.become_method == 'doas':
prompt = 'Password:'
exe = self.become_exe or 'doas'
if not self.become_pass:
flags += ' -n '
if self.become_user:
flags += ' -u %s ' % self.become_user
becomecmd = '%s %s echo %s && %s %s env ANSIBLE=true %s' % (exe, flags, success_key, exe, flags, cmd)
2015-03-13 20:31:20 +00:00
else:
raise AnsibleError("Privilege escalation method not found: %s" % self.become_method)
2015-03-13 20:31:20 +00:00
if self.become_pass:
self.prompt = prompt
self.success_key = success_key
return ('%s -c %s' % (executable, pipes.quote(becomecmd)))
2015-03-13 20:31:20 +00:00
return cmd
def update_vars(self, variables):
'''
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.
'''
#FIXME: remove password? possibly add become/sudo settings
for special_var in ['ansible_connection', 'ansible_ssh_host', 'ansible_ssh_pass', 'ansible_ssh_port', 'ansible_ssh_user', 'ansible_ssh_private_key_file']:
if special_var not in variables:
for prop, varnames in MAGIC_VARIABLE_MAPPING.items():
if special_var in varnames:
variables[special_var] = getattr(self, prop)