summaryrefslogtreecommitdiff
path: root/v2/ansible/executor/connection_info.py
blob: 5c48ff0089eb126d271591176aa735c90636ee63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# (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

from ansible import constants as C
from ansible.template import Templar
from ansible.utils.boolean import boolean


__all__ = ['ConnectionInformation']


class ConnectionInformation:

    '''
    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.
    '''

    def __init__(self, play=None, options=None):
        # FIXME: implement the new methodology here for supporting
        #        various different auth escalation methods (becomes, etc.)

        self.connection  = C.DEFAULT_TRANSPORT
        self.remote_user = 'root'
        self.password    = ''
        self.port        = 22
        self.su          = False
        self.su_user     = ''
        self.su_pass     = ''
        self.sudo        = False
        self.sudo_user   = ''
        self.sudo_pass   = ''
        self.verbosity   = 0
        self.only_tags   = set()
        self.skip_tags   = set()

        self.no_log      = False
        self.check_mode  = False

        if play:
            self.set_play(play)

        if options:
            self.set_options(options)

    def set_play(self, play):
        '''
        Configures this connection information instance with data from
        the play class.
        '''

        if play.connection:
            self.connection = play.connection

        self.remote_user = play.remote_user
        self.password    = ''
        self.port        = int(play.port) if play.port else 22
        self.su          = play.su
        self.su_user     = play.su_user
        self.su_pass     = play.su_pass
        self.sudo        = play.sudo
        self.sudo_user   = play.sudo_user
        self.sudo_pass   = play.sudo_pass

        # non connection related
        self.no_log      = play.no_log
        self.environment = play.environment

    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
        higher precedence than those set on the play or host.
        '''

        # FIXME: set other values from options here?

        self.verbosity = options.verbosity
        if options.connection:
            self.connection = options.connection

        if options.check:
            self.check_mode = boolean(options.check)

        # 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, basestring):
                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, basestring):
                self.skip_tags.update(options.skip_tags.split(','))

    def copy(self, ci):
        '''
        Copies the connection info from another connection info object, used
        when merging in data from task overrides.
        '''

        #self.connection  = ci.connection
        #self.remote_user = ci.remote_user
        #self.password    = ci.password
        #self.port        = ci.port
        #self.su          = ci.su
        #self.su_user     = ci.su_user
        #self.su_pass     = ci.su_pass
        #self.sudo        = ci.sudo
        #self.sudo_user   = ci.sudo_user
        #self.sudo_pass   = ci.sudo_pass
        #self.verbosity   = ci.verbosity

        # other
        #self.no_log      = ci.no_log
        #self.environment = ci.environment

        # requested tags
        #self.only_tags   = ci.only_tags.copy()
        #self.skip_tags   = ci.skip_tags.copy()

        for field in self._get_fields():
            value = getattr(ci, field, None)
            if isinstance(value, dict):
                setattr(self, field, value.copy())
            elif isinstance(value, set):
                setattr(self, field, value.copy())
            elif isinstance(value, list):
                setattr(self, field, value[:])
            else:
                setattr(self, field, value)

    def set_task_override(self, task):
        '''
        Sets attributes from the task if they are set, which will override
        those from the play.
        '''

        new_info = ConnectionInformation()
        new_info.copy(self)

        for attr in ('connection', 'remote_user', 'su', 'su_user', 'su_pass', 'sudo', 'sudo_user', 'sudo_pass', 'environment', 'no_log'):
            if hasattr(task, attr):
                attr_val = getattr(task, attr)
                if attr_val:
                    setattr(new_info, attr, attr_val)

        return new_info

    def make_sudo_cmd(self, sudo_exe, executable, cmd):
        """
        Helper function for wrapping commands with sudo.

        Rather than detect if sudo wants a password this time, -k makes
        sudo always ask for a password if one is required. 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.  We loop reading output until we see the randomly-
        generated sudo prompt set with the -p option.
        """

        randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
        prompt = '[sudo via ansible, key=%s] password: ' % randbits
        success_key = 'SUDO-SUCCESS-%s' % randbits

        sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % (
            sudo_exe, sudo_exe, C.DEFAULT_SUDO_FLAGS, prompt,
            self.sudo_user, executable or '$SHELL',
            pipes.quote('echo %s; %s' % (success_key, cmd))
        )

        # FIXME: old code, can probably be removed as it's been commented out for a while
        #return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
        return (sudocmd, prompt, success_key)

    def _get_fields(self):
        return [i for i in self.__dict__.keys() if i[:1] != '_']

    def post_validate(self, variables, loader):
        '''
        Finalizes templated values which may be set on this objects fields.
        '''

        templar = Templar(loader=loader, variables=variables)
        for field in self._get_fields():
            value = templar.template(getattr(self, field))
            setattr(self, field, value)