| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright (c) 2022, Felix Fontein (@felixfontein) <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or 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_modify |
| 13 |
author: |
| 14 |
- "Felix Fontein (@felixfontein)" |
| 15 |
short_description: Modify data at paths with API |
| 16 |
version_added: 2.2.0 |
| 17 |
description: |
| 18 |
- Allows to modify information for a path using the API. |
| 19 |
- Use the M(community.routeros.api_find_and_modify) module to modify one or multiple entries in a controlled way depending |
| 20 |
on some search conditions. |
| 21 |
- To make a backup of a path that can be restored with this module, use the M(community.routeros.api_info) module. |
| 22 |
- The module ignores dynamic and builtin entries. |
| 23 |
- B(Note) that this module is still heavily in development, and only supports B(some) paths. If you want to support new |
| 24 |
paths, or think you found problems with existing paths, please first L(create an issue in the community.routeros Issue |
| 25 |
Tracker,https://github.com/ansible-collections/community.routeros/issues/). |
| 26 |
notes: |
| 27 |
- If write-only fields are present in the path, the module is B(not idempotent) in a strict sense, since it is not able |
| 28 |
to verify the current value of these fields. The behavior the module should assume can be controlled with the O(handle_write_only) |
| 29 |
option. |
| 30 |
- If you want to modify a path where a property is called V(cmd), you should use librouteros 4.0.0 or newer. |
| 31 |
This is for example true for O(path=container). |
| 32 |
Previous versions of librouteros had a bug preventing to add or modify entries when V(cmd) is provided. |
| 33 |
requirements: |
| 34 |
- Needs L(ordereddict,https://pypi.org/project/ordereddict) for Python 2.6 |
| 35 |
extends_documentation_fragment: |
| 36 |
- community.routeros.api |
| 37 |
- community.routeros.api.restrict |
| 38 |
- community.routeros.attributes |
| 39 |
- community.routeros.attributes.actiongroup_api |
| 40 |
attributes: |
| 41 |
check_mode: |
| 42 |
support: full |
| 43 |
diff_mode: |
| 44 |
support: full |
| 45 |
platform: |
| 46 |
support: full |
| 47 |
platforms: RouterOS |
| 48 |
idempotent: |
| 49 |
support: full |
| 50 |
options: |
| 51 |
path: |
| 52 |
description: |
| 53 |
- Path to query. |
| 54 |
- An example value is V(ip address). This is equivalent to running modification commands in C(/ip address) in the RouterOS |
| 55 |
CLI. |
| 56 |
required: true |
| 57 |
type: str |
| 58 |
choices: |
| 59 |
# BEGIN PATH LIST |
| 60 |
- app settings |
| 61 |
- caps-man aaa |
| 62 |
- caps-man access-list |
| 63 |
- caps-man channel |
| 64 |
- caps-man configuration |
| 65 |
- caps-man datapath |
| 66 |
- caps-man interface |
| 67 |
- caps-man manager |
| 68 |
- caps-man manager interface |
| 69 |
- caps-man provisioning |
| 70 |
- caps-man rates |
| 71 |
- caps-man security |
| 72 |
- certificate |
| 73 |
- certificate crl |
| 74 |
- certificate scep-server |
| 75 |
- certificate scep-server ra |
| 76 |
- certificate settings |
| 77 |
- console settings |
| 78 |
- container |
| 79 |
- container config |
| 80 |
- container envs |
| 81 |
- container mounts |
| 82 |
- disk |
| 83 |
- disk btrfs subvolume |
| 84 |
- disk btrfs transfer |
| 85 |
- disk settings |
| 86 |
- dude |
| 87 |
- dude agent |
| 88 |
- dude device |
| 89 |
- dude device-type |
| 90 |
- dude notification |
| 91 |
- dude probe |
| 92 |
- dude ros address |
| 93 |
- dude ros arp |
| 94 |
- dude ros lease |
| 95 |
- dude ros queue |
| 96 |
- dude ros route |
| 97 |
- dude service |
| 98 |
- file |
| 99 |
- file rsync-daemon |
| 100 |
- file sync |
| 101 |
- interface 6to4 |
| 102 |
- interface amt |
| 103 |
- interface bonding |
| 104 |
- interface bridge |
| 105 |
- interface bridge calea |
| 106 |
- interface bridge filter |
| 107 |
- interface bridge host |
| 108 |
- interface bridge mdb |
| 109 |
- interface bridge mlag |
| 110 |
- interface bridge msti |
| 111 |
- interface bridge nat |
| 112 |
- interface bridge port |
| 113 |
- interface bridge port mst-override |
| 114 |
- interface bridge port-controller |
| 115 |
- interface bridge port-controller device |
| 116 |
- interface bridge port-extender |
| 117 |
- interface bridge settings |
| 118 |
- interface bridge vlan |
| 119 |
- interface detect-internet |
| 120 |
- interface dot1x client |
| 121 |
- interface dot1x server |
| 122 |
- interface eoip |
| 123 |
- interface eoipv6 |
| 124 |
- interface ethernet |
| 125 |
- interface ethernet poe |
| 126 |
- interface ethernet switch |
| 127 |
- interface ethernet switch acl |
| 128 |
- interface ethernet switch acl policer |
| 129 |
- interface ethernet switch dscp-qos-map |
| 130 |
- interface ethernet switch dscp-to-dscp |
| 131 |
- interface ethernet switch egress-vlan-tag |
| 132 |
- interface ethernet switch egress-vlan-translation |
| 133 |
- interface ethernet switch host |
| 134 |
- interface ethernet switch ingress-port-policer |
| 135 |
- interface ethernet switch ingress-vlan-translation |
| 136 |
- interface ethernet switch l3hw-settings |
| 137 |
- interface ethernet switch l3hw-settings advanced |
| 138 |
- interface ethernet switch mac-based-vlan |
| 139 |
- interface ethernet switch multicast-fdb |
| 140 |
- interface ethernet switch one2one-vlan-switching |
| 141 |
- interface ethernet switch policer-qos-map |
| 142 |
- interface ethernet switch port |
| 143 |
- interface ethernet switch port-isolation |
| 144 |
- interface ethernet switch port-leakage |
| 145 |
- interface ethernet switch protocol-based-vlan |
| 146 |
- interface ethernet switch qos map |
| 147 |
- interface ethernet switch qos map ip |
| 148 |
- interface ethernet switch qos map vlan |
| 149 |
- interface ethernet switch qos priority-flow-control |
| 150 |
- interface ethernet switch qos profile |
| 151 |
- interface ethernet switch qos settings |
| 152 |
- interface ethernet switch qos tx-manager |
| 153 |
- interface ethernet switch qos-group |
| 154 |
- interface ethernet switch reserved-fdb |
| 155 |
- interface ethernet switch rule |
| 156 |
- interface ethernet switch shaper |
| 157 |
- interface ethernet switch trunk |
| 158 |
- interface ethernet switch unicast-fdb |
| 159 |
- interface ethernet switch vlan |
| 160 |
- interface gre |
| 161 |
- interface gre6 |
| 162 |
- interface ipip |
| 163 |
- interface ipipv6 |
| 164 |
- interface l2tp-client |
| 165 |
- interface l2tp-ether |
| 166 |
- interface l2tp-server |
| 167 |
- interface l2tp-server server |
| 168 |
- interface list |
| 169 |
- interface list member |
| 170 |
- interface lte apn |
| 171 |
- interface lte settings |
| 172 |
- interface macsec |
| 173 |
- interface macsec profile |
| 174 |
- interface macvlan |
| 175 |
- interface mesh |
| 176 |
- interface mesh port |
| 177 |
- interface ovpn-client |
| 178 |
- interface ovpn-server |
| 179 |
- interface ovpn-server server |
| 180 |
- interface ppp-client |
| 181 |
- interface ppp-server |
| 182 |
- interface pppoe-client |
| 183 |
- interface pppoe-server |
| 184 |
- interface pppoe-server server |
| 185 |
- interface pptp-client |
| 186 |
- interface pptp-server |
| 187 |
- interface pptp-server server |
| 188 |
- interface sstp-client |
| 189 |
- interface sstp-server |
| 190 |
- interface sstp-server server |
| 191 |
- interface veth |
| 192 |
- interface vlan |
| 193 |
- interface vpls |
| 194 |
- interface vrrp |
| 195 |
- interface vxlan |
| 196 |
- interface vxlan vteps |
| 197 |
- interface wifi |
| 198 |
- interface wifi aaa |
| 199 |
- interface wifi access-list |
| 200 |
- interface wifi cap |
| 201 |
- interface wifi capsman |
| 202 |
- interface wifi channel |
| 203 |
- interface wifi configuration |
| 204 |
- interface wifi datapath |
| 205 |
- interface wifi interworking |
| 206 |
- interface wifi network |
| 207 |
- interface wifi network radio |
| 208 |
- interface wifi provisioning |
| 209 |
- interface wifi radio settings |
| 210 |
- interface wifi security |
| 211 |
- interface wifi security multi-passphrase |
| 212 |
- interface wifi steering |
| 213 |
- interface wifiwave2 |
| 214 |
- interface wifiwave2 aaa |
| 215 |
- interface wifiwave2 access-list |
| 216 |
- interface wifiwave2 cap |
| 217 |
- interface wifiwave2 capsman |
| 218 |
- interface wifiwave2 channel |
| 219 |
- interface wifiwave2 configuration |
| 220 |
- interface wifiwave2 datapath |
| 221 |
- interface wifiwave2 interworking |
| 222 |
- interface wifiwave2 provisioning |
| 223 |
- interface wifiwave2 security |
| 224 |
- interface wifiwave2 steering |
| 225 |
- interface wireguard |
| 226 |
- interface wireguard peers |
| 227 |
- interface wireless |
| 228 |
- interface wireless access-list |
| 229 |
- interface wireless align |
| 230 |
- interface wireless cap |
| 231 |
- interface wireless channels |
| 232 |
- interface wireless connect-list |
| 233 |
- interface wireless interworking-profiles |
| 234 |
- interface wireless nstreme-dual |
| 235 |
- interface wireless security-profiles |
| 236 |
- interface wireless sniffer |
| 237 |
- interface wireless snooper |
| 238 |
- interface wireless wds |
| 239 |
- iot bluetooth advertisers ad-structures |
| 240 |
- iot bluetooth whitelist |
| 241 |
- iot lora joineui |
| 242 |
- iot lora netid |
| 243 |
- iot lora servers |
| 244 |
- iot lora traffic options |
| 245 |
- iot modbus |
| 246 |
- iot modbus security-rules |
| 247 |
- iot mqtt brokers |
| 248 |
- iot mqtt subscriptions |
| 249 |
- ip accounting |
| 250 |
- ip accounting web-access |
| 251 |
- ip address |
| 252 |
- ip arp |
| 253 |
- ip cloud |
| 254 |
- ip cloud advanced |
| 255 |
- ip cloud back-to-home-file |
| 256 |
- ip cloud back-to-home-file settings |
| 257 |
- ip cloud back-to-home-user |
| 258 |
- ip cloud back-to-home-users |
| 259 |
- ip dhcp-client |
| 260 |
- ip dhcp-client option |
| 261 |
- ip dhcp-relay |
| 262 |
- ip dhcp-server |
| 263 |
- ip dhcp-server alert |
| 264 |
- ip dhcp-server config |
| 265 |
- ip dhcp-server lease |
| 266 |
- ip dhcp-server matcher |
| 267 |
- ip dhcp-server network |
| 268 |
- ip dhcp-server option |
| 269 |
- ip dhcp-server option sets |
| 270 |
- ip dns |
| 271 |
- ip dns adlist |
| 272 |
- ip dns forwarders |
| 273 |
- ip dns static |
| 274 |
- ip firewall address-list |
| 275 |
- ip firewall calea |
| 276 |
- ip firewall connection tracking |
| 277 |
- ip firewall filter |
| 278 |
- ip firewall layer7-protocol |
| 279 |
- ip firewall mangle |
| 280 |
- ip firewall nat |
| 281 |
- ip firewall raw |
| 282 |
- ip firewall service-port |
| 283 |
- ip hotspot |
| 284 |
- ip hotspot ip-binding |
| 285 |
- ip hotspot profile |
| 286 |
- ip hotspot service-port |
| 287 |
- ip hotspot user |
| 288 |
- ip hotspot user profile |
| 289 |
- ip hotspot walled-garden |
| 290 |
- ip hotspot walled-garden ip |
| 291 |
- ip ipsec identity |
| 292 |
- ip ipsec key psk |
| 293 |
- ip ipsec key qkd |
| 294 |
- ip ipsec key rsa |
| 295 |
- ip ipsec mode-config |
| 296 |
- ip ipsec peer |
| 297 |
- ip ipsec policy |
| 298 |
- ip ipsec policy group |
| 299 |
- ip ipsec profile |
| 300 |
- ip ipsec proposal |
| 301 |
- ip ipsec settings |
| 302 |
- ip kid-control |
| 303 |
- ip kid-control device |
| 304 |
- ip media |
| 305 |
- ip media settings |
| 306 |
- ip nat-pmp |
| 307 |
- ip nat-pmp interfaces |
| 308 |
- ip neighbor discovery-settings |
| 309 |
- ip packing |
| 310 |
- ip pool |
| 311 |
- ip proxy |
| 312 |
- ip proxy access |
| 313 |
- ip proxy cache |
| 314 |
- ip proxy direct |
| 315 |
- ip reverse-proxy |
| 316 |
- ip route |
| 317 |
- ip route rule |
| 318 |
- ip route vrf |
| 319 |
- ip service |
| 320 |
- ip service webserver |
| 321 |
- ip settings |
| 322 |
- ip smb |
| 323 |
- ip smb shares |
| 324 |
- ip smb users |
| 325 |
- ip socks |
| 326 |
- ip socks access |
| 327 |
- ip socks users |
| 328 |
- ip socksify |
| 329 |
- ip ssh |
| 330 |
- ip tftp |
| 331 |
- ip tftp settings |
| 332 |
- ip traffic-flow |
| 333 |
- ip traffic-flow ipfix |
| 334 |
- ip traffic-flow target |
| 335 |
- ip upnp |
| 336 |
- ip upnp interfaces |
| 337 |
- ip vrf |
| 338 |
- ipv6 address |
| 339 |
- ipv6 dhcp-client |
| 340 |
- ipv6 dhcp-client option |
| 341 |
- ipv6 dhcp-relay |
| 342 |
- ipv6 dhcp-relay option |
| 343 |
- ipv6 dhcp-server |
| 344 |
- ipv6 dhcp-server binding |
| 345 |
- ipv6 dhcp-server option |
| 346 |
- ipv6 dhcp-server option sets |
| 347 |
- ipv6 firewall address-list |
| 348 |
- ipv6 firewall filter |
| 349 |
- ipv6 firewall mangle |
| 350 |
- ipv6 firewall nat |
| 351 |
- ipv6 firewall raw |
| 352 |
- ipv6 nd |
| 353 |
- ipv6 nd prefix |
| 354 |
- ipv6 nd prefix default |
| 355 |
- ipv6 nd proxy |
| 356 |
- ipv6 neighbor |
| 357 |
- ipv6 pool |
| 358 |
- ipv6 route |
| 359 |
- ipv6 settings |
| 360 |
- lcd |
| 361 |
- lcd interface |
| 362 |
- lcd interface pages |
| 363 |
- lcd pin |
| 364 |
- lora joineui |
| 365 |
- lora netid |
| 366 |
- lora servers |
| 367 |
- lora traffic options |
| 368 |
- mpls |
| 369 |
- mpls interface |
| 370 |
- mpls ldp |
| 371 |
- mpls ldp accept-filter |
| 372 |
- mpls ldp advertise-filter |
| 373 |
- mpls ldp interface |
| 374 |
- mpls ldp local-mapping |
| 375 |
- mpls ldp neighbor |
| 376 |
- mpls ldp remote-mapping |
| 377 |
- mpls mangle |
| 378 |
- mpls settings |
| 379 |
- mpls traffic-eng interface |
| 380 |
- mpls traffic-eng path |
| 381 |
- mpls traffic-eng tunnel |
| 382 |
- openflow |
| 383 |
- openflow port |
| 384 |
- port firmware |
| 385 |
- port remote-access |
| 386 |
- ppp aaa |
| 387 |
- ppp l2tp-secret |
| 388 |
- ppp profile |
| 389 |
- ppp secret |
| 390 |
- queue interface |
| 391 |
- queue simple |
| 392 |
- queue tree |
| 393 |
- queue type |
| 394 |
- radius |
| 395 |
- radius incoming |
| 396 |
- routing bfd configuration |
| 397 |
- routing bgp aggregate |
| 398 |
- routing bgp connection |
| 399 |
- routing bgp evpn |
| 400 |
- routing bgp instance |
| 401 |
- routing bgp network |
| 402 |
- routing bgp peer |
| 403 |
- routing bgp template |
| 404 |
- routing bgp vpls |
| 405 |
- routing bgp vpn |
| 406 |
- routing fantasy |
| 407 |
- routing filter |
| 408 |
- routing filter community-ext-list |
| 409 |
- routing filter community-large-list |
| 410 |
- routing filter community-list |
| 411 |
- routing filter num-list |
| 412 |
- routing filter rule |
| 413 |
- routing filter select-rule |
| 414 |
- routing gmp |
| 415 |
- routing id |
| 416 |
- routing igmp-proxy |
| 417 |
- routing igmp-proxy interface |
| 418 |
- routing igmp-proxy mfc |
| 419 |
- routing isis instance |
| 420 |
- routing isis interface-template |
| 421 |
- routing mme |
| 422 |
- routing ospf area |
| 423 |
- routing ospf area range |
| 424 |
- routing ospf instance |
| 425 |
- routing ospf interface-template |
| 426 |
- routing ospf static-neighbor |
| 427 |
- routing pimsm bsr candidate |
| 428 |
- routing pimsm bsr rp-candidate |
| 429 |
- routing pimsm instance |
| 430 |
- routing pimsm interface-template |
| 431 |
- routing pimsm static-rp |
| 432 |
- routing rip |
| 433 |
- routing rip instance |
| 434 |
- routing rip interface-template |
| 435 |
- routing rip keys |
| 436 |
- routing rip static-neighbor |
| 437 |
- routing ripng |
| 438 |
- routing rpki |
| 439 |
- routing rule |
| 440 |
- routing settings |
| 441 |
- routing table |
| 442 |
- rsync-daemon |
| 443 |
- snmp |
| 444 |
- snmp community |
| 445 |
- special-login |
| 446 |
- system clock |
| 447 |
- system clock manual |
| 448 |
- system console |
| 449 |
- system console screen |
| 450 |
- system gps |
| 451 |
- system hardware |
| 452 |
- system health |
| 453 |
- system health settings |
| 454 |
- system identity |
| 455 |
- system leds |
| 456 |
- system leds settings |
| 457 |
- system logging |
| 458 |
- system logging action |
| 459 |
- system note |
| 460 |
- system ntp client |
| 461 |
- system ntp client servers |
| 462 |
- system ntp key |
| 463 |
- system ntp server |
| 464 |
- system package local-update mirror |
| 465 |
- system package local-update update-package-source |
| 466 |
- system package update |
| 467 |
- system resource hardware usb-settings |
| 468 |
- system resource irq rps |
| 469 |
- system resource usb settings |
| 470 |
- system routerboard mode-button |
| 471 |
- system routerboard reset-button |
| 472 |
- system routerboard settings |
| 473 |
- system routerboard usb |
| 474 |
- system routerboard wps-button |
| 475 |
- system scheduler |
| 476 |
- system script |
| 477 |
- system swos |
| 478 |
- system upgrade mirror |
| 479 |
- system upgrade upgrade-package-source |
| 480 |
- system ups |
| 481 |
- system watchdog |
| 482 |
- task |
| 483 |
- tool bandwidth-server |
| 484 |
- tool calea |
| 485 |
- tool e-mail |
| 486 |
- tool graphing |
| 487 |
- tool graphing interface |
| 488 |
- tool graphing queue |
| 489 |
- tool graphing resource |
| 490 |
- tool mac-server |
| 491 |
- tool mac-server mac-winbox |
| 492 |
- tool mac-server ping |
| 493 |
- tool netwatch |
| 494 |
- tool romon |
| 495 |
- tool romon port |
| 496 |
- tool sms |
| 497 |
- tool sniffer |
| 498 |
- tool traffic-generator |
| 499 |
- tool traffic-generator packet-template |
| 500 |
- tool traffic-generator port |
| 501 |
- tool traffic-generator raw-packet-template |
| 502 |
- tool traffic-generator stream |
| 503 |
- tool traffic-monitor |
| 504 |
- tr069-client |
| 505 |
- user |
| 506 |
- user aaa |
| 507 |
- user group |
| 508 |
- user settings |
| 509 |
- user ssh-keys |
| 510 |
- user-manager |
| 511 |
- user-manager advanced |
| 512 |
- user-manager attribute |
| 513 |
- user-manager database |
| 514 |
- user-manager limitation |
| 515 |
- user-manager payment |
| 516 |
- user-manager profile |
| 517 |
- user-manager profile-limitation |
| 518 |
- user-manager router |
| 519 |
- user-manager user |
| 520 |
- user-manager user group |
| 521 |
- user-manager user-profile |
| 522 |
- zerotier |
| 523 |
- zerotier controller |
| 524 |
- zerotier controller member |
| 525 |
- zerotier interface |
| 526 |
# END PATH LIST |
| 527 |
data: |
| 528 |
description: |
| 529 |
- Data to ensure that is present for this path. |
| 530 |
- Fields not provided will not be modified. |
| 531 |
- If C(.id) appears in an entry, it will be ignored. |
| 532 |
required: true |
| 533 |
type: list |
| 534 |
elements: dict |
| 535 |
ensure_order: |
| 536 |
description: |
| 537 |
- Whether to ensure the same order of the config as present in O(data). |
| 538 |
- Requires O(handle_absent_entries=remove). |
| 539 |
type: bool |
| 540 |
default: false |
| 541 |
handle_absent_entries: |
| 542 |
description: |
| 543 |
- How to handle entries that are present in the current config, but not in O(data). |
| 544 |
- V(ignore) ignores them. |
| 545 |
- V(remove) removes them. |
| 546 |
type: str |
| 547 |
choices: |
| 548 |
- ignore |
| 549 |
- remove |
| 550 |
default: ignore |
| 551 |
handle_entries_content: |
| 552 |
description: |
| 553 |
- For a single entry in O(data), this describes how to handle fields that are not mentioned in that entry, but appear |
| 554 |
in the actual config. |
| 555 |
- If V(ignore), they are not modified. |
| 556 |
- If V(remove), they are removed. If at least one cannot be removed, the module will fail. |
| 557 |
- If V(remove_as_much_as_possible), all that can be removed will be removed. The ones that cannot be removed will be |
| 558 |
kept. |
| 559 |
- Note that V(remove) and V(remove_as_much_as_possible) do not apply to write-only fields. |
| 560 |
type: str |
| 561 |
choices: |
| 562 |
- ignore |
| 563 |
- remove |
| 564 |
- remove_as_much_as_possible |
| 565 |
default: ignore |
| 566 |
handle_read_only: |
| 567 |
description: |
| 568 |
- How to handle values passed in for read-only fields. |
| 569 |
- If V(ignore), they are not passed to the API. |
| 570 |
- If V(validate), the values are not passed for creation, and for updating they are compared to the value returned for |
| 571 |
the object. If they differ, the module fails. |
| 572 |
- If V(error), the module will fail if read-only fields are provided. |
| 573 |
type: str |
| 574 |
choices: |
| 575 |
- ignore |
| 576 |
- validate |
| 577 |
- error |
| 578 |
default: error |
| 579 |
version_added: 2.10.0 |
| 580 |
handle_write_only: |
| 581 |
description: |
| 582 |
- How to handle values passed in for write-only fields. |
| 583 |
- If V(create_only), they are passed on creation, and ignored for updating. |
| 584 |
- If V(always_update), they are always passed to the API. This means that if such a value is present, the module will |
| 585 |
always result in C(changed) since there is no way to validate whether the value actually changed. |
| 586 |
- If V(error), the module will fail if write-only fields are provided. |
| 587 |
type: str |
| 588 |
choices: |
| 589 |
- create_only |
| 590 |
- always_update |
| 591 |
- error |
| 592 |
default: create_only |
| 593 |
version_added: 2.10.0 |
| 594 |
restrict: |
| 595 |
description: |
| 596 |
- Restrict operation to entries matching the following criteria. |
| 597 |
- This can be useful together with O(handle_absent_entries=remove) to operate on a subset of the values. |
| 598 |
- For example, for O(path=ip firewall filter), you can set O(restrict[].field=chain) and O(restrict[].values=input) |
| 599 |
to restrict operation to the input chain, and ignore the forward and output chains. |
| 600 |
version_added: 2.18.0 |
| 601 |
seealso: |
| 602 |
- module: community.routeros.api |
| 603 |
- module: community.routeros.api_facts |
| 604 |
- module: community.routeros.api_find_and_modify |
| 605 |
- module: community.routeros.api_info |
| 606 |
""" |
| 607 |
|
| 608 |
EXAMPLES = r""" |
| 609 |
--- |
| 610 |
- name: Setup DHCP server networks |
| 611 |
# Ensures that we have exactly two DHCP server networks (in the specified order) |
| 612 |
community.routeros.api_modify: |
| 613 |
path: ip dhcp-server network |
| 614 |
handle_absent_entries: remove |
| 615 |
handle_entries_content: remove_as_much_as_possible |
| 616 |
ensure_order: true |
| 617 |
data: |
| 618 |
- address: 192.168.88.0/24 |
| 619 |
comment: admin network |
| 620 |
dns-server: 192.168.88.1 |
| 621 |
gateway: 192.168.88.1 |
| 622 |
- address: 192.168.1.0/24 |
| 623 |
comment: customer network 1 |
| 624 |
dns-server: 192.168.1.1 |
| 625 |
gateway: 192.168.1.1 |
| 626 |
netmask: 24 |
| 627 |
|
| 628 |
- name: Adjust NAT |
| 629 |
community.routeros.api_modify: |
| 630 |
hostname: "{{ hostname }}" |
| 631 |
password: "{{ password }}" |
| 632 |
username: "{{ username }}" |
| 633 |
path: ip firewall nat |
| 634 |
data: |
| 635 |
- action: masquerade |
| 636 |
chain: srcnat |
| 637 |
comment: NAT to WAN |
| 638 |
out-interface-list: WAN |
| 639 |
# Three ways to unset values: |
| 640 |
# - nothing after `:` |
| 641 |
# - "empty" value (null/~/None) |
| 642 |
# - prepend '!' |
| 643 |
out-interface: |
| 644 |
to-addresses: ~ |
| 645 |
'!to-ports': |
| 646 |
|
| 647 |
- name: Block all incoming connections |
| 648 |
community.routeros.api_modify: |
| 649 |
hostname: "{{ hostname }}" |
| 650 |
password: "{{ password }}" |
| 651 |
username: "{{ username }}" |
| 652 |
path: ip firewall filter |
| 653 |
handle_absent_entries: remove |
| 654 |
handle_entries_content: remove_as_much_as_possible |
| 655 |
restrict: |
| 656 |
# Do not touch any chain except the input chain |
| 657 |
- field: chain |
| 658 |
values: |
| 659 |
- input |
| 660 |
data: |
| 661 |
- action: drop |
| 662 |
chain: input |
| 663 |
""" |
| 664 |
|
| 665 |
RETURN = r""" |
| 666 |
old_data: |
| 667 |
description: |
| 668 |
- A list of all elements for the current path before a change was made. |
| 669 |
sample: |
| 670 |
- '.id': '*1' |
| 671 |
actual-interface: bridge |
| 672 |
address: "192.168.88.1/24" |
| 673 |
comment: defconf |
| 674 |
disabled: false |
| 675 |
dynamic: false |
| 676 |
interface: bridge |
| 677 |
invalid: false |
| 678 |
network: 192.168.88.0 |
| 679 |
type: list |
| 680 |
elements: dict |
| 681 |
returned: always |
| 682 |
new_data: |
| 683 |
description: |
| 684 |
- A list of all elements for the current path after a change was made. |
| 685 |
sample: |
| 686 |
- '.id': '*1' |
| 687 |
actual-interface: bridge |
| 688 |
address: "192.168.1.1/24" |
| 689 |
comment: awesome |
| 690 |
disabled: false |
| 691 |
dynamic: false |
| 692 |
interface: bridge |
| 693 |
invalid: false |
| 694 |
network: 192.168.1.0 |
| 695 |
type: list |
| 696 |
elements: dict |
| 697 |
returned: always |
| 698 |
""" |
| 699 |
|
| 700 |
from collections import defaultdict |
| 701 |
|
| 702 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 703 |
from ansible.module_utils.common.text.converters import to_native |
| 704 |
|
| 705 |
from ansible_collections.community.routeros.plugins.module_utils.api import ( |
| 706 |
api_argument_spec, |
| 707 |
check_has_library, |
| 708 |
create_api, |
| 709 |
get_api_version, |
| 710 |
) |
| 711 |
|
| 712 |
from ansible_collections.community.routeros.plugins.module_utils._api_data import ( |
| 713 |
PATHS, |
| 714 |
join_path, |
| 715 |
split_path, |
| 716 |
) |
| 717 |
|
| 718 |
from ansible_collections.community.routeros.plugins.module_utils._api_helper import ( |
| 719 |
apply_value_sanitizer, |
| 720 |
restrict_argument_spec, |
| 721 |
restrict_entry_accepted, |
| 722 |
validate_and_prepare_restrict, |
| 723 |
value_to_str, |
| 724 |
) |
| 725 |
|
| 726 |
from ansible_collections.community.routeros.plugins.module_utils._hardware_detect import ( |
| 727 |
get_cached_or_detect, |
| 728 |
) |
| 729 |
|
| 730 |
HAS_ORDEREDDICT = True |
| 731 |
try: |
| 732 |
from collections import OrderedDict |
| 733 |
except ImportError: |
| 734 |
try: |
| 735 |
from ordereddict import OrderedDict |
| 736 |
except ImportError: |
| 737 |
HAS_ORDEREDDICT = False |
| 738 |
OrderedDict = dict |
| 739 |
|
| 740 |
try: |
| 741 |
from librouteros.exceptions import LibRouterosError |
| 742 |
except Exception: |
| 743 |
# Handled in api module_utils |
| 744 |
pass |
| 745 |
|
| 746 |
|
| 747 |
def compose_api_path(api, path): |
| 748 |
api_path = api.path() |
| 749 |
for p in path: |
| 750 |
api_path = api_path.join(p) |
| 751 |
return api_path |
| 752 |
|
| 753 |
|
| 754 |
def find_modifications(old_entry, new_entry, path_info, module, for_text='', return_none_instead_of_fail=False): |
| 755 |
modifications = OrderedDict() |
| 756 |
updated_entry = old_entry.copy() |
| 757 |
for k, v in new_entry.items(): |
| 758 |
if k == '.id': |
| 759 |
continue |
| 760 |
disabled_k = None |
| 761 |
if k.startswith('!'): |
| 762 |
disabled_k = k[1:] |
| 763 |
elif v is None or value_to_str(v) == value_to_str(path_info.fields[k].remove_value): |
| 764 |
disabled_k = k |
| 765 |
if disabled_k is not None: |
| 766 |
if disabled_k in old_entry: |
| 767 |
if path_info.fields[disabled_k].remove_value is not None: |
| 768 |
modifications[disabled_k] = path_info.fields[disabled_k].remove_value |
| 769 |
else: |
| 770 |
modifications['!%s' % disabled_k] = '' |
| 771 |
del updated_entry[disabled_k] |
| 772 |
continue |
| 773 |
if k not in old_entry and value_to_str(path_info.fields[k].default) == value_to_str(v) and not path_info.fields[k].can_disable: |
| 774 |
continue |
| 775 |
key_info = path_info.fields[k] |
| 776 |
if key_info.read_only: |
| 777 |
# handle_read_only must be 'validate' |
| 778 |
if old_entry.get(k) != v: |
| 779 |
module.fail_json( |
| 780 |
msg='Read-only key "{key}" has value "{old_value}", but should have new value "{new_value}"{for_text}.'.format( |
| 781 |
key=k, old_value=old_entry.get(k), new_value=v, for_text=for_text)) |
| 782 |
continue |
| 783 |
if key_info.write_only: |
| 784 |
if module.params['handle_write_only'] == 'create_only': |
| 785 |
# do not update this value |
| 786 |
continue |
| 787 |
if k not in old_entry or value_to_str(old_entry[k]) != value_to_str(v): |
| 788 |
modifications[k] = v |
| 789 |
updated_entry[k] = v |
| 790 |
handle_entries_content = module.params['handle_entries_content'] |
| 791 |
if handle_entries_content != 'ignore': |
| 792 |
for k in old_entry: |
| 793 |
if k == '.id' or k in new_entry or ('!%s' % k) in new_entry or k not in path_info.fields: |
| 794 |
continue |
| 795 |
field_info = path_info.fields[k] |
| 796 |
if field_info.default is not None and field_info.default == old_entry[k]: |
| 797 |
continue |
| 798 |
if field_info.remove_value is not None and field_info.remove_value == old_entry[k]: |
| 799 |
continue |
| 800 |
if field_info.can_disable: |
| 801 |
if field_info.default is not None: |
| 802 |
modifications[k] = field_info.default |
| 803 |
elif field_info.remove_value is not None: |
| 804 |
modifications[k] = field_info.remove_value |
| 805 |
else: |
| 806 |
modifications['!%s' % k] = '' |
| 807 |
del updated_entry[k] |
| 808 |
elif field_info.default is not None: |
| 809 |
modifications[k] = field_info.default |
| 810 |
updated_entry[k] = field_info.default |
| 811 |
elif handle_entries_content == 'remove': |
| 812 |
if return_none_instead_of_fail: |
| 813 |
return None, None |
| 814 |
module.fail_json(msg='Key "{key}" cannot be removed{for_text}.'.format(key=k, for_text=for_text)) |
| 815 |
for k in path_info.fields: |
| 816 |
field_info = path_info.fields[k] |
| 817 |
if k not in old_entry and k not in new_entry and field_info.can_disable and field_info.default is not None: |
| 818 |
modifications[k] = field_info.default |
| 819 |
updated_entry[k] = field_info.default |
| 820 |
return modifications, updated_entry |
| 821 |
|
| 822 |
|
| 823 |
def essentially_same_weight(old_entry, new_entry, path_info, module): |
| 824 |
for k, v in new_entry.items(): |
| 825 |
if k == '.id': |
| 826 |
continue |
| 827 |
disabled_k = None |
| 828 |
if k.startswith('!'): |
| 829 |
disabled_k = k[1:] |
| 830 |
elif v is None or value_to_str(v) == value_to_str(path_info.fields[k].remove_value): |
| 831 |
disabled_k = k |
| 832 |
if disabled_k is not None: |
| 833 |
if disabled_k in old_entry: |
| 834 |
return None |
| 835 |
continue |
| 836 |
if k not in old_entry and value_to_str(path_info.fields[k].default) == value_to_str(v): |
| 837 |
continue |
| 838 |
if k not in old_entry or value_to_str(old_entry[k]) != value_to_str(v): |
| 839 |
return None |
| 840 |
handle_entries_content = module.params['handle_entries_content'] |
| 841 |
weight = 0 |
| 842 |
for k in old_entry: |
| 843 |
if k == '.id' or k in new_entry or ('!%s' % k) in new_entry or k not in path_info.fields: |
| 844 |
continue |
| 845 |
field_info = path_info.fields[k] |
| 846 |
if field_info.default is not None and field_info.default == old_entry[k]: |
| 847 |
continue |
| 848 |
if handle_entries_content != 'ignore': |
| 849 |
return None |
| 850 |
else: |
| 851 |
weight += 1 |
| 852 |
return weight |
| 853 |
|
| 854 |
|
| 855 |
def remove_read_only(entry, path_info): |
| 856 |
to_remove = [] |
| 857 |
for real_k, v in entry.items(): |
| 858 |
k = real_k |
| 859 |
if k.startswith('!'): |
| 860 |
k = k[1:] |
| 861 |
if path_info.fields[k].read_only: |
| 862 |
to_remove.append(real_k) |
| 863 |
for k in to_remove: |
| 864 |
entry.pop(k) |
| 865 |
|
| 866 |
|
| 867 |
def format_pk(primary_keys, values): |
| 868 |
return ', '.join('{pk}="{value}"'.format(pk=pk, value=value) for pk, value in zip(primary_keys, values)) |
| 869 |
|
| 870 |
|
| 871 |
def polish_entry(entry, path_info, module, for_text): |
| 872 |
if '.id' in entry: |
| 873 |
entry.pop('.id') |
| 874 |
to_remove = [] |
| 875 |
for key, value in entry.items(): |
| 876 |
real_key = key |
| 877 |
disabled_key = False |
| 878 |
if key.startswith('!'): |
| 879 |
disabled_key = True |
| 880 |
key = key[1:] |
| 881 |
if key in entry: |
| 882 |
module.fail_json(msg='Not both "{key}" and "!{key}" must appear{for_text}.'.format(key=key, for_text=for_text)) |
| 883 |
key_info = path_info.fields.get(key) |
| 884 |
if key_info is None: |
| 885 |
module.fail_json(msg='Unknown key "{key}"{for_text}.'.format(key=real_key, for_text=for_text)) |
| 886 |
if disabled_key: |
| 887 |
if not key_info.can_disable: |
| 888 |
module.fail_json(msg='Key "!{key}" must not be disabled (leading "!"){for_text}.'.format(key=key, for_text=for_text)) |
| 889 |
if value not in (None, '', key_info.remove_value): |
| 890 |
module.fail_json(msg='Disabled key "!{key}" must not have a value{for_text}.'.format(key=key, for_text=for_text)) |
| 891 |
elif value is None: |
| 892 |
if not key_info.can_disable: |
| 893 |
module.fail_json(msg='Key "{key}" must not be disabled (value null/~/None){for_text}.'.format(key=key, for_text=for_text)) |
| 894 |
if key_info.read_only: |
| 895 |
if module.params['handle_read_only'] == 'error': |
| 896 |
module.fail_json(msg='Key "{key}" is read-only{for_text}, and handle_read_only=error.'.format(key=key, for_text=for_text)) |
| 897 |
if module.params['handle_read_only'] == 'ignore': |
| 898 |
to_remove.append(real_key) |
| 899 |
if key_info.write_only: |
| 900 |
if module.params['handle_write_only'] == 'error': |
| 901 |
module.fail_json(msg='Key "{key}" is write-only{for_text}, and handle_write_only=error.'.format(key=key, for_text=for_text)) |
| 902 |
if key_info.depr and key_info.depr.applies("write"): |
| 903 |
key_info.depr.emit(module) |
| 904 |
for key in to_remove: |
| 905 |
entry.pop(key) |
| 906 |
# Iterate over a snapshot of keys because we may update values in-place. |
| 907 |
# Disabled-key entries (!key) carry no meaningful value to sanitise and are |
| 908 |
# skipped. Type handling for all other values is delegated to the individual |
| 909 |
# sanitizer – see the value sanitizer CONTRACT in api_data.py. |
| 910 |
for key in list(entry): |
| 911 |
if key.startswith('!'): |
| 912 |
continue |
| 913 |
key_info = path_info.fields.get(key) |
| 914 |
if key_info is None or key_info.value_sanitizer is None: |
| 915 |
continue |
| 916 |
entry[key] = apply_value_sanitizer(key_info, entry[key], key, module.warn) |
| 917 |
for key, field_info in path_info.fields.items(): |
| 918 |
if field_info.required and key not in entry: |
| 919 |
module.fail_json(msg='Key "{key}" must be present{for_text}.'.format(key=key, for_text=for_text)) |
| 920 |
for require_list in path_info.required_one_of: |
| 921 |
found_req_keys = [rk for rk in require_list if rk in entry] |
| 922 |
if len(require_list) > 0 and not found_req_keys: |
| 923 |
module.fail_json( |
| 924 |
msg='Every element in data must contain one of {required_keys}. For example, the element{for_text} does not provide it.'.format( |
| 925 |
required_keys=', '.join(['"{k}"'.format(k=k) for k in require_list]), |
| 926 |
for_text=for_text, |
| 927 |
) |
| 928 |
) |
| 929 |
for exclusive_list in path_info.mutually_exclusive: |
| 930 |
found_ex_keys = [ek for ek in exclusive_list if ek in entry] |
| 931 |
if len(found_ex_keys) > 1: |
| 932 |
module.fail_json( |
| 933 |
msg='Keys {exclusive_keys} cannot be used at the same time{for_text}.'.format( |
| 934 |
exclusive_keys=', '.join(['"{k}"'.format(k=k) for k in found_ex_keys]), |
| 935 |
for_text=for_text, |
| 936 |
) |
| 937 |
) |
| 938 |
|
| 939 |
|
| 940 |
def remove_irrelevant_data(entry, path_info): |
| 941 |
for k, v in list(entry.items()): |
| 942 |
if k == '.id': |
| 943 |
continue |
| 944 |
if k not in path_info.fields or v is None: |
| 945 |
del entry[k] |
| 946 |
|
| 947 |
|
| 948 |
def match_entries(new_entries, old_entries, path_info, module): |
| 949 |
matching_old_entries = [None for entry in new_entries] |
| 950 |
old_entries = list(old_entries) |
| 951 |
matches = [] |
| 952 |
handle_absent_entries = module.params['handle_absent_entries'] |
| 953 |
if handle_absent_entries == 'remove': |
| 954 |
for new_index, (unused, new_entry) in enumerate(new_entries): |
| 955 |
for old_index, (unused, old_entry) in enumerate(old_entries): |
| 956 |
modifications, unused = find_modifications(old_entry, new_entry, path_info, module, return_none_instead_of_fail=True) |
| 957 |
if modifications is not None: |
| 958 |
matches.append((new_index, old_index, len(modifications))) |
| 959 |
else: |
| 960 |
for new_index, (unused, new_entry) in enumerate(new_entries): |
| 961 |
for old_index, (unused, old_entry) in enumerate(old_entries): |
| 962 |
weight = essentially_same_weight(old_entry, new_entry, path_info, module) |
| 963 |
if weight is not None: |
| 964 |
matches.append((new_index, old_index, weight)) |
| 965 |
matches.sort(key=lambda entry: entry[2]) |
| 966 |
for new_index, old_index, rating in matches: |
| 967 |
if matching_old_entries[new_index] is not None or old_entries[old_index] is None: |
| 968 |
continue |
| 969 |
matching_old_entries[new_index], old_entries[old_index] = old_entries[old_index], None |
| 970 |
unmatched_old_entries = [index_entry for index_entry in old_entries if index_entry is not None] |
| 971 |
return matching_old_entries, unmatched_old_entries |
| 972 |
|
| 973 |
|
| 974 |
def remove_dynamic(entries): |
| 975 |
result = [] |
| 976 |
for entry in entries: |
| 977 |
if entry.get('dynamic', False) or entry.get('builtin', False): |
| 978 |
continue |
| 979 |
result.append(entry) |
| 980 |
return result |
| 981 |
|
| 982 |
|
| 983 |
def get_api_data(api_path, path_info): |
| 984 |
entries = list(api_path) |
| 985 |
for entry in entries: |
| 986 |
for k, field_info in path_info.fields.items(): |
| 987 |
if field_info.absent_value is not None and k not in entry: |
| 988 |
entry[k] = field_info.absent_value |
| 989 |
return entries |
| 990 |
|
| 991 |
|
| 992 |
def prepare_for_add(entry, path_info): |
| 993 |
new_entry = {} |
| 994 |
for k, v in entry.items(): |
| 995 |
if k.startswith('!'): |
| 996 |
real_k = k[1:] |
| 997 |
remove_value = path_info.fields[real_k].remove_value |
| 998 |
if remove_value is not None: |
| 999 |
k = real_k |
| 1000 |
v = remove_value |
| 1001 |
else: |
| 1002 |
if v is None: |
| 1003 |
v = path_info.fields[k].remove_value |
| 1004 |
new_entry[k] = v |
| 1005 |
return new_entry |
| 1006 |
|
| 1007 |
|
| 1008 |
def remove_rejected(data, path_info, restrict_data): |
| 1009 |
return [ |
| 1010 |
entry for entry in data |
| 1011 |
if restrict_entry_accepted(entry, path_info, restrict_data) |
| 1012 |
] |
| 1013 |
|
| 1014 |
|
| 1015 |
def sync_list(module, api, path, path_info, restrict_data): |
| 1016 |
handle_absent_entries = module.params['handle_absent_entries'] |
| 1017 |
handle_entries_content = module.params['handle_entries_content'] |
| 1018 |
if handle_absent_entries == 'remove': |
| 1019 |
if handle_entries_content == 'ignore': |
| 1020 |
module.fail_json( |
| 1021 |
msg='For this path, handle_absent_entries=remove cannot be combined with handle_entries_content=ignore' |
| 1022 |
) |
| 1023 |
|
| 1024 |
stratify_keys = path_info.stratify_keys or () |
| 1025 |
|
| 1026 |
data = module.params['data'] |
| 1027 |
stratified_data = defaultdict(list) |
| 1028 |
for index, entry in enumerate(data): |
| 1029 |
if not restrict_entry_accepted(entry, path_info, restrict_data): |
| 1030 |
module.fail_json(msg='The element at index #{index} does not match `restrict`'.format(index=index + 1)) |
| 1031 |
for stratify_key in stratify_keys: |
| 1032 |
if stratify_key not in entry: |
| 1033 |
module.fail_json( |
| 1034 |
msg='Every element in data must contain "{stratify_key}". For example, the element at index #{index} does not provide it.'.format( |
| 1035 |
stratify_key=stratify_key, |
| 1036 |
index=index + 1, |
| 1037 |
) |
| 1038 |
) |
| 1039 |
polish_entry(entry, path_info, module, ' at index {index}'.format(index=index + 1)) |
| 1040 |
# Compute stratification keys AFTER sanitization so they match |
| 1041 |
# the normalised form RouterOS stores and returns. |
| 1042 |
sks = tuple(entry[stratify_key] for stratify_key in stratify_keys) |
| 1043 |
stratified_data[sks].append((index, entry)) |
| 1044 |
stratified_data = dict(stratified_data) |
| 1045 |
|
| 1046 |
api_path = compose_api_path(api, path) |
| 1047 |
|
| 1048 |
old_data = get_api_data(api_path, path_info) |
| 1049 |
old_data = remove_dynamic(old_data) |
| 1050 |
old_data = remove_rejected(old_data, path_info, restrict_data) |
| 1051 |
stratified_old_data = defaultdict(list) |
| 1052 |
for index, entry in enumerate(old_data): |
| 1053 |
sks = tuple(entry[stratify_key] for stratify_key in stratify_keys) |
| 1054 |
stratified_old_data[sks].append((index, entry)) |
| 1055 |
stratified_old_data = dict(stratified_old_data) |
| 1056 |
|
| 1057 |
create_list = [] |
| 1058 |
modify_list = [] |
| 1059 |
remove_list = [] |
| 1060 |
|
| 1061 |
new_data = [] |
| 1062 |
for key, indexed_entries in stratified_data.items(): |
| 1063 |
old_entries = stratified_old_data.pop(key, []) |
| 1064 |
|
| 1065 |
# Try to match indexed_entries with old_entries |
| 1066 |
matching_old_entries, unmatched_old_entries = match_entries(indexed_entries, old_entries, path_info, module) |
| 1067 |
|
| 1068 |
# Update existing entries |
| 1069 |
for (index, new_entry), potential_old_entry in zip(indexed_entries, matching_old_entries): |
| 1070 |
if potential_old_entry is not None: |
| 1071 |
old_index, old_entry = potential_old_entry |
| 1072 |
modifications, updated_entry = find_modifications( |
| 1073 |
old_entry, new_entry, path_info, module, |
| 1074 |
' at index {index}'.format(index=index + 1), |
| 1075 |
) |
| 1076 |
# Add to modification list if there are changes |
| 1077 |
if modifications: |
| 1078 |
modifications['.id'] = old_entry['.id'] |
| 1079 |
modify_list.append(modifications) |
| 1080 |
new_data.append((old_index, updated_entry)) |
| 1081 |
new_entry['.id'] = old_entry['.id'] |
| 1082 |
else: |
| 1083 |
remove_read_only(new_entry, path_info) |
| 1084 |
create_list.append(new_entry) |
| 1085 |
|
| 1086 |
if handle_absent_entries == 'remove': |
| 1087 |
remove_list.extend(entry['.id'] for index, entry in unmatched_old_entries) |
| 1088 |
else: |
| 1089 |
new_data.extend(unmatched_old_entries) |
| 1090 |
|
| 1091 |
for key, entries in stratified_old_data.items(): |
| 1092 |
if handle_absent_entries == 'remove': |
| 1093 |
remove_list.extend(entry['.id'] for index, entry in entries) |
| 1094 |
else: |
| 1095 |
new_data.extend(entries) |
| 1096 |
|
| 1097 |
new_data = [entry for index, entry in sorted(new_data, key=lambda entry: entry[0])] |
| 1098 |
new_data.extend(create_list) |
| 1099 |
|
| 1100 |
reorder_list = [] |
| 1101 |
if module.params['ensure_order']: |
| 1102 |
for index, entry in enumerate(data): |
| 1103 |
if '.id' in entry: |
| 1104 |
def match(current_entry): |
| 1105 |
return current_entry['.id'] == entry['.id'] |
| 1106 |
|
| 1107 |
else: |
| 1108 |
def match(current_entry): |
| 1109 |
return current_entry is entry |
| 1110 |
|
| 1111 |
current_index = next(current_index + index for current_index, current_entry in enumerate(new_data[index:]) if match(current_entry)) |
| 1112 |
if current_index != index: |
| 1113 |
reorder_list.append((index, new_data[current_index], new_data[index])) |
| 1114 |
new_data.insert(index, new_data.pop(current_index)) |
| 1115 |
|
| 1116 |
if not module.check_mode: |
| 1117 |
if remove_list: |
| 1118 |
try: |
| 1119 |
api_path.remove(*remove_list) |
| 1120 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1121 |
module.fail_json( |
| 1122 |
msg='Error while removing {remove_list}: {error}'.format( |
| 1123 |
remove_list=', '.join(['ID {id}'.format(id=id) for id in remove_list]), |
| 1124 |
error=to_native(e), |
| 1125 |
) |
| 1126 |
) |
| 1127 |
for modifications in modify_list: |
| 1128 |
try: |
| 1129 |
api_path.update(**modifications) |
| 1130 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1131 |
module.fail_json( |
| 1132 |
msg='Error while modifying for ID {id}: {error}'.format( |
| 1133 |
id=modifications['.id'], |
| 1134 |
error=to_native(e), |
| 1135 |
) |
| 1136 |
) |
| 1137 |
for entry in create_list: |
| 1138 |
try: |
| 1139 |
entry['.id'] = api_path.add(**prepare_for_add(entry, path_info)) |
| 1140 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1141 |
module.fail_json( |
| 1142 |
msg='Error while creating entry: {error}'.format( |
| 1143 |
error=to_native(e), |
| 1144 |
) |
| 1145 |
) |
| 1146 |
for new_index, new_entry, old_entry in reorder_list: |
| 1147 |
try: |
| 1148 |
for res in api_path('move', numbers=new_entry['.id'], destination=old_entry['.id']): |
| 1149 |
pass |
| 1150 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1151 |
module.fail_json( |
| 1152 |
msg='Error while moving entry ID {element_id} to position #{new_index} ID ({new_id}): {error}'.format( |
| 1153 |
element_id=new_entry['.id'], |
| 1154 |
new_index=new_index, |
| 1155 |
new_id=old_entry['.id'], |
| 1156 |
error=to_native(e), |
| 1157 |
) |
| 1158 |
) |
| 1159 |
|
| 1160 |
# For sake of completeness, retrieve the full new data: |
| 1161 |
if modify_list or create_list or reorder_list: |
| 1162 |
new_data = remove_dynamic(get_api_data(api_path, path_info)) |
| 1163 |
new_data = remove_rejected(new_data, path_info, restrict_data) |
| 1164 |
|
| 1165 |
# Remove 'irrelevant' data |
| 1166 |
for entry in old_data: |
| 1167 |
remove_irrelevant_data(entry, path_info) |
| 1168 |
for entry in new_data: |
| 1169 |
remove_irrelevant_data(entry, path_info) |
| 1170 |
|
| 1171 |
# Produce return value |
| 1172 |
more = {} |
| 1173 |
if module._diff: |
| 1174 |
more['diff'] = { |
| 1175 |
'before': { |
| 1176 |
'data': old_data, |
| 1177 |
}, |
| 1178 |
'after': { |
| 1179 |
'data': new_data, |
| 1180 |
}, |
| 1181 |
} |
| 1182 |
module.exit_json( |
| 1183 |
changed=bool(create_list or modify_list or remove_list or reorder_list), |
| 1184 |
old_data=old_data, |
| 1185 |
new_data=new_data, |
| 1186 |
**more |
| 1187 |
) |
| 1188 |
|
| 1189 |
|
| 1190 |
def sync_with_primary_keys(module, api, path, path_info, restrict_data): |
| 1191 |
primary_keys = path_info.primary_keys |
| 1192 |
|
| 1193 |
if path_info.fixed_entries: |
| 1194 |
if module.params['ensure_order']: |
| 1195 |
module.fail_json(msg='ensure_order=true cannot be used with this path') |
| 1196 |
if module.params['handle_absent_entries'] == 'remove': |
| 1197 |
module.fail_json(msg='handle_absent_entries=remove cannot be used with this path') |
| 1198 |
|
| 1199 |
data = module.params['data'] |
| 1200 |
new_data_by_key = OrderedDict() |
| 1201 |
for index, entry in enumerate(data): |
| 1202 |
if not restrict_entry_accepted(entry, path_info, restrict_data): |
| 1203 |
module.fail_json(msg='The element at index #{index} does not match `restrict`'.format(index=index + 1)) |
| 1204 |
for primary_key in primary_keys: |
| 1205 |
if primary_key not in entry: |
| 1206 |
module.fail_json( |
| 1207 |
msg='Every element in data must contain "{primary_key}". For example, the element at index #{index} does not provide it.'.format( |
| 1208 |
primary_key=primary_key, |
| 1209 |
index=index + 1, |
| 1210 |
) |
| 1211 |
) |
| 1212 |
# Build for_text from raw values — only used for human-readable error |
| 1213 |
# messages inside polish_entry, so pre-sanitization values are fine here |
| 1214 |
for_text = ' for values {0}'.format( |
| 1215 |
', '.join( |
| 1216 |
'{pk}={value!r}'.format(pk=pk, value=entry[pk]) |
| 1217 |
for pk in primary_keys |
| 1218 |
) |
| 1219 |
) |
| 1220 |
|
| 1221 |
# Sanitize the entry in-place (e.g. 'TEST' → '/TEST') |
| 1222 |
polish_entry(entry, path_info, module, for_text) |
| 1223 |
|
| 1224 |
# Compute primary keys AFTER sanitization so the key should match to what RouterOS returns |
| 1225 |
pks = tuple(value_to_str(entry[primary_key]) for primary_key in primary_keys) |
| 1226 |
|
| 1227 |
if pks in new_data_by_key: |
| 1228 |
module.fail_json( |
| 1229 |
msg='Every element in data must contain a unique value for {pks}. ' |
| 1230 |
'The value {value} appears at least twice.'.format( |
| 1231 |
pks=', '.join(primary_keys), |
| 1232 |
value=', '.join('{0}'.format(pk) for pk in pks), |
| 1233 |
) |
| 1234 |
) |
| 1235 |
new_data_by_key[pks] = entry |
| 1236 |
|
| 1237 |
api_path = compose_api_path(api, path) |
| 1238 |
|
| 1239 |
old_data = get_api_data(api_path, path_info) |
| 1240 |
old_data = remove_dynamic(old_data) |
| 1241 |
old_data = remove_rejected(old_data, path_info, restrict_data) |
| 1242 |
old_data_by_key = OrderedDict() |
| 1243 |
id_by_key = {} |
| 1244 |
for entry in old_data: |
| 1245 |
pks = tuple(value_to_str(entry[primary_key]) for primary_key in primary_keys) |
| 1246 |
old_data_by_key[pks] = entry |
| 1247 |
id_by_key[pks] = entry['.id'] |
| 1248 |
new_data = [] |
| 1249 |
|
| 1250 |
create_list = [] |
| 1251 |
modify_list = [] |
| 1252 |
remove_list = [] |
| 1253 |
remove_keys = [] |
| 1254 |
handle_absent_entries = module.params['handle_absent_entries'] |
| 1255 |
for key, old_entry in old_data_by_key.items(): |
| 1256 |
new_entry = new_data_by_key.pop(key, None) |
| 1257 |
if new_entry is None: |
| 1258 |
if handle_absent_entries == 'remove': |
| 1259 |
remove_list.append(old_entry['.id']) |
| 1260 |
remove_keys.append(key) |
| 1261 |
else: |
| 1262 |
new_data.append(old_entry) |
| 1263 |
else: |
| 1264 |
modifications, updated_entry = find_modifications( |
| 1265 |
old_entry, new_entry, path_info, module, |
| 1266 |
' for {values}'.format( |
| 1267 |
values=', '.join([ |
| 1268 |
'{primary_key}="{value}"'.format(primary_key=primary_key, value=value) |
| 1269 |
for primary_key, value in zip(primary_keys, key) |
| 1270 |
]) |
| 1271 |
) |
| 1272 |
) |
| 1273 |
new_data.append(updated_entry) |
| 1274 |
# Add to modification list if there are changes |
| 1275 |
if modifications: |
| 1276 |
modifications['.id'] = old_entry['.id'] |
| 1277 |
modify_list.append((key, modifications)) |
| 1278 |
for new_entry in new_data_by_key.values(): |
| 1279 |
if path_info.fixed_entries: |
| 1280 |
module.fail_json(msg='Cannot add new entry {values} to this path'.format( |
| 1281 |
values=', '.join([ |
| 1282 |
'{primary_key}="{value}"'.format(primary_key=primary_key, value=new_entry[primary_key]) |
| 1283 |
for primary_key in primary_keys |
| 1284 |
]), |
| 1285 |
)) |
| 1286 |
remove_read_only(new_entry, path_info) |
| 1287 |
create_list.append(new_entry) |
| 1288 |
new_entry = new_entry.copy() |
| 1289 |
for key in list(new_entry): |
| 1290 |
if key.startswith('!'): |
| 1291 |
new_entry.pop(key) |
| 1292 |
new_data.append(new_entry) |
| 1293 |
|
| 1294 |
reorder_list = [] |
| 1295 |
if module.params['ensure_order']: |
| 1296 |
index_by_key = dict() |
| 1297 |
for index, entry in enumerate(new_data): |
| 1298 |
index_by_key[tuple(value_to_str(entry[primary_key]) for primary_key in primary_keys)] = index |
| 1299 |
for index, source_entry in enumerate(data): |
| 1300 |
source_pks = tuple(value_to_str(source_entry[primary_key]) for primary_key in primary_keys) |
| 1301 |
source_index = index_by_key.pop(source_pks) |
| 1302 |
if index == source_index: |
| 1303 |
continue |
| 1304 |
entry = new_data[index] |
| 1305 |
pks = tuple(value_to_str(entry[primary_key]) for primary_key in primary_keys) |
| 1306 |
reorder_list.append((source_pks, index, pks)) |
| 1307 |
for k, v in index_by_key.items(): |
| 1308 |
if v >= index and v < source_index: |
| 1309 |
index_by_key[k] = v + 1 |
| 1310 |
new_data.insert(index, new_data.pop(source_index)) |
| 1311 |
|
| 1312 |
if not module.check_mode: |
| 1313 |
if remove_list: |
| 1314 |
try: |
| 1315 |
api_path.remove(*remove_list) |
| 1316 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1317 |
module.fail_json( |
| 1318 |
msg='Error while removing {remove_list}: {error}'.format( |
| 1319 |
remove_list=', '.join([ |
| 1320 |
'{identifier} (ID {id})'.format(identifier=format_pk(primary_keys, key), id=id) |
| 1321 |
for id, key in zip(remove_list, remove_keys) |
| 1322 |
]), |
| 1323 |
error=to_native(e), |
| 1324 |
) |
| 1325 |
) |
| 1326 |
for key, modifications in modify_list: |
| 1327 |
try: |
| 1328 |
api_path.update(**modifications) |
| 1329 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1330 |
module.fail_json( |
| 1331 |
msg='Error while modifying for {identifier} (ID {id}): {error}'.format( |
| 1332 |
identifier=format_pk(primary_keys, key), |
| 1333 |
id=modifications['.id'], |
| 1334 |
error=to_native(e), |
| 1335 |
) |
| 1336 |
) |
| 1337 |
for entry in create_list: |
| 1338 |
try: |
| 1339 |
entry['.id'] = api_path.add(**prepare_for_add(entry, path_info)) |
| 1340 |
# Store ID for primary keys |
| 1341 |
pks = tuple(entry[primary_key] for primary_key in primary_keys) |
| 1342 |
id_by_key[pks] = entry['.id'] |
| 1343 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1344 |
module.fail_json( |
| 1345 |
msg='Error while creating entry for {identifier}: {error}'.format( |
| 1346 |
identifier=format_pk(primary_keys, [entry[pk] for pk in primary_keys]), |
| 1347 |
error=to_native(e), |
| 1348 |
) |
| 1349 |
) |
| 1350 |
for element_pks, new_index, new_pks in reorder_list: |
| 1351 |
try: |
| 1352 |
element_id = id_by_key[element_pks] |
| 1353 |
new_id = id_by_key[new_pks] |
| 1354 |
for res in api_path('move', numbers=element_id, destination=new_id): |
| 1355 |
pass |
| 1356 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1357 |
module.fail_json( |
| 1358 |
msg='Error while moving entry ID {element_id} to position of ID {new_id}: {error}'.format( |
| 1359 |
element_id=element_id, |
| 1360 |
new_id=new_id, |
| 1361 |
error=to_native(e), |
| 1362 |
) |
| 1363 |
) |
| 1364 |
|
| 1365 |
# For sake of completeness, retrieve the full new data: |
| 1366 |
if modify_list or create_list or reorder_list: |
| 1367 |
new_data = remove_dynamic(get_api_data(api_path, path_info)) |
| 1368 |
new_data = remove_rejected(new_data, path_info, restrict_data) |
| 1369 |
|
| 1370 |
# Remove 'irrelevant' data |
| 1371 |
for entry in old_data: |
| 1372 |
remove_irrelevant_data(entry, path_info) |
| 1373 |
for entry in new_data: |
| 1374 |
remove_irrelevant_data(entry, path_info) |
| 1375 |
|
| 1376 |
# Produce return value |
| 1377 |
more = {} |
| 1378 |
if module._diff: |
| 1379 |
more['diff'] = { |
| 1380 |
'before': { |
| 1381 |
'data': old_data, |
| 1382 |
}, |
| 1383 |
'after': { |
| 1384 |
'data': new_data, |
| 1385 |
}, |
| 1386 |
} |
| 1387 |
module.exit_json( |
| 1388 |
changed=bool(create_list or modify_list or remove_list or reorder_list), |
| 1389 |
old_data=old_data, |
| 1390 |
new_data=new_data, |
| 1391 |
**more |
| 1392 |
) |
| 1393 |
|
| 1394 |
|
| 1395 |
def sync_single_value(module, api, path, path_info, restrict_data): |
| 1396 |
if module.params['restrict'] is not None: |
| 1397 |
module.fail_json(msg='The restrict option cannot be used with this path, since there is precisely one entry.') |
| 1398 |
data = module.params['data'] |
| 1399 |
if len(data) != 1: |
| 1400 |
module.fail_json(msg='Data must be a list with exactly one element.') |
| 1401 |
new_entry = data[0] |
| 1402 |
polish_entry(new_entry, path_info, module, '') |
| 1403 |
|
| 1404 |
api_path = compose_api_path(api, path) |
| 1405 |
|
| 1406 |
old_data = get_api_data(api_path, path_info) |
| 1407 |
if len(old_data) != 1: |
| 1408 |
module.fail_json( |
| 1409 |
msg='Internal error: retrieving /{path} resulted in {count} elements. Expected exactly 1.'.format( |
| 1410 |
path=join_path(path), |
| 1411 |
count=len(old_data) |
| 1412 |
) |
| 1413 |
) |
| 1414 |
old_entry = old_data[0] |
| 1415 |
|
| 1416 |
# Determine modifications |
| 1417 |
modifications, updated_entry = find_modifications(old_entry, new_entry, path_info, module, '') |
| 1418 |
# Do modifications |
| 1419 |
if modifications: |
| 1420 |
if not module.check_mode: |
| 1421 |
# Actually do modification |
| 1422 |
try: |
| 1423 |
api_path.update(**modifications) |
| 1424 |
except (LibRouterosError, UnicodeEncodeError) as e: |
| 1425 |
module.fail_json(msg='Error while modifying: {error}'.format(error=to_native(e))) |
| 1426 |
# Retrieve latest version |
| 1427 |
new_data = get_api_data(api_path, path_info) |
| 1428 |
if len(new_data) == 1: |
| 1429 |
updated_entry = new_data[0] |
| 1430 |
|
| 1431 |
# Remove 'irrelevant' data |
| 1432 |
remove_irrelevant_data(old_entry, path_info) |
| 1433 |
remove_irrelevant_data(updated_entry, path_info) |
| 1434 |
|
| 1435 |
# Produce return value |
| 1436 |
more = {} |
| 1437 |
if module._diff: |
| 1438 |
more['diff'] = { |
| 1439 |
'before': old_entry, |
| 1440 |
'after': updated_entry, |
| 1441 |
} |
| 1442 |
module.exit_json( |
| 1443 |
changed=bool(modifications), |
| 1444 |
old_data=[old_entry], |
| 1445 |
new_data=[updated_entry], |
| 1446 |
**more |
| 1447 |
) |
| 1448 |
|
| 1449 |
|
| 1450 |
def get_backend(path_info): |
| 1451 |
if path_info is None: |
| 1452 |
return None |
| 1453 |
if not path_info.fully_understood: |
| 1454 |
return None |
| 1455 |
|
| 1456 |
if path_info.primary_keys: |
| 1457 |
return sync_with_primary_keys |
| 1458 |
|
| 1459 |
if path_info.single_value: |
| 1460 |
return sync_single_value |
| 1461 |
|
| 1462 |
if not path_info.has_identifier and not path_info.modify_not_supported: |
| 1463 |
return sync_list |
| 1464 |
|
| 1465 |
return None |
| 1466 |
|
| 1467 |
|
| 1468 |
def has_backend(versioned_path_info): |
| 1469 |
if not versioned_path_info.fully_understood: |
| 1470 |
return False |
| 1471 |
|
| 1472 |
if versioned_path_info.hardware_variants is not None: |
| 1473 |
return any(has_backend(v) for v in versioned_path_info.hardware_variants.values()) |
| 1474 |
|
| 1475 |
if versioned_path_info.unversioned is not None: |
| 1476 |
return get_backend(versioned_path_info.unversioned) is not None |
| 1477 |
|
| 1478 |
if versioned_path_info.versioned is not None: |
| 1479 |
for dummy, dummy, unversioned in versioned_path_info.versioned: |
| 1480 |
if unversioned and not isinstance(unversioned, str) and get_backend(unversioned) is not None: |
| 1481 |
return True |
| 1482 |
|
| 1483 |
return False |
| 1484 |
|
| 1485 |
|
| 1486 |
def main(): |
| 1487 |
path_choices = sorted([join_path(path) for path, versioned_path_info in PATHS.items() if has_backend(versioned_path_info)]) |
| 1488 |
module_args = dict( |
| 1489 |
path=dict(type='str', required=True, choices=path_choices), |
| 1490 |
data=dict(type='list', elements='dict', required=True), |
| 1491 |
handle_absent_entries=dict(type='str', choices=['ignore', 'remove'], default='ignore'), |
| 1492 |
handle_entries_content=dict(type='str', choices=['ignore', 'remove', 'remove_as_much_as_possible'], default='ignore'), |
| 1493 |
ensure_order=dict(type='bool', default=False), |
| 1494 |
handle_read_only=dict(type='str', default='error', choices=['ignore', 'validate', 'error']), |
| 1495 |
handle_write_only=dict(type='str', default='create_only', choices=['create_only', 'always_update', 'error']), |
| 1496 |
) |
| 1497 |
module_args.update(api_argument_spec()) |
| 1498 |
module_args.update(restrict_argument_spec()) |
| 1499 |
|
| 1500 |
module = AnsibleModule( |
| 1501 |
argument_spec=module_args, |
| 1502 |
supports_check_mode=True, |
| 1503 |
) |
| 1504 |
if module.params['ensure_order'] and module.params['handle_absent_entries'] == 'ignore': |
| 1505 |
module.fail_json(msg='ensure_order=true requires handle_absent_entries=remove') |
| 1506 |
|
| 1507 |
if not HAS_ORDEREDDICT: |
| 1508 |
# This should never happen for Python 2.7+ |
| 1509 |
module.fail_json(msg=missing_required_lib('ordereddict')) |
| 1510 |
|
| 1511 |
check_has_library(module) |
| 1512 |
api = create_api(module) |
| 1513 |
|
| 1514 |
path = split_path(module.params['path']) |
| 1515 |
versioned_path_info = PATHS.get(tuple(path)) |
| 1516 |
|
| 1517 |
if versioned_path_info.hardware_detect: |
| 1518 |
hardware_variant_key = get_cached_or_detect(versioned_path_info.hardware_detect, api) |
| 1519 |
if hardware_variant_key not in versioned_path_info.hardware_variants: |
| 1520 |
module.fail_json( |
| 1521 |
msg='Path /{path} is not supported for detected hardware variant {variant}'.format( |
| 1522 |
path='/'.join(path), variant=hardware_variant_key)) |
| 1523 |
versioned_path_info = versioned_path_info.hardware_variants[hardware_variant_key] |
| 1524 |
|
| 1525 |
if versioned_path_info.needs_version: |
| 1526 |
api_version = get_api_version(api) |
| 1527 |
supported, not_supported_msg = versioned_path_info.provide_version(api_version) |
| 1528 |
if not supported: |
| 1529 |
msg = 'Path /{path} is not supported for API version {api_version}'.format(path='/'.join(path), api_version=api_version) |
| 1530 |
if not_supported_msg: |
| 1531 |
msg = '{0}: {1}'.format(msg, not_supported_msg) |
| 1532 |
module.fail_json(msg=msg) |
| 1533 |
path_info = versioned_path_info.get_data() |
| 1534 |
|
| 1535 |
backend = get_backend(path_info) |
| 1536 |
if path_info is None or backend is None: |
| 1537 |
module.fail_json(msg='Path /{path} is not yet supported'.format(path='/'.join(path))) |
| 1538 |
|
| 1539 |
restrict_data = validate_and_prepare_restrict(module, path_info) |
| 1540 |
|
| 1541 |
backend(module, api, path, path_info, restrict_data) |
| 1542 |
|
| 1543 |
|
| 1544 |
if __name__ == '__main__': |
| 1545 |
main() |