PageRenderTime 41ms CodeModel.GetById 19ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/ansible/plugins/action/script.py

https://github.com/debfx/ansible
Python | 152 lines | 103 code | 16 blank | 33 comment | 16 complexity | 8a019aac7a6985a8e4d178627670eb98 MD5 | raw file
  1# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
  2#
  3# This file is part of Ansible
  4#
  5# Ansible is free software: you can redistribute it and/or modify
  6# it under the terms of the GNU General Public License as published by
  7# the Free Software Foundation, either version 3 of the License, or
  8# (at your option) any later version.
  9#
 10# Ansible is distributed in the hope that it will be useful,
 11# but WITHOUT ANY WARRANTY; without even the implied warranty of
 12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 13# GNU General Public License for more details.
 14#
 15# You should have received a copy of the GNU General Public License
 16# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
 17from __future__ import (absolute_import, division, print_function)
 18__metaclass__ = type
 19
 20import os
 21import re
 22import shlex
 23
 24from ansible.errors import AnsibleError, AnsibleAction, _AnsibleActionDone, AnsibleActionFail, AnsibleActionSkip
 25from ansible.executor.powershell import module_manifest as ps_manifest
 26from ansible.module_utils._text import to_bytes, to_native, to_text
 27from ansible.plugins.action import ActionBase
 28
 29
 30class ActionModule(ActionBase):
 31
 32    TRANSFERS_FILES = True
 33
 34    # On Windows platform, absolute paths begin with a (back)slash
 35    # after chopping off a potential drive letter.
 36    windows_absolute_path_detection = re.compile(r'^(?:[a-zA-Z]\:)?(\\|\/)')
 37
 38    def run(self, tmp=None, task_vars=None):
 39        ''' handler for file transfer operations '''
 40        if task_vars is None:
 41            task_vars = dict()
 42
 43        result = super(ActionModule, self).run(tmp, task_vars)
 44        del tmp  # tmp no longer has any effect
 45
 46        try:
 47            creates = self._task.args.get('creates')
 48            if creates:
 49                # do not run the command if the line contains creates=filename
 50                # and the filename already exists. This allows idempotence
 51                # of command executions.
 52                if self._remote_file_exists(creates):
 53                    raise AnsibleActionSkip("%s exists, matching creates option" % creates)
 54
 55            removes = self._task.args.get('removes')
 56            if removes:
 57                # do not run the command if the line contains removes=filename
 58                # and the filename does not exist. This allows idempotence
 59                # of command executions.
 60                if not self._remote_file_exists(removes):
 61                    raise AnsibleActionSkip("%s does not exist, matching removes option" % removes)
 62
 63            # The chdir must be absolute, because a relative path would rely on
 64            # remote node behaviour & user config.
 65            chdir = self._task.args.get('chdir')
 66            if chdir:
 67                # Powershell is the only Windows-path aware shell
 68                if self._connection._shell.SHELL_FAMILY == 'powershell' and \
 69                        not self.windows_absolute_path_detection.match(chdir):
 70                    raise AnsibleActionFail('chdir %s must be an absolute path for a Windows remote node' % chdir)
 71                # Every other shell is unix-path-aware.
 72                if self._connection._shell.SHELL_FAMILY != 'powershell' and not chdir.startswith('/'):
 73                    raise AnsibleActionFail('chdir %s must be an absolute path for a Unix-aware remote node' % chdir)
 74
 75            # Split out the script as the first item in raw_params using
 76            # shlex.split() in order to support paths and files with spaces in the name.
 77            # Any arguments passed to the script will be added back later.
 78            raw_params = to_native(self._task.args.get('_raw_params', ''), errors='surrogate_or_strict')
 79            parts = [to_text(s, errors='surrogate_or_strict') for s in shlex.split(raw_params.strip())]
 80            source = parts[0]
 81
 82            # Support executable paths and files with spaces in the name.
 83            executable = to_native(self._task.args.get('executable', ''), errors='surrogate_or_strict')
 84
 85            try:
 86                source = self._loader.get_real_file(self._find_needle('files', source), decrypt=self._task.args.get('decrypt', True))
 87            except AnsibleError as e:
 88                raise AnsibleActionFail(to_native(e))
 89
 90            # now we execute script, always assume changed.
 91            result['changed'] = True
 92
 93            if not self._play_context.check_mode:
 94                # transfer the file to a remote tmp location
 95                tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir,
 96                                                            os.path.basename(source))
 97
 98                # Convert raw_params to text for the purpose of replacing the script since
 99                # parts and tmp_src are both unicode strings and raw_params will be different
100                # depending on Python version.
101                #
102                # Once everything is encoded consistently, replace the script path on the remote
103                # system with the remainder of the raw_params. This preserves quoting in parameters
104                # that would have been removed by shlex.split().
105                target_command = to_text(raw_params).strip().replace(parts[0], tmp_src)
106
107                self._transfer_file(source, tmp_src)
108
109                # set file permissions, more permissive when the copy is done as a different user
110                self._fixup_perms2((self._connection._shell.tmpdir, tmp_src), execute=True)
111
112                # add preparation steps to one ssh roundtrip executing the script
113                env_dict = dict()
114                env_string = self._compute_environment_string(env_dict)
115
116                if executable:
117                    script_cmd = ' '.join([env_string, executable, target_command])
118                else:
119                    script_cmd = ' '.join([env_string, target_command])
120
121            if self._play_context.check_mode:
122                raise _AnsibleActionDone()
123
124            script_cmd = self._connection._shell.wrap_for_exec(script_cmd)
125
126            exec_data = None
127            # PowerShell runs the script in a special wrapper to enable things
128            # like become and environment args
129            if self._connection._shell.SHELL_FAMILY == "powershell":
130                # FUTURE: use a more public method to get the exec payload
131                pc = self._play_context
132                exec_data = ps_manifest._create_powershell_wrapper(
133                    to_bytes(script_cmd), {}, env_dict, self._task.async_val,
134                    pc.become, pc.become_method, pc.become_user,
135                    pc.become_pass, pc.become_flags, substyle="script"
136                )
137                # build the necessary exec wrapper command
138                # FUTURE: this still doesn't let script work on Windows with non-pipelined connections or
139                # full manual exec of KEEP_REMOTE_FILES
140                script_cmd = self._connection._shell.build_module_command(env_string='', shebang='#!powershell', cmd='')
141
142            result.update(self._low_level_execute_command(cmd=script_cmd, in_data=exec_data, sudoable=True, chdir=chdir))
143
144            if 'rc' in result and result['rc'] != 0:
145                raise AnsibleActionFail('non-zero return code')
146
147        except AnsibleAction as e:
148            result.update(e.result)
149        finally:
150            self._remove_tmp_path(self._connection._shell.tmpdir)
151
152        return result