| 1 |
# (c) 2014 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 |
|
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import ansible.constants as C |
| 21 |
from ansible.errors import AnsibleParserError, AnsibleError, AnsibleAssertionError |
| 22 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper |
| 23 |
from ansible.module_utils.common.sentinel import Sentinel |
| 24 |
from ansible.module_utils.common.text.converters import to_text |
| 25 |
from ansible.parsing.splitter import parse_kv, split_args |
| 26 |
from ansible.parsing.vault import EncryptedString |
| 27 |
from ansible.plugins.loader import module_loader, action_loader |
| 28 |
from ansible._internal._templating import _jinja_bits |
| 29 |
from ansible.utils.display import Display |
| 30 |
from ansible.utils.fqcn import add_internal_fqcns |
| 31 |
|
| 32 |
|
| 33 |
# modules formatted for user msg |
| 34 |
_BUILTIN_RAW_PARAM_MODULES_SIMPLE = set([ |
| 35 |
'include_vars', |
| 36 |
'include_tasks', |
| 37 |
'include_role', |
| 38 |
'import_tasks', |
| 39 |
'import_role', |
| 40 |
'add_host', |
| 41 |
'group_by', |
| 42 |
'set_fact', |
| 43 |
'meta', |
| 44 |
]) |
| 45 |
FREEFORM_ACTIONS_SIMPLE = set(C.MODULE_REQUIRE_ARGS_SIMPLE) |
| 46 |
FREEFORM_ACTIONS = frozenset(C.MODULE_REQUIRE_ARGS) |
| 47 |
RAW_PARAM_MODULES_SIMPLE = _BUILTIN_RAW_PARAM_MODULES_SIMPLE.union(FREEFORM_ACTIONS_SIMPLE) |
| 48 |
# For filtering out modules correctly below, use all permutations |
| 49 |
RAW_PARAM_MODULES = frozenset(add_internal_fqcns(RAW_PARAM_MODULES_SIMPLE)).union(FREEFORM_ACTIONS) |
| 50 |
BUILTIN_TASKS = frozenset(add_internal_fqcns(( |
| 51 |
'meta', |
| 52 |
'include_tasks', |
| 53 |
'include_role', |
| 54 |
'import_tasks', |
| 55 |
'import_role' |
| 56 |
))) |
| 57 |
|
| 58 |
|
| 59 |
def _get_action_context(action_or_module, collection_list): |
| 60 |
module_context = module_loader.find_plugin_with_context(action_or_module, collection_list=collection_list) |
| 61 |
if module_context and module_context.resolved and module_context.action_plugin: |
| 62 |
action_or_module = module_context.action_plugin |
| 63 |
|
| 64 |
context = action_loader.find_plugin_with_context(action_or_module, collection_list=collection_list) |
| 65 |
if not context or not context.resolved: |
| 66 |
context = module_context |
| 67 |
return context |
| 68 |
|
| 69 |
|
| 70 |
class ModuleArgsParser: |
| 71 |
|
| 72 |
""" |
| 73 |
There are several ways a module and argument set can be expressed: |
| 74 |
|
| 75 |
# legacy form (for a shell command) |
| 76 |
- action: shell echo hi |
| 77 |
|
| 78 |
# common shorthand for local actions vs delegate_to |
| 79 |
- local_action: shell echo hi |
| 80 |
|
| 81 |
# most commonly: |
| 82 |
- copy: src=a dest=b |
| 83 |
|
| 84 |
# legacy form |
| 85 |
- action: copy src=a dest=b |
| 86 |
|
| 87 |
# complex args form, for passing structured data |
| 88 |
- copy: |
| 89 |
src: a |
| 90 |
dest: b |
| 91 |
|
| 92 |
# gross, but technically legal |
| 93 |
- action: |
| 94 |
module: copy |
| 95 |
args: |
| 96 |
src: a |
| 97 |
dest: b |
| 98 |
|
| 99 |
# Standard YAML form for command-type modules. In this case, the args specified |
| 100 |
# will act as 'defaults' and will be overridden by any args specified |
| 101 |
# in one of the other formats (complex args under the action, or |
| 102 |
# parsed from the k=v string |
| 103 |
- command: 'pwd' |
| 104 |
args: |
| 105 |
chdir: '/tmp' |
| 106 |
|
| 107 |
|
| 108 |
This class has some of the logic to canonicalize these into the form |
| 109 |
|
| 110 |
- module: <module_name> |
| 111 |
delegate_to: <optional> |
| 112 |
args: <args> |
| 113 |
|
| 114 |
Args may also be munged for certain shell command parameters. |
| 115 |
""" |
| 116 |
|
| 117 |
def __init__(self, task_ds=None, collection_list=None): |
| 118 |
task_ds = {} if task_ds is None else task_ds |
| 119 |
|
| 120 |
if not isinstance(task_ds, dict): |
| 121 |
raise AnsibleAssertionError("the type of 'task_ds' should be a dict, but is a %s" % type(task_ds)) |
| 122 |
self._task_ds = task_ds |
| 123 |
self._collection_list = collection_list |
| 124 |
# delayed local imports to prevent circular import |
| 125 |
from ansible.playbook.task import Task |
| 126 |
from ansible.playbook.handler import Handler |
| 127 |
# store the valid Task/Handler attrs for quick access |
| 128 |
self._task_attrs = set(Task.fattributes) |
| 129 |
self._task_attrs.update(set(Handler.fattributes)) |
| 130 |
# HACK: why are these not FieldAttributes on task with a post-validate to check usage? |
| 131 |
self._task_attrs.update(['local_action', 'static']) |
| 132 |
self._task_attrs = frozenset(self._task_attrs) |
| 133 |
self._resolved_action = None |
| 134 |
|
| 135 |
def _split_module_string(self, module_string: str) -> tuple[str, str]: |
| 136 |
""" |
| 137 |
when module names are expressed like: |
| 138 |
action: copy src=a dest=b |
| 139 |
the first part of the string is the name of the module |
| 140 |
and the rest are strings pertaining to the arguments. |
| 141 |
""" |
| 142 |
|
| 143 |
tokens = split_args(module_string) |
| 144 |
if len(tokens) > 1: |
| 145 |
result = (tokens[0].strip(), " ".join(tokens[1:])) |
| 146 |
else: |
| 147 |
result = (tokens[0].strip(), "") |
| 148 |
|
| 149 |
return AnsibleTagHelper.tag_copy(module_string, result[0]), AnsibleTagHelper.tag_copy(module_string, result[1]) |
| 150 |
|
| 151 |
def _normalize_parameters(self, thing, action=None, additional_args=None): |
| 152 |
""" |
| 153 |
arguments can be fuzzy. Deal with all the forms. |
| 154 |
""" |
| 155 |
|
| 156 |
# final args are the ones we'll eventually return, so first update |
| 157 |
# them with any additional args specified, which have lower priority |
| 158 |
# than those which may be parsed/normalized next |
| 159 |
final_args = dict() |
| 160 |
|
| 161 |
if additional_args is not Sentinel: |
| 162 |
if isinstance(additional_args, str) and _jinja_bits.is_possibly_all_template(additional_args): |
| 163 |
final_args['_variable_params'] = additional_args |
| 164 |
elif isinstance(additional_args, dict): |
| 165 |
final_args.update(additional_args) |
| 166 |
elif additional_args is None: |
| 167 |
Display().deprecated( |
| 168 |
msg="Ignoring empty task `args` keyword.", |
| 169 |
version="2.23", |
| 170 |
help_text='A mapping or template which resolves to a mapping is required.', |
| 171 |
obj=self._task_ds, |
| 172 |
) |
| 173 |
else: |
| 174 |
raise AnsibleParserError( |
| 175 |
message='The value of the task `args` keyword is invalid.', |
| 176 |
help_text='A mapping or template which resolves to a mapping is required.', |
| 177 |
obj=additional_args, |
| 178 |
) |
| 179 |
|
| 180 |
# how we normalize depends if we figured out what the module name is |
| 181 |
# yet. If we have already figured it out, it's a 'new style' invocation. |
| 182 |
# otherwise, it's not |
| 183 |
|
| 184 |
if action is not None: |
| 185 |
args = self._normalize_new_style_args(thing, action, additional_args) |
| 186 |
else: |
| 187 |
(action, args) = self._normalize_old_style_args(thing) |
| 188 |
|
| 189 |
# this can occasionally happen, simplify |
| 190 |
if args and 'args' in args: |
| 191 |
tmp_args = args.pop('args') |
| 192 |
if isinstance(tmp_args, str): |
| 193 |
tmp_args = parse_kv(tmp_args) |
| 194 |
args.update(tmp_args) |
| 195 |
|
| 196 |
# only internal variables can start with an underscore, so |
| 197 |
# we don't allow users to set them directly in arguments |
| 198 |
if args and action not in FREEFORM_ACTIONS: |
| 199 |
for arg in args: |
| 200 |
arg = to_text(arg) |
| 201 |
if arg.startswith('_ansible_'): |
| 202 |
err_msg = ( |
| 203 |
f"Invalid parameter specified beginning with keyword '_ansible_' for action '{action !s}': '{arg !s}'. " |
| 204 |
"The prefix '_ansible_' is reserved for internal use only." |
| 205 |
) |
| 206 |
raise AnsibleError(err_msg) |
| 207 |
|
| 208 |
# finally, update the args we're going to return with the ones |
| 209 |
# which were normalized above |
| 210 |
if args: |
| 211 |
final_args.update(args) |
| 212 |
|
| 213 |
return (action, final_args) |
| 214 |
|
| 215 |
def _normalize_new_style_args(self, thing, action, additional_args): |
| 216 |
""" |
| 217 |
deals with fuzziness in new style module invocations |
| 218 |
accepting key=value pairs and dictionaries, and returns |
| 219 |
a dictionary of arguments |
| 220 |
|
| 221 |
possible example inputs: |
| 222 |
'echo hi', 'shell' |
| 223 |
{'region': 'xyz'}, 'ec2' |
| 224 |
standardized outputs like: |
| 225 |
{ _raw_params: 'echo hi', _uses_shell: True } |
| 226 |
""" |
| 227 |
|
| 228 |
if isinstance(thing, dict): |
| 229 |
# form is like: { xyz: { x: 2, y: 3 } } |
| 230 |
args = thing |
| 231 |
elif isinstance(thing, str): |
| 232 |
# form is like: copy: src=a dest=b |
| 233 |
check_raw = action in FREEFORM_ACTIONS |
| 234 |
args = parse_kv(thing, check_raw=check_raw) |
| 235 |
args_keys = set(args) - {'_raw_params'} |
| 236 |
|
| 237 |
if args_keys and additional_args is not Sentinel: |
| 238 |
kv_args = ', '.join(repr(arg) for arg in sorted(args_keys)) |
| 239 |
|
| 240 |
Display().deprecated( |
| 241 |
msg=f"Merging legacy k=v args ({kv_args}) into task args.", |
| 242 |
help_text="Include all task args in the task `args` mapping.", |
| 243 |
version="2.23", |
| 244 |
obj=thing, |
| 245 |
) |
| 246 |
elif isinstance(thing, EncryptedString): |
| 247 |
# k=v parsing intentionally omitted |
| 248 |
args = dict(_raw_params=thing) |
| 249 |
elif thing is None: |
| 250 |
# this can happen with modules which take no params, like ping: |
| 251 |
args = None |
| 252 |
else: |
| 253 |
raise AnsibleParserError("unexpected parameter type in action: %s" % type(thing), obj=self._task_ds) |
| 254 |
return args |
| 255 |
|
| 256 |
def _normalize_old_style_args(self, thing): |
| 257 |
""" |
| 258 |
deals with fuzziness in old-style (action/local_action) module invocations |
| 259 |
returns tuple of (module_name, dictionary_args) |
| 260 |
|
| 261 |
possible example inputs: |
| 262 |
{ 'shell' : 'echo hi' } |
| 263 |
'shell echo hi' |
| 264 |
{'module': 'ec2', 'x': 1 } |
| 265 |
standardized outputs like: |
| 266 |
('ec2', { 'x': 1} ) |
| 267 |
""" |
| 268 |
|
| 269 |
action = None |
| 270 |
args = None |
| 271 |
|
| 272 |
if isinstance(thing, dict): |
| 273 |
# form is like: action: { module: 'copy', src: 'a', dest: 'b' } |
| 274 |
Display().deprecated("Using a mapping for `action` is deprecated.", version='2.23', help_text='Use a string value for `action`.', obj=thing) |
| 275 |
thing = thing.copy() |
| 276 |
if 'module' in thing: |
| 277 |
action, module_args = self._split_module_string(thing['module']) |
| 278 |
args = thing.copy() |
| 279 |
check_raw = action in FREEFORM_ACTIONS |
| 280 |
args.update(parse_kv(module_args, check_raw=check_raw)) |
| 281 |
del args['module'] |
| 282 |
|
| 283 |
elif isinstance(thing, str): |
| 284 |
# form is like: action: copy src=a dest=b |
| 285 |
(action, args) = self._split_module_string(thing) |
| 286 |
check_raw = action in FREEFORM_ACTIONS |
| 287 |
args = parse_kv(args, check_raw=check_raw) |
| 288 |
|
| 289 |
else: |
| 290 |
# need a dict or a string, so giving up |
| 291 |
raise AnsibleParserError("unexpected parameter type in action: %s" % type(thing), obj=self._task_ds) |
| 292 |
|
| 293 |
return (action, args) |
| 294 |
|
| 295 |
def parse(self, skip_action_validation=False): |
| 296 |
""" |
| 297 |
Given a task in one of the supported forms, parses and returns |
| 298 |
returns the action, arguments, and delegate_to values for the |
| 299 |
task, dealing with all sorts of levels of fuzziness. |
| 300 |
""" |
| 301 |
|
| 302 |
action = None |
| 303 |
delegate_to = self._task_ds.get('delegate_to', Sentinel) |
| 304 |
args = dict() |
| 305 |
|
| 306 |
# This is the standard YAML form for command-type modules. We grab |
| 307 |
# the args and pass them in as additional arguments, which can/will |
| 308 |
# be overwritten via dict updates from the other arg sources below |
| 309 |
additional_args = self._task_ds.get('args', Sentinel) |
| 310 |
|
| 311 |
# We can have one of action, local_action, or module specified |
| 312 |
# action |
| 313 |
if 'action' in self._task_ds: |
| 314 |
# an old school 'action' statement |
| 315 |
thing = self._task_ds['action'] |
| 316 |
action, args = self._normalize_parameters(thing, additional_args=additional_args) |
| 317 |
|
| 318 |
# local_action |
| 319 |
if 'local_action' in self._task_ds: |
| 320 |
# local_action is similar but also implies a delegate_to |
| 321 |
if action is not None: |
| 322 |
raise AnsibleParserError("action and local_action are mutually exclusive", obj=self._task_ds) |
| 323 |
thing = self._task_ds.get('local_action', '') |
| 324 |
delegate_to = 'localhost' |
| 325 |
action, args = self._normalize_parameters(thing, additional_args=additional_args) |
| 326 |
|
| 327 |
# module: <stuff> is the more new-style invocation |
| 328 |
|
| 329 |
# filter out task attributes so we're only querying unrecognized keys as actions/modules |
| 330 |
non_task_ds = dict((k, v) for k, v in self._task_ds.items() if (k not in self._task_attrs) and (not k.startswith('with_'))) |
| 331 |
|
| 332 |
# walk the filtered input dictionary to see if we recognize a module name |
| 333 |
for item, value in non_task_ds.items(): |
| 334 |
if item in BUILTIN_TASKS: |
| 335 |
is_action_candidate = True |
| 336 |
elif skip_action_validation: |
| 337 |
is_action_candidate = True |
| 338 |
else: |
| 339 |
try: |
| 340 |
# DTFIX-FUTURE: extract to a helper method, shared with Task.post_validate_args |
| 341 |
context = _get_action_context(item, self._collection_list) |
| 342 |
except AnsibleError as e: |
| 343 |
if e.obj is None: |
| 344 |
e.obj = self._task_ds |
| 345 |
raise e |
| 346 |
|
| 347 |
is_action_candidate = context.resolved and bool(context.redirect_list) |
| 348 |
if is_action_candidate: |
| 349 |
self._resolved_action = context.resolved_fqcn |
| 350 |
|
| 351 |
if is_action_candidate: |
| 352 |
# finding more than one module name is a problem |
| 353 |
if action is not None: |
| 354 |
raise AnsibleParserError("conflicting action statements: %s, %s" % (action, item), obj=self._task_ds) |
| 355 |
|
| 356 |
action = item |
| 357 |
thing = value |
| 358 |
action, args = self._normalize_parameters(thing, action=action, additional_args=additional_args) |
| 359 |
|
| 360 |
# if we didn't see any module in the task at all, it's not a task really |
| 361 |
if action is None: |
| 362 |
if non_task_ds: # there was one non-task action, but we couldn't find it |
| 363 |
bad_action = list(non_task_ds.keys())[0] |
| 364 |
raise AnsibleParserError("couldn't resolve module/action '{0}'. This often indicates a " |
| 365 |
"misspelling, missing collection, or incorrect module path.".format(bad_action), |
| 366 |
obj=self._task_ds) |
| 367 |
else: |
| 368 |
raise AnsibleParserError("no module/action detected in task.", |
| 369 |
obj=self._task_ds) |
| 370 |
|
| 371 |
return action, args, delegate_to |