| 1 |
# (c) 2012, Jeroen Hoekx <[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 functools |
| 21 |
import re |
| 22 |
import operator as py_operator |
| 23 |
|
| 24 |
from collections.abc import MutableMapping, MutableSequence |
| 25 |
|
| 26 |
from jinja2.tests import test_defined, test_undefined |
| 27 |
|
| 28 |
from ansible.module_utils.compat.version import LooseVersion, StrictVersion |
| 29 |
|
| 30 |
from ansible import errors |
| 31 |
from ansible.module_utils.common.text.converters import to_native, to_text, to_bytes |
| 32 |
from ansible._internal._templating._jinja_common import Marker, UndefinedMarker |
| 33 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 34 |
from ansible.template import accept_args_markers |
| 35 |
from ansible.parsing.vault import is_encrypted_file, VaultHelper, VaultLib |
| 36 |
from ansible.utils.display import Display |
| 37 |
from ansible.utils.version import SemanticVersion |
| 38 |
|
| 39 |
try: |
| 40 |
from packaging.version import Version as PEP440Version |
| 41 |
HAS_PACKAGING = True |
| 42 |
except ImportError: |
| 43 |
HAS_PACKAGING = False |
| 44 |
|
| 45 |
display = Display() |
| 46 |
|
| 47 |
|
| 48 |
def timedout(result): |
| 49 |
""" Test if task result yields a time out""" |
| 50 |
if not isinstance(result, MutableMapping): |
| 51 |
raise errors.AnsibleFilterError("The 'timedout' test expects a dictionary") |
| 52 |
|
| 53 |
return bool(result.get('timedout') and bool(result['timedout'].get('period'))) |
| 54 |
|
| 55 |
|
| 56 |
def failed(result): |
| 57 |
""" Test if task result yields failed """ |
| 58 |
if not isinstance(result, MutableMapping): |
| 59 |
raise errors.AnsibleFilterError("The 'failed' test expects a dictionary") |
| 60 |
|
| 61 |
return bool(result.get('failed')) |
| 62 |
|
| 63 |
|
| 64 |
def success(result): |
| 65 |
""" Test if task result yields success """ |
| 66 |
return not bool(failed(result)) |
| 67 |
|
| 68 |
|
| 69 |
def unreachable(result): |
| 70 |
""" Test if task result yields unreachable """ |
| 71 |
if not isinstance(result, MutableMapping): |
| 72 |
raise errors.AnsibleFilterError("The 'unreachable' test expects a dictionary") |
| 73 |
|
| 74 |
return bool(result.get('unreachable')) |
| 75 |
|
| 76 |
|
| 77 |
def reachable(result): |
| 78 |
""" Test if task result yields reachable """ |
| 79 |
return bool(not unreachable(result)) |
| 80 |
|
| 81 |
|
| 82 |
def changed(result): |
| 83 |
""" Test if task result yields changed """ |
| 84 |
if not isinstance(result, MutableMapping): |
| 85 |
raise errors.AnsibleFilterError("The 'changed' test expects a dictionary") |
| 86 |
|
| 87 |
if 'changed' not in result: |
| 88 |
changed = False |
| 89 |
if ( |
| 90 |
'results' in result and # some modules return a 'results' key |
| 91 |
isinstance(result['results'], MutableSequence) and |
| 92 |
isinstance(result['results'][0], MutableMapping) |
| 93 |
): |
| 94 |
for res in result['results']: |
| 95 |
if res.get('changed'): |
| 96 |
changed = True |
| 97 |
break |
| 98 |
else: |
| 99 |
changed = result.get('changed') |
| 100 |
|
| 101 |
return bool(changed) |
| 102 |
|
| 103 |
|
| 104 |
def skipped(result): |
| 105 |
""" Test if task result yields skipped """ |
| 106 |
if not isinstance(result, MutableMapping): |
| 107 |
raise errors.AnsibleFilterError("The 'skipped' test expects a dictionary") |
| 108 |
|
| 109 |
return bool(result.get('skipped')) |
| 110 |
|
| 111 |
|
| 112 |
def started(result): |
| 113 |
""" Test if async task has started """ |
| 114 |
if not isinstance(result, MutableMapping): |
| 115 |
raise errors.AnsibleFilterError("The 'started' test expects a dictionary") |
| 116 |
|
| 117 |
if 'started' in result: |
| 118 |
# For async tasks, return status |
| 119 |
return bool(result.get('started')) |
| 120 |
else: |
| 121 |
# For non-async tasks, warn user, but return as if started |
| 122 |
display.warning("The 'started' test expects an async task, but a non-async task was tested") |
| 123 |
return True |
| 124 |
|
| 125 |
|
| 126 |
def finished(result): |
| 127 |
""" Test if async task has finished """ |
| 128 |
if not isinstance(result, MutableMapping): |
| 129 |
raise errors.AnsibleFilterError("The 'finished' test expects a dictionary") |
| 130 |
|
| 131 |
if 'finished' in result: |
| 132 |
# For async tasks, return status |
| 133 |
return bool(result.get('finished')) |
| 134 |
else: |
| 135 |
# For non-async tasks, warn user, but return as if finished |
| 136 |
display.warning("The 'finished' test expects an async task, but a non-async task was tested") |
| 137 |
return True |
| 138 |
|
| 139 |
|
| 140 |
def regex(value='', pattern='', ignorecase=False, multiline=False, match_type='search'): |
| 141 |
""" Expose `re` as a boolean filter using the `search` method by default. |
| 142 |
This is likely only useful for `search` and `match` which already |
| 143 |
have their own filters. |
| 144 |
""" |
| 145 |
valid_match_types = ('search', 'match', 'fullmatch') |
| 146 |
if match_type not in valid_match_types: |
| 147 |
raise errors.AnsibleTemplatePluginError(f"Invalid match_type specified. Expected one of: {', '.join(valid_match_types)}.", obj=match_type) |
| 148 |
value = to_text(value, errors='surrogate_or_strict') |
| 149 |
flags = 0 |
| 150 |
if ignorecase: |
| 151 |
flags |= re.I |
| 152 |
if multiline: |
| 153 |
flags |= re.M |
| 154 |
_re = re.compile(pattern, flags=flags) |
| 155 |
return bool(getattr(_re, match_type)(value)) |
| 156 |
|
| 157 |
|
| 158 |
@accept_args_markers |
| 159 |
def vault_encrypted(value: object) -> bool: |
| 160 |
"""Evaluate whether a variable is a single vault encrypted value |
| 161 |
|
| 162 |
.. versionadded:: 2.10 |
| 163 |
""" |
| 164 |
if ciphertext := VaultHelper.get_ciphertext(value, with_tags=False): |
| 165 |
return VaultLib.is_encrypted(ciphertext) |
| 166 |
|
| 167 |
if isinstance(value, Marker): |
| 168 |
value.trip() |
| 169 |
|
| 170 |
return False |
| 171 |
|
| 172 |
|
| 173 |
def vaulted_file(value): |
| 174 |
"""Evaluate whether a file is a vault |
| 175 |
|
| 176 |
.. versionadded:: 2.18 |
| 177 |
""" |
| 178 |
try: |
| 179 |
with open(to_bytes(value), 'rb') as f: |
| 180 |
return is_encrypted_file(f) |
| 181 |
except OSError as ex: |
| 182 |
raise errors.AnsibleFilterError(f"Cannot test if the file {value!r} is a vault.") from ex |
| 183 |
|
| 184 |
|
| 185 |
def match(value, pattern='', ignorecase=False, multiline=False): |
| 186 |
""" Perform a `re.match` returning a boolean """ |
| 187 |
return regex(value, pattern, ignorecase, multiline, 'match') |
| 188 |
|
| 189 |
|
| 190 |
def search(value, pattern='', ignorecase=False, multiline=False): |
| 191 |
""" Perform a `re.search` returning a boolean """ |
| 192 |
return regex(value, pattern, ignorecase, multiline, 'search') |
| 193 |
|
| 194 |
|
| 195 |
def version_compare(value, version, operator='eq', strict=None, version_type=None): |
| 196 |
""" Perform a version comparison on a value """ |
| 197 |
op_map = { |
| 198 |
'==': 'eq', '=': 'eq', 'eq': 'eq', |
| 199 |
'<': 'lt', 'lt': 'lt', |
| 200 |
'<=': 'le', 'le': 'le', |
| 201 |
'>': 'gt', 'gt': 'gt', |
| 202 |
'>=': 'ge', 'ge': 'ge', |
| 203 |
'!=': 'ne', '<>': 'ne', 'ne': 'ne' |
| 204 |
} |
| 205 |
|
| 206 |
type_map = { |
| 207 |
'loose': LooseVersion, |
| 208 |
'strict': StrictVersion, |
| 209 |
'semver': SemanticVersion, |
| 210 |
'semantic': SemanticVersion, |
| 211 |
'pep440': PEP440Version, |
| 212 |
} |
| 213 |
|
| 214 |
if strict is not None and version_type is not None: |
| 215 |
raise errors.AnsibleFilterError("Cannot specify both 'strict' and 'version_type'") |
| 216 |
|
| 217 |
if not value: |
| 218 |
raise errors.AnsibleFilterError("Input version value cannot be empty") |
| 219 |
|
| 220 |
if not version: |
| 221 |
raise errors.AnsibleFilterError("Version parameter to compare against cannot be empty") |
| 222 |
|
| 223 |
if version_type == 'pep440' and not HAS_PACKAGING: |
| 224 |
raise errors.AnsibleFilterError("The pep440 version_type requires the Python 'packaging' library") |
| 225 |
|
| 226 |
Version = LooseVersion |
| 227 |
if strict: |
| 228 |
Version = StrictVersion |
| 229 |
elif version_type: |
| 230 |
try: |
| 231 |
Version = type_map[version_type] |
| 232 |
except KeyError: |
| 233 |
raise errors.AnsibleFilterError( |
| 234 |
"Invalid version type (%s). Must be one of %s" % (version_type, ', '.join(map(repr, type_map))) |
| 235 |
) |
| 236 |
|
| 237 |
if operator in op_map: |
| 238 |
operator = op_map[operator] |
| 239 |
else: |
| 240 |
raise errors.AnsibleFilterError( |
| 241 |
'Invalid operator type (%s). Must be one of %s' % (operator, ', '.join(map(repr, op_map))) |
| 242 |
) |
| 243 |
|
| 244 |
try: |
| 245 |
method = getattr(py_operator, operator) |
| 246 |
return method(Version(to_text(value)), Version(to_text(version))) |
| 247 |
except Exception as e: |
| 248 |
raise errors.AnsibleFilterError('Version comparison failed: %s' % to_native(e)) |
| 249 |
|
| 250 |
|
| 251 |
def truthy(value, convert_bool=False): |
| 252 |
"""Evaluate as value for truthiness using python ``bool`` |
| 253 |
|
| 254 |
Optionally, attempt to do a conversion to bool from boolean like values |
| 255 |
such as ``"false"``, ``"true"``, ``"yes"``, ``"no"``, ``"on"``, ``"off"``, etc. |
| 256 |
|
| 257 |
.. versionadded:: 2.10 |
| 258 |
""" |
| 259 |
if convert_bool: |
| 260 |
try: |
| 261 |
value = boolean(value) |
| 262 |
except TypeError: |
| 263 |
pass |
| 264 |
|
| 265 |
return bool(value) |
| 266 |
|
| 267 |
|
| 268 |
def falsy(value, convert_bool=False): |
| 269 |
"""Evaluate as value for falsiness using python ``bool`` |
| 270 |
|
| 271 |
Optionally, attempt to do a conversion to bool from boolean like values |
| 272 |
such as ``"false"``, ``"true"``, ``"yes"``, ``"no"``, ``"on"``, ``"off"``, etc. |
| 273 |
|
| 274 |
.. versionadded:: 2.10 |
| 275 |
""" |
| 276 |
return not truthy(value, convert_bool=convert_bool) |
| 277 |
|
| 278 |
|
| 279 |
@accept_args_markers |
| 280 |
@functools.wraps(test_defined) |
| 281 |
def wrapped_test_defined(value: object) -> Marker | bool: |
| 282 |
"""Wrapper around Jinja's `defined` test to avoid mutating the externally-owned function with our marker attribute.""" |
| 283 |
if isinstance(value, Marker) and not isinstance(value, UndefinedMarker): |
| 284 |
return value |
| 285 |
|
| 286 |
return test_defined(value) |
| 287 |
|
| 288 |
|
| 289 |
@accept_args_markers |
| 290 |
@functools.wraps(test_undefined) |
| 291 |
def wrapped_test_undefined(value: object) -> Marker | bool: |
| 292 |
"""Wrapper around Jinja's `undefined` test to avoid mutating the externally-owned function with our marker attribute.""" |
| 293 |
if isinstance(value, Marker) and not isinstance(value, UndefinedMarker): |
| 294 |
return value |
| 295 |
|
| 296 |
return test_undefined(value) |
| 297 |
|
| 298 |
|
| 299 |
class TestModule(object): |
| 300 |
""" Ansible core jinja2 tests """ |
| 301 |
|
| 302 |
def tests(self): |
| 303 |
return { |
| 304 |
# failure testing |
| 305 |
'failed': failed, |
| 306 |
'failure': failed, |
| 307 |
'succeeded': success, |
| 308 |
'success': success, |
| 309 |
'successful': success, |
| 310 |
'reachable': reachable, |
| 311 |
'unreachable': unreachable, |
| 312 |
'timedout': timedout, |
| 313 |
|
| 314 |
# changed testing |
| 315 |
'changed': changed, |
| 316 |
'change': changed, |
| 317 |
|
| 318 |
# skip testing |
| 319 |
'skipped': skipped, |
| 320 |
'skip': skipped, |
| 321 |
|
| 322 |
# async testing |
| 323 |
'finished': finished, |
| 324 |
'started': started, |
| 325 |
|
| 326 |
# regex |
| 327 |
'match': match, |
| 328 |
'search': search, |
| 329 |
'regex': regex, |
| 330 |
|
| 331 |
# version comparison |
| 332 |
'version_compare': version_compare, |
| 333 |
'version': version_compare, |
| 334 |
|
| 335 |
# lists |
| 336 |
'any': any, |
| 337 |
'all': all, |
| 338 |
|
| 339 |
# truthiness |
| 340 |
'truthy': truthy, |
| 341 |
'falsy': falsy, |
| 342 |
|
| 343 |
# vault |
| 344 |
'vault_encrypted': vault_encrypted, |
| 345 |
'vaulted_file': vaulted_file, |
| 346 |
|
| 347 |
# overrides that require special arg handling |
| 348 |
'defined': wrapped_test_defined, |
| 349 |
'undefined': wrapped_test_undefined, |
| 350 |
} |