Debian Codegraph @

lib/ansible/plugins/action/script.py

raw
1 # (c) 2012, Michael DeHaan <[email protected]>
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/>.
17 from __future__ import annotations
18
19 import os
20 import pathlib
21 import re
22 import shlex
23 import typing as _t
24
25 from ansible._internal._powershell import _script as _ps_script
26 from ansible.errors import AnsibleError, AnsibleActionFail
27 from ansible.executor.powershell import module_manifest as ps_manifest
28 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
29 from ansible.plugins.action import ActionBase
30
31
32 class ActionModule(ActionBase):
33
34 TRANSFERS_FILES = True
35
36 # On Windows platform, absolute paths begin with a (back)slash
37 # after chopping off a potential drive letter.
38 windows_absolute_path_detection = re.compile(r'^(?:[a-zA-Z]\:)?(\\|\/)')
39
40 def run(self, tmp: str | None = None, task_vars: dict[str, _t.Any] | None = None) -> dict[str, _t.Any]:
41 """ handler for file transfer operations """
42 if task_vars is None:
43 task_vars = dict()
44
45 validation_result, new_module_args = self.validate_argument_spec(
46 argument_spec={
47 '_raw_params': {},
48 'cmd': {'type': 'str'},
49 'creates': {'type': 'str'},
50 'removes': {'type': 'str'},
51 'chdir': {'type': 'str'},
52 'executable': {'type': 'str'},
53 },
54 required_one_of=[['_raw_params', 'cmd']],
55 mutually_exclusive=[['_raw_params', 'cmd']],
56 )
57
58 super(ActionModule, self).run(tmp, task_vars)
59 del tmp # tmp no longer has any effect
60
61 try:
62 creates = new_module_args['creates']
63 if creates:
64 # do not run the command if the line contains creates=filename
65 # and the filename already exists. This allows idempotence
66 # of command executions.
67 if self._remote_file_exists(creates):
68 return dict(
69 changed=False,
70 skipped=True, # deprecated: description='remove this skipped return', core_version='2.25'
71 msg=f'{creates} exists, matching creates option',
72 )
73
74 removes = new_module_args['removes']
75 if removes:
76 # do not run the command if the line contains removes=filename
77 # and the filename does not exist. This allows idempotence
78 # of command executions.
79 if not self._remote_file_exists(removes):
80 return dict(
81 changed=False,
82 skipped=True, # deprecated: description='remove this skipped return', core_version='2.25'
83 msg=f'{removes} does not exist, matching removes option',
84 )
85
86 # The chdir must be absolute, because a relative path would rely on
87 # remote node behaviour & user config.
88 chdir = new_module_args['chdir']
89 if chdir:
90 # Powershell is the only Windows-path aware shell
91 if getattr(self._connection._shell, "_IS_WINDOWS", False) and \
92 not self.windows_absolute_path_detection.match(chdir):
93 raise AnsibleActionFail('chdir %s must be an absolute path for a Windows remote node' % chdir)
94 # Every other shell is unix-path-aware.
95 if not getattr(self._connection._shell, "_IS_WINDOWS", False) and not chdir.startswith('/'):
96 raise AnsibleActionFail('chdir %s must be an absolute path for a Unix-aware remote node' % chdir)
97
98 # Split out the script as the first item in raw_params using
99 # shlex.split() in order to support paths and files with spaces in the name.
100 # Any arguments passed to the script will be added back later.
101 raw_params = new_module_args['_raw_params'] or new_module_args['cmd']
102 parts = [to_text(s, errors='surrogate_or_strict') for s in shlex.split(raw_params.strip())]
103 source = parts[0]
104
105 # Support executable paths and files with spaces in the name.
106 executable = new_module_args['executable']
107 if executable:
108 executable = to_native(new_module_args['executable'], errors='surrogate_or_strict')
109 try:
110 source = self._loader.get_real_file(self._find_needle('files', source))
111 except AnsibleError as e:
112 raise AnsibleActionFail(to_native(e))
113
114 if self._task.check_mode:
115 # check mode is supported if 'creates' or 'removes' are provided
116 # the task has already been skipped if a change would not occur
117 if new_module_args['creates'] or new_module_args['removes']:
118 return dict(changed=True)
119 # If the script doesn't return changed in the result, it defaults to True,
120 # but since the script may override 'changed', just skip instead of guessing.
121 else:
122 return dict(
123 msg='Check mode is not supported for this task.',
124 changed=False,
125 skipped=True, # deprecated: description='remove this skipped return', core_version='2.25'
126 )
127
128 # transfer the file to a remote tmp location
129 tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir,
130 os.path.basename(source))
131
132 # Convert raw_params to text for the purpose of replacing the script since
133 # parts and tmp_src are both unicode strings and raw_params will be different
134 # depending on Python version.
135 #
136 # Once everything is encoded consistently, replace the script path on the remote
137 # system with the remainder of the raw_params. This preserves quoting in parameters
138 # that would have been removed by shlex.split().
139 target_command = to_text(raw_params).strip().replace(parts[0], tmp_src)
140
141 self._transfer_file(source, tmp_src)
142
143 # set file permissions, more permissive when the copy is done as a different user
144 self._fixup_perms2((self._connection._shell.tmpdir, tmp_src), execute=True)
145
146 # add preparation steps to one ssh roundtrip executing the script
147 env_dict: dict[str, _t.Any] = {}
148 env_string = self._compute_environment_string(env_dict)
149
150 if executable:
151 script_cmd = ' '.join([env_string, executable, target_command])
152 else:
153 script_cmd = ' '.join([env_string, target_command])
154
155 exec_data = None
156 # PowerShell runs the script in a special wrapper to enable things
157 # like become and environment args
158 if getattr(self._connection._shell, "_IS_WINDOWS", False):
159 # FUTURE: use a more public method to get the exec payload
160 exec_data = ps_manifest._create_powershell_wrapper(
161 name=f"ansible.builtin.script.{pathlib.Path(source).stem}",
162 module_data=to_bytes(f"& {script_cmd}; exit $LASTEXITCODE"),
163 module_path=source,
164 module_args={},
165 environment=env_dict,
166 async_timeout=self._task.async_val,
167 become_plugin=self._connection.become,
168 substyle="script",
169 task_vars=task_vars,
170 profile='legacy', # the profile doesn't really matter since the module args dict is empty
171 )
172 bootstrap_wrapper = ps_manifest._get_powershell_script("bootstrap_wrapper.ps1").decode('utf-8')
173 pwsh_args = _ps_script.get_pwsh_encoded_cmdline(bootstrap_wrapper, override_execution_policy=True)
174 script_cmd = self._connection._shell.join(pwsh_args)
175
176 # now we execute script, always assume changed.
177 result: dict[str, object] = dict(self._low_level_execute_command(cmd=script_cmd, in_data=exec_data, sudoable=True, chdir=chdir), changed=True)
178
179 if 'rc' in result and result['rc'] != 0:
180 result.update(msg='non-zero return code', failed=True)
181
182 return result
183 finally:
184 self._remove_tmp_path(self._connection._shell.tmpdir)