| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright (c) 2022, Felix Fontein <[email protected]> |
| 5 |
# GNU General Public License v3.0+ https://www.gnu.org/licenses/gpl-3.0.txt |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import (absolute_import, division, print_function) |
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
module: api_find_and_modify |
| 13 |
author: |
| 14 |
- "Felix Fontein (@felixfontein)" |
| 15 |
short_description: Find and modify information using the API |
| 16 |
version_added: 2.1.0 |
| 17 |
description: |
| 18 |
- Allows to find entries for a path by conditions and modify the values of these entries. |
| 19 |
- Use the M(community.routeros.api_find_and_modify) module to set all entries of a path to specific values, or change multiple |
| 20 |
entries in different ways in one step. |
| 21 |
notes: |
| 22 |
- "If you want to change values based on their old values (like change all comments 'foo' to 'bar') and make sure that there |
| 23 |
are at least N such values, you can use O(require_matches_min=N) together with O(allow_no_matches=true). This will make |
| 24 |
the module fail if there are less than N such entries, but not if there is no match. The latter case is needed for idempotency |
| 25 |
of the task: once the values have been changed, there should be no further match." |
| 26 |
extends_documentation_fragment: |
| 27 |
- community.routeros.api |
| 28 |
- community.routeros.attributes |
| 29 |
- community.routeros.attributes.actiongroup_api |
| 30 |
attributes: |
| 31 |
check_mode: |
| 32 |
support: full |
| 33 |
diff_mode: |
| 34 |
support: full |
| 35 |
platform: |
| 36 |
support: full |
| 37 |
platforms: RouterOS |
| 38 |
idempotent: |
| 39 |
support: full |
| 40 |
options: |
| 41 |
path: |
| 42 |
description: |
| 43 |
- Path to query. |
| 44 |
- An example value is V(ip address). This is equivalent to running C(/ip address) in the RouterOS CLI. |
| 45 |
required: true |
| 46 |
type: str |
| 47 |
find: |
| 48 |
description: |
| 49 |
- Fields to search for. |
| 50 |
- The module will only consider entries in the given O(path) that match all fields provided here. |
| 51 |
- Use YAML V(~), or prepend keys with V(!), to specify an unset value. |
| 52 |
- Note that if the dictionary specified here is empty, every entry in the path will be matched. |
| 53 |
required: true |
| 54 |
type: dict |
| 55 |
values: |
| 56 |
description: |
| 57 |
- On all entries matching the conditions in O(find), set the keys of this option to the values specified here. |
| 58 |
- Use YAML V(~), or prepend keys with V(!), to specify to unset a value. |
| 59 |
required: true |
| 60 |
type: dict |
| 61 |
require_matches_min: |
| 62 |
description: |
| 63 |
- Make sure that there are no less matches than this number. |
| 64 |
- If there are less matches, fail instead of modifying anything. |
| 65 |
type: int |
| 66 |
default: 0 |
| 67 |
require_matches_max: |
| 68 |
description: |
| 69 |
- Make sure that there are no more matches than this number. |
| 70 |
- If there are more matches, fail instead of modifying anything. |
| 71 |
- If not specified, there is no upper limit. |
| 72 |
type: int |
| 73 |
allow_no_matches: |
| 74 |
description: |
| 75 |
- Whether to allow that no match is found. |
| 76 |
- If not specified, this value is induced from whether O(require_matches_min) is 0 or larger. |
| 77 |
type: bool |
| 78 |
ignore_dynamic: |
| 79 |
description: |
| 80 |
- Whether to ignore dynamic entries. |
| 81 |
- By default, they are considered (V(false)). If set to V(true), they are not considered. |
| 82 |
- It is generally recommended to set this to V(true) unless when you really need to modify dynamic entries. |
| 83 |
- Note that the current default (V(false)) is B(deprecated) and will change to V(true) in community.routeros 4.0.0. |
| 84 |
type: bool |
| 85 |
version_added: 3.7.0 |
| 86 |
ignore_builtin: |
| 87 |
description: |
| 88 |
- Whether to ignore builtin entries. |
| 89 |
- By default, they are considered (V(false)). If set to V(true), they are not considered. |
| 90 |
- It is generally recommended to set this to V(true) unless when you really need to modify builtin entries. |
| 91 |
- Note that the current default (V(false)) is B(deprecated) and will change to V(true) in community.routeros 4.0.0. |
| 92 |
type: bool |
| 93 |
version_added: 3.7.0 |
| 94 |
seealso: |
| 95 |
- module: community.routeros.api |
| 96 |
- module: community.routeros.api_facts |
| 97 |
- module: community.routeros.api_modify |
| 98 |
- module: community.routeros.api_info |
| 99 |
""" |
| 100 |
|
| 101 |
EXAMPLES = r""" |
| 102 |
--- |
| 103 |
- name: Rename bridge from 'bridge' to 'my-bridge' |
| 104 |
community.routeros.api_find_and_modify: |
| 105 |
hostname: "{{ hostname }}" |
| 106 |
password: "{{ password }}" |
| 107 |
username: "{{ username }}" |
| 108 |
path: interface bridge |
| 109 |
find: |
| 110 |
name: bridge |
| 111 |
values: |
| 112 |
name: my-bridge |
| 113 |
# Always ignore dynamic and builtin entries |
| 114 |
# (not relevant for this path, but generally recommended) |
| 115 |
ignore_dynamic: true |
| 116 |
ignore_builtin: true |
| 117 |
|
| 118 |
- name: Change IP address to 192.168.1.1 for interface bridge - assuming there is only one |
| 119 |
community.routeros.api_find_and_modify: |
| 120 |
hostname: "{{ hostname }}" |
| 121 |
password: "{{ password }}" |
| 122 |
username: "{{ username }}" |
| 123 |
path: ip address |
| 124 |
find: |
| 125 |
interface: bridge |
| 126 |
values: |
| 127 |
address: "192.168.1.1/24" |
| 128 |
# If there are zero entries, or more than one: fail! We expected that |
| 129 |
# exactly one is configured. |
| 130 |
require_matches_min: 1 |
| 131 |
require_matches_max: 1 |
| 132 |
# Always ignore dynamic and builtin entries |
| 133 |
# (not relevant for this path, but generally recommended) |
| 134 |
ignore_dynamic: true |
| 135 |
ignore_builtin: true |
| 136 |
""" |
| 137 |
|
| 138 |
RETURN = r""" |
| 139 |
old_data: |
| 140 |
description: |
| 141 |
- A list of all elements for the current path before a change was made. |
| 142 |
sample: |
| 143 |
- '.id': '*1' |
| 144 |
actual-interface: bridge |
| 145 |
address: "192.168.88.1/24" |
| 146 |
comment: defconf |
| 147 |
disabled: false |
| 148 |
dynamic: false |
| 149 |
interface: bridge |
| 150 |
invalid: false |
| 151 |
network: 192.168.88.0 |
| 152 |
type: list |
| 153 |
elements: dict |
| 154 |
returned: success |
| 155 |
new_data: |
| 156 |
description: |
| 157 |
- A list of all elements for the current path after a change was made. |
| 158 |
sample: |
| 159 |
- '.id': '*1' |
| 160 |
actual-interface: bridge |
| 161 |
address: "192.168.1.1/24" |
| 162 |
comment: awesome |
| 163 |
disabled: false |
| 164 |
dynamic: false |
| 165 |
interface: bridge |
| 166 |
invalid: false |
| 167 |
network: 192.168.1.0 |
| 168 |
type: list |
| 169 |
elements: dict |
| 170 |
returned: success |
| 171 |
match_count: |
| 172 |
description: |
| 173 |
- The number of entries that matched the criteria in O(find). |
| 174 |
sample: 1 |
| 175 |
type: int |
| 176 |
returned: success |
| 177 |
modify__count: |
| 178 |
description: |
| 179 |
- The number of entries that were modified. |
| 180 |
sample: 1 |
| 181 |
type: int |
| 182 |
returned: success |
| 183 |
""" |
| 184 |
|
| 185 |
from ansible.module_utils.basic import AnsibleModule |
| 186 |
from ansible.module_utils.common.text.converters import to_native |
| 187 |
|
| 188 |
from ansible_collections.community.routeros.plugins.module_utils.api import ( |
| 189 |
api_argument_spec, |
| 190 |
check_has_library, |
| 191 |
create_api, |
| 192 |
) |
| 193 |
|
| 194 |
from ansible_collections.community.routeros.plugins.module_utils._api_data import ( |
| 195 |
split_path, |
| 196 |
) |
| 197 |
|
| 198 |
from ansible_collections.community.routeros.plugins.module_utils._api_helper import ( |
| 199 |
value_to_str, |
| 200 |
) |
| 201 |
|
| 202 |
try: |
| 203 |
from librouteros.exceptions import LibRouterosError |
| 204 |
except Exception: |
| 205 |
# Handled in api module_utils |
| 206 |
pass |
| 207 |
|
| 208 |
|
| 209 |
def compose_api_path(api, path): |
| 210 |
api_path = api.path() |
| 211 |
for p in path: |
| 212 |
api_path = api_path.join(p) |
| 213 |
return api_path |
| 214 |
|
| 215 |
|
| 216 |
def filter_entries(entries, ignore_dynamic=False, ignore_builtin=False): |
| 217 |
result = [] |
| 218 |
has_dynamic = False |
| 219 |
has_builtin = False |
| 220 |
for entry in entries: |
| 221 |
if entry.get('dynamic', False): |
| 222 |
has_dynamic = True |
| 223 |
if ignore_dynamic: |
| 224 |
continue |
| 225 |
if entry.get('builtin', False): |
| 226 |
has_builtin = True |
| 227 |
if ignore_builtin: |
| 228 |
continue |
| 229 |
result.append(entry) |
| 230 |
return result, has_dynamic, has_builtin |
| 231 |
|
| 232 |
|
| 233 |
DISABLED_MEANS_EMPTY_STRING = ('comment', ) |
| 234 |
|
| 235 |
|
| 236 |
def main(): |
| 237 |
module_args = dict( |
| 238 |
path=dict(type='str', required=True), |
| 239 |
find=dict(type='dict', required=True), |
| 240 |
values=dict(type='dict', required=True), |
| 241 |
require_matches_min=dict(type='int', default=0), |
| 242 |
require_matches_max=dict(type='int'), |
| 243 |
allow_no_matches=dict(type='bool'), |
| 244 |
ignore_dynamic=dict(type='bool'), |
| 245 |
ignore_builtin=dict(type='bool'), |
| 246 |
) |
| 247 |
module_args.update(api_argument_spec()) |
| 248 |
|
| 249 |
module = AnsibleModule( |
| 250 |
argument_spec=module_args, |
| 251 |
supports_check_mode=True, |
| 252 |
) |
| 253 |
if module.params['allow_no_matches'] is None: |
| 254 |
module.params['allow_no_matches'] = module.params['require_matches_min'] <= 0 |
| 255 |
|
| 256 |
find = module.params['find'] |
| 257 |
for key, value in sorted(find.items()): |
| 258 |
if key.startswith('!'): |
| 259 |
key = key[1:] |
| 260 |
if value not in (None, ''): |
| 261 |
module.fail_json(msg='The value for "!{key}" in `find` must not be non-trivial!'.format(key=key)) |
| 262 |
if key in find: |
| 263 |
module.fail_json(msg='`find` must not contain both "{key}" and "!{key}"!'.format(key=key)) |
| 264 |
values = module.params['values'] |
| 265 |
for key, value in sorted(values.items()): |
| 266 |
if key.startswith('!'): |
| 267 |
key = key[1:] |
| 268 |
if value not in (None, ''): |
| 269 |
module.fail_json(msg='The value for "!{key}" in `values` must not be non-trivial!'.format(key=key)) |
| 270 |
if key in values: |
| 271 |
module.fail_json(msg='`values` must not contain both "{key}" and "!{key}"!'.format(key=key)) |
| 272 |
|
| 273 |
ignore_dynamic = module.params['ignore_dynamic'] |
| 274 |
ignore_builtin = module.params['ignore_builtin'] |
| 275 |
|
| 276 |
check_has_library(module) |
| 277 |
api = create_api(module) |
| 278 |
|
| 279 |
path = split_path(module.params['path']) |
| 280 |
|
| 281 |
api_path = compose_api_path(api, path) |
| 282 |
|
| 283 |
old_data, has_dynamic, has_builtin = filter_entries(list(api_path), ignore_dynamic=ignore_dynamic or False, ignore_builtin=ignore_builtin or False) |
| 284 |
new_data = [entry.copy() for entry in old_data] |
| 285 |
if ignore_dynamic is None and has_dynamic: |
| 286 |
module.deprecate( |
| 287 |
"The current default (false) of the ignore_dynamic function has been deprecated. It will change to `true` in community.routeros 4.0.0.", |
| 288 |
version="4.0.0", |
| 289 |
collection_name="community.routeros", |
| 290 |
) |
| 291 |
if ignore_builtin is None and has_builtin: |
| 292 |
module.deprecate( |
| 293 |
"The current default (false) of the ignore_builtin function has been deprecated. It will change to `true` in community.routeros 4.0.0.", |
| 294 |
version="4.0.0", |
| 295 |
collection_name="community.routeros", |
| 296 |
) |
| 297 |
|
| 298 |
# Find matching entries |
| 299 |
matching_entries = [] |
| 300 |
for index, entry in enumerate(new_data): |
| 301 |
matches = True |
| 302 |
for key, value in find.items(): |
| 303 |
if key.startswith('!'): |
| 304 |
# Allow to specify keys that should not be present by prepending '!' |
| 305 |
key = key[1:] |
| 306 |
value = None |
| 307 |
current_value = entry.get(key) |
| 308 |
if key in DISABLED_MEANS_EMPTY_STRING and value == '' and current_value is None: |
| 309 |
current_value = value |
| 310 |
if value_to_str(current_value) != value_to_str(value): |
| 311 |
matches = False |
| 312 |
break |
| 313 |
if matches: |
| 314 |
matching_entries.append((index, entry)) |
| 315 |
|
| 316 |
# Check whether the correct amount of entries was found |
| 317 |
if matching_entries: |
| 318 |
if len(matching_entries) < module.params['require_matches_min']: |
| 319 |
module.fail_json(msg='Found %d entries, but expected at least %d' % (len(matching_entries), module.params['require_matches_min'])) |
| 320 |
if module.params['require_matches_max'] is not None and len(matching_entries) > module.params['require_matches_max']: |
| 321 |
module.fail_json(msg='Found %d entries, but expected at most %d' % (len(matching_entries), module.params['require_matches_max'])) |
| 322 |
elif not module.params['allow_no_matches']: |
| 323 |
module.fail_json(msg='Found no entries, but allow_no_matches=false') |
| 324 |
|
| 325 |
# Identify entries to update |
| 326 |
modifications = [] |
| 327 |
for index, entry in matching_entries: |
| 328 |
modification = {} |
| 329 |
for key, value in values.items(): |
| 330 |
if key.startswith('!'): |
| 331 |
# Allow to specify keys to remove by prepending '!' |
| 332 |
key = key[1:] |
| 333 |
value = None |
| 334 |
current_value = entry.get(key) |
| 335 |
if key in DISABLED_MEANS_EMPTY_STRING and value == '' and current_value is None: |
| 336 |
current_value = value |
| 337 |
if value_to_str(current_value) != value_to_str(value): |
| 338 |
if value is None: |
| 339 |
disable_key = '!%s' % key |
| 340 |
if key in DISABLED_MEANS_EMPTY_STRING: |
| 341 |
disable_key = key |
| 342 |
modification[disable_key] = '' |
| 343 |
entry.pop(key, None) |
| 344 |
else: |
| 345 |
modification[key] = value |
| 346 |
entry[key] = value |
| 347 |
if modification: |
| 348 |
if '.id' in entry: |
| 349 |
modification['.id'] = entry['.id'] |
| 350 |
modifications.append(modification) |
| 351 |
|
| 352 |
# Apply changes |
| 353 |
if not module.check_mode and modifications: |
| 354 |
for modification in modifications: |
| 355 |
try: |
| 356 |
api_path.update(**modification) |
| 357 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 358 |
module.fail_json( |
| 359 |
msg='Error while modifying for .id={id}: {error}'.format( |
| 360 |
id=modification['.id'], |
| 361 |
error=to_native(e), |
| 362 |
) |
| 363 |
) |
| 364 |
new_data, has_dynamic, has_builtin = filter_entries(list(api_path), ignore_dynamic=ignore_dynamic or False, ignore_builtin=ignore_builtin or False) |
| 365 |
if ignore_dynamic is None and has_dynamic: |
| 366 |
module.deprecate( |
| 367 |
"The current default (false) of the ignore_dynamic function has been deprecated. It will change to `true` in community.routeros 4.0.0.", |
| 368 |
version="4.0.0", |
| 369 |
collection_name="community.routeros", |
| 370 |
) |
| 371 |
if ignore_builtin is None and has_builtin: |
| 372 |
module.deprecate( |
| 373 |
"The current default (false) of the ignore_builtin function has been deprecated. It will change to `true` in community.routeros 4.0.0.", |
| 374 |
version="4.0.0", |
| 375 |
collection_name="community.routeros", |
| 376 |
) |
| 377 |
|
| 378 |
# Produce return value |
| 379 |
more = {} |
| 380 |
if module._diff: |
| 381 |
# Only include the matching values |
| 382 |
more['diff'] = { |
| 383 |
'before': { |
| 384 |
'values': [old_data[index] for index, entry in matching_entries], |
| 385 |
}, |
| 386 |
'after': { |
| 387 |
'values': [entry for index, entry in matching_entries], |
| 388 |
}, |
| 389 |
} |
| 390 |
module.exit_json( |
| 391 |
changed=bool(modifications), |
| 392 |
old_data=old_data, |
| 393 |
new_data=new_data, |
| 394 |
match_count=len(matching_entries), |
| 395 |
modify_count=len(modifications), |
| 396 |
**more |
| 397 |
) |
| 398 |
|
| 399 |
|
| 400 |
if __name__ == '__main__': |
| 401 |
main() |