1# -*- coding: utf-8 -*-
2
3# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
4#
5# This file is part of Ansible
6#
7# Ansible is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# Ansible is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
19
20# Make coding more python3-ish
21from __future__ import (absolute_import, division, print_function)
22__metaclass__ = type
23
24import os
25import sys
26
27from ansible import constants as C
28from ansible import context
29from ansible.errors import AnsibleError
30from ansible.module_utils.compat.paramiko import paramiko
31from ansible.module_utils.six import iteritems
32from ansible.playbook.attribute import FieldAttribute
33from ansible.playbook.base import Base
34from ansible.plugins import get_plugin_class
35from ansible.utils.display import Display
36from ansible.plugins.loader import get_shell_plugin
37from ansible.utils.ssh_functions import check_for_controlpersist
38
39
40display = Display()
41
42
43__all__ = ['PlayContext']
44
45
46TASK_ATTRIBUTE_OVERRIDES = (
47    'become',
48    'become_user',
49    'become_pass',
50    'become_method',
51    'become_flags',
52    'connection',
53    'docker_extra_args',  # TODO: remove
54    'delegate_to',
55    'no_log',
56    'remote_user',
57)
58
59RESET_VARS = (
60    'ansible_connection',
61    'ansible_user',
62    'ansible_host',
63    'ansible_port',
64
65    # TODO: ???
66    'ansible_docker_extra_args',
67    'ansible_ssh_host',
68    'ansible_ssh_pass',
69    'ansible_ssh_port',
70    'ansible_ssh_user',
71    'ansible_ssh_private_key_file',
72    'ansible_ssh_pipelining',
73    'ansible_ssh_executable',
74)
75
76
77class PlayContext(Base):
78
79    '''
80    This class is used to consolidate the connection information for
81    hosts in a play and child tasks, where the task may override some
82    connection/authentication information.
83    '''
84
85    # base
86    _module_compression = FieldAttribute(isa='string', default=C.DEFAULT_MODULE_COMPRESSION)
87    _shell = FieldAttribute(isa='string')
88    _executable = FieldAttribute(isa='string', default=C.DEFAULT_EXECUTABLE)
89
90    # connection fields, some are inherited from Base:
91    # (connection, port, remote_user, environment, no_log)
92    _remote_addr = FieldAttribute(isa='string')
93    _password = FieldAttribute(isa='string')
94    _timeout = FieldAttribute(isa='int', default=C.DEFAULT_TIMEOUT)
95    _connection_user = FieldAttribute(isa='string')
96    _private_key_file = FieldAttribute(isa='string', default=C.DEFAULT_PRIVATE_KEY_FILE)
97    _pipelining = FieldAttribute(isa='bool', default=C.ANSIBLE_PIPELINING)
98
99    # networking modules
100    _network_os = FieldAttribute(isa='string')
101
102    # docker FIXME: remove these
103    _docker_extra_args = FieldAttribute(isa='string')
104
105    # ???
106    _connection_lockfd = FieldAttribute(isa='int')
107
108    # privilege escalation fields
109    _become = FieldAttribute(isa='bool')
110    _become_method = FieldAttribute(isa='string')
111    _become_user = FieldAttribute(isa='string')
112    _become_pass = FieldAttribute(isa='string')
113    _become_exe = FieldAttribute(isa='string', default=C.DEFAULT_BECOME_EXE)
114    _become_flags = FieldAttribute(isa='string', default=C.DEFAULT_BECOME_FLAGS)
115    _prompt = FieldAttribute(isa='string')
116
117    # general flags
118    _verbosity = FieldAttribute(isa='int', default=0)
119    _only_tags = FieldAttribute(isa='set', default=set)
120    _skip_tags = FieldAttribute(isa='set', default=set)
121
122    _start_at_task = FieldAttribute(isa='string')
123    _step = FieldAttribute(isa='bool', default=False)
124
125    # "PlayContext.force_handlers should not be used, the calling code should be using play itself instead"
126    _force_handlers = FieldAttribute(isa='bool', default=False)
127
128    def __init__(self, play=None, passwords=None, connection_lockfd=None):
129        # Note: play is really not optional.  The only time it could be omitted is when we create
130        # a PlayContext just so we can invoke its deserialize method to load it from a serialized
131        # data source.
132
133        super(PlayContext, self).__init__()
134
135        if passwords is None:
136            passwords = {}
137
138        self.password = passwords.get('conn_pass', '')
139        self.become_pass = passwords.get('become_pass', '')
140
141        self._become_plugin = None
142
143        self.prompt = ''
144        self.success_key = ''
145
146        # a file descriptor to be used during locking operations
147        self.connection_lockfd = connection_lockfd
148
149        # set options before play to allow play to override them
150        if context.CLIARGS:
151            self.set_attributes_from_cli()
152
153        if play:
154            self.set_attributes_from_play(play)
155
156    def set_attributes_from_plugin(self, plugin):
157        # generic derived from connection plugin, temporary for backwards compat, in the end we should not set play_context properties
158
159        # get options for plugins
160        options = C.config.get_configuration_definitions(get_plugin_class(plugin), plugin._load_name)
161        for option in options:
162            if option:
163                flag = options[option].get('name')
164                if flag:
165                    setattr(self, flag, plugin.get_option(flag))
166
167    def set_attributes_from_play(self, play):
168        self.force_handlers = play.force_handlers
169
170    def set_attributes_from_cli(self):
171        '''
172        Configures this connection information instance with data from
173        options specified by the user on the command line. These have a
174        lower precedence than those set on the play or host.
175        '''
176        if context.CLIARGS.get('timeout', False):
177            self.timeout = int(context.CLIARGS['timeout'])
178
179        # From the command line.  These should probably be used directly by plugins instead
180        # For now, they are likely to be moved to FieldAttribute defaults
181        self.private_key_file = context.CLIARGS.get('private_key_file')  # Else default
182        self.verbosity = context.CLIARGS.get('verbosity')  # Else default
183
184        # Not every cli that uses PlayContext has these command line args so have a default
185        self.start_at_task = context.CLIARGS.get('start_at_task', None)  # Else default
186
187    def set_task_and_variable_override(self, task, variables, templar):
188        '''
189        Sets attributes from the task if they are set, which will override
190        those from the play.
191
192        :arg task: the task object with the parameters that were set on it
193        :arg variables: variables from inventory
194        :arg templar: templar instance if templating variables is needed
195        '''
196
197        new_info = self.copy()
198
199        # loop through a subset of attributes on the task object and set
200        # connection fields based on their values
201        for attr in TASK_ATTRIBUTE_OVERRIDES:
202            if hasattr(task, attr):
203                attr_val = getattr(task, attr)
204                if attr_val is not None:
205                    setattr(new_info, attr, attr_val)
206
207        # next, use the MAGIC_VARIABLE_MAPPING dictionary to update this
208        # connection info object with 'magic' variables from the variable list.
209        # If the value 'ansible_delegated_vars' is in the variables, it means
210        # we have a delegated-to host, so we check there first before looking
211        # at the variables in general
212        if task.delegate_to is not None:
213            # In the case of a loop, the delegated_to host may have been
214            # templated based on the loop variable, so we try and locate
215            # the host name in the delegated variable dictionary here
216            delegated_host_name = templar.template(task.delegate_to)
217            delegated_vars = variables.get('ansible_delegated_vars', dict()).get(delegated_host_name, dict())
218
219            delegated_transport = C.DEFAULT_TRANSPORT
220            for transport_var in C.MAGIC_VARIABLE_MAPPING.get('connection'):
221                if transport_var in delegated_vars:
222                    delegated_transport = delegated_vars[transport_var]
223                    break
224
225            # make sure this delegated_to host has something set for its remote
226            # address, otherwise we default to connecting to it by name. This
227            # may happen when users put an IP entry into their inventory, or if
228            # they rely on DNS for a non-inventory hostname
229            for address_var in ('ansible_%s_host' % delegated_transport,) + C.MAGIC_VARIABLE_MAPPING.get('remote_addr'):
230                if address_var in delegated_vars:
231                    break
232            else:
233                display.debug("no remote address found for delegated host %s\nusing its name, so success depends on DNS resolution" % delegated_host_name)
234                delegated_vars['ansible_host'] = delegated_host_name
235
236            # reset the port back to the default if none was specified, to prevent
237            # the delegated host from inheriting the original host's setting
238            for port_var in ('ansible_%s_port' % delegated_transport,) + C.MAGIC_VARIABLE_MAPPING.get('port'):
239                if port_var in delegated_vars:
240                    break
241            else:
242                if delegated_transport == 'winrm':
243                    delegated_vars['ansible_port'] = 5986
244                else:
245                    delegated_vars['ansible_port'] = C.DEFAULT_REMOTE_PORT
246
247            # and likewise for the remote user
248            for user_var in ('ansible_%s_user' % delegated_transport,) + C.MAGIC_VARIABLE_MAPPING.get('remote_user'):
249                if user_var in delegated_vars and delegated_vars[user_var]:
250                    break
251            else:
252                delegated_vars['ansible_user'] = task.remote_user or self.remote_user
253        else:
254            delegated_vars = dict()
255
256            # setup shell
257            for exe_var in C.MAGIC_VARIABLE_MAPPING.get('executable'):
258                if exe_var in variables:
259                    setattr(new_info, 'executable', variables.get(exe_var))
260
261        attrs_considered = []
262        for (attr, variable_names) in iteritems(C.MAGIC_VARIABLE_MAPPING):
263            for variable_name in variable_names:
264                if attr in attrs_considered:
265                    continue
266                # if delegation task ONLY use delegated host vars, avoid delegated FOR host vars
267                if task.delegate_to is not None:
268                    if isinstance(delegated_vars, dict) and variable_name in delegated_vars:
269                        setattr(new_info, attr, delegated_vars[variable_name])
270                        attrs_considered.append(attr)
271                elif variable_name in variables:
272                    setattr(new_info, attr, variables[variable_name])
273                    attrs_considered.append(attr)
274                # no else, as no other vars should be considered
275
276        # become legacy updates -- from inventory file (inventory overrides
277        # commandline)
278        for become_pass_name in C.MAGIC_VARIABLE_MAPPING.get('become_pass'):
279            if become_pass_name in variables:
280                break
281
282        # make sure we get port defaults if needed
283        if new_info.port is None and C.DEFAULT_REMOTE_PORT is not None:
284            new_info.port = int(C.DEFAULT_REMOTE_PORT)
285
286        # special overrides for the connection setting
287        if len(delegated_vars) > 0:
288            # in the event that we were using local before make sure to reset the
289            # connection type to the default transport for the delegated-to host,
290            # if not otherwise specified
291            for connection_type in C.MAGIC_VARIABLE_MAPPING.get('connection'):
292                if connection_type in delegated_vars:
293                    break
294            else:
295                remote_addr_local = new_info.remote_addr in C.LOCALHOST
296                inv_hostname_local = delegated_vars.get('inventory_hostname') in C.LOCALHOST
297                if remote_addr_local and inv_hostname_local:
298                    setattr(new_info, 'connection', 'local')
299                elif getattr(new_info, 'connection', None) == 'local' and (not remote_addr_local or not inv_hostname_local):
300                    setattr(new_info, 'connection', C.DEFAULT_TRANSPORT)
301
302        # we store original in 'connection_user' for use of network/other modules that fallback to it as login user
303        # connection_user to be deprecated once connection=local is removed for, as local resets remote_user
304        if new_info.connection == 'local':
305            if not new_info.connection_user:
306                new_info.connection_user = new_info.remote_user
307
308        # set no_log to default if it was not previously set
309        if new_info.no_log is None:
310            new_info.no_log = C.DEFAULT_NO_LOG
311
312        if task.check_mode is not None:
313            new_info.check_mode = task.check_mode
314
315        if task.diff is not None:
316            new_info.diff = task.diff
317
318        return new_info
319
320    def set_become_plugin(self, plugin):
321        self._become_plugin = plugin
322
323    def make_become_cmd(self, cmd, executable=None):
324        """ helper function to create privilege escalation commands """
325        display.deprecated(
326            "PlayContext.make_become_cmd should not be used, the calling code should be using become plugins instead",
327            version="2.12", collection_name='ansible.builtin'
328        )
329
330        if not cmd or not self.become:
331            return cmd
332
333        become_method = self.become_method
334
335        # load/call become plugins here
336        plugin = self._become_plugin
337
338        if plugin:
339            options = {
340                'become_exe': self.become_exe or become_method,
341                'become_flags': self.become_flags or '',
342                'become_user': self.become_user,
343                'become_pass': self.become_pass
344            }
345            plugin.set_options(direct=options)
346
347            if not executable:
348                executable = self.executable
349
350            shell = get_shell_plugin(executable=executable)
351            cmd = plugin.build_become_command(cmd, shell)
352            # for backwards compat:
353            if self.become_pass:
354                self.prompt = plugin.prompt
355        else:
356            raise AnsibleError("Privilege escalation method not found: %s" % become_method)
357
358        return cmd
359
360    def update_vars(self, variables):
361        '''
362        Adds 'magic' variables relating to connections to the variable dictionary provided.
363        In case users need to access from the play, this is a legacy from runner.
364        '''
365
366        for prop, var_list in C.MAGIC_VARIABLE_MAPPING.items():
367            try:
368                if 'become' in prop:
369                    continue
370
371                var_val = getattr(self, prop)
372                for var_opt in var_list:
373                    if var_opt not in variables and var_val is not None:
374                        variables[var_opt] = var_val
375            except AttributeError:
376                continue
377
378    def _get_attr_connection(self):
379        ''' connections are special, this takes care of responding correctly '''
380        conn_type = None
381        if self._attributes['connection'] == 'smart':
382            conn_type = 'ssh'
383            # see if SSH can support ControlPersist if not use paramiko
384            if not check_for_controlpersist('ssh') and paramiko is not None:
385                conn_type = "paramiko"
386
387        # if someone did `connection: persistent`, default it to using a persistent paramiko connection to avoid problems
388        elif self._attributes['connection'] == 'persistent' and paramiko is not None:
389            conn_type = 'paramiko'
390
391        if conn_type:
392            self.connection = conn_type
393
394        return self._attributes['connection']
395