| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2025, Jana Hoch <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
module: proxmox_firewall |
| 10 |
short_description: Manage firewall rules in Proxmox |
| 11 |
version_added: "1.4.0" |
| 12 |
description: |
| 13 |
- create/update/delete FW rules at cluster/group/vnet/node/vm level |
| 14 |
- Create/delete firewall security groups |
| 15 |
- Create/delete aliases |
| 16 |
author: 'Jana Hoch <[email protected]> (!UNKNOWN)' |
| 17 |
attributes: |
| 18 |
check_mode: |
| 19 |
support: none |
| 20 |
diff_mode: |
| 21 |
support: none |
| 22 |
options: |
| 23 |
state: |
| 24 |
description: |
| 25 |
- Create/update/delete firewall rules or security group. |
| 26 |
type: str |
| 27 |
choices: |
| 28 |
- present |
| 29 |
- absent |
| 30 |
default: present |
| 31 |
update: |
| 32 |
description: |
| 33 |
- If O(state=present) and if one or more rule/alias/ipset already exists it will update them. |
| 34 |
type: bool |
| 35 |
default: true |
| 36 |
level: |
| 37 |
description: |
| 38 |
- Level at which the firewall rule applies. |
| 39 |
type: str |
| 40 |
choices: |
| 41 |
- cluster |
| 42 |
- group |
| 43 |
- vnet |
| 44 |
- node |
| 45 |
- vm |
| 46 |
default: cluster |
| 47 |
node: |
| 48 |
description: |
| 49 |
- Name of the node. |
| 50 |
- Only needed when O(level=node). |
| 51 |
type: str |
| 52 |
vmid: |
| 53 |
description: |
| 54 |
- ID of the VM to which the rule applies. |
| 55 |
- Only needed when O(level=vm). |
| 56 |
type: int |
| 57 |
vnet: |
| 58 |
description: |
| 59 |
- Name of the virtual network for the rule. |
| 60 |
- Only needed when O(level=vnet). |
| 61 |
type: str |
| 62 |
pos: |
| 63 |
description: |
| 64 |
- Position of the rule in the list. |
| 65 |
- Only needed if O(state=absent). |
| 66 |
type: int |
| 67 |
group_conf: |
| 68 |
description: |
| 69 |
- Whether security group should be created or deleted. |
| 70 |
type: bool |
| 71 |
default: false |
| 72 |
group: |
| 73 |
description: |
| 74 |
- Name of the group to which the rule belongs. |
| 75 |
- Only needed when O(level=group) or O(group_conf=true). |
| 76 |
type: str |
| 77 |
comment: |
| 78 |
description: |
| 79 |
- Comment for security group. |
| 80 |
- Only needed when creating group. |
| 81 |
type: str |
| 82 |
ip_sets: |
| 83 |
description: |
| 84 |
- List of IP set definitions to create, update, or remove. |
| 85 |
- Each IP set is a named collection of CIDRs (with optional negation and comments). |
| 86 |
type: list |
| 87 |
elements: dict |
| 88 |
required: false |
| 89 |
suboptions: |
| 90 |
name: |
| 91 |
description: |
| 92 |
- Unique name of the IP set. |
| 93 |
type: str |
| 94 |
required: true |
| 95 |
comment: |
| 96 |
description: |
| 97 |
- Optional comment for the IP set. |
| 98 |
type: str |
| 99 |
cidrs: |
| 100 |
description: |
| 101 |
- List of CIDR entries in the IP set. |
| 102 |
type: list |
| 103 |
elements: dict |
| 104 |
required: false |
| 105 |
suboptions: |
| 106 |
cidr: |
| 107 |
description: |
| 108 |
- CIDR notation for the entry. |
| 109 |
type: str |
| 110 |
required: true |
| 111 |
nomatch: |
| 112 |
description: |
| 113 |
- When true, this CIDR acts as a negative match (exclusion) within the set. |
| 114 |
type: bool |
| 115 |
default: false |
| 116 |
comment: |
| 117 |
description: |
| 118 |
- Optional comment for this CIDR entry. |
| 119 |
type: str |
| 120 |
required: false |
| 121 |
aliases: |
| 122 |
description: |
| 123 |
- List of aliases. |
| 124 |
- Alias can only be created/updated/deleted at cluster or VM level. |
| 125 |
type: list |
| 126 |
elements: dict |
| 127 |
suboptions: |
| 128 |
name: |
| 129 |
description: Alias name. |
| 130 |
type: str |
| 131 |
required: true |
| 132 |
cidr: |
| 133 |
description: |
| 134 |
- CIDR for alias. |
| 135 |
- Only needed when O(state=present) or O(state=update). |
| 136 |
type: str |
| 137 |
required: false |
| 138 |
comment: |
| 139 |
description: Comment for alias. |
| 140 |
type: str |
| 141 |
required: false |
| 142 |
rules: |
| 143 |
description: |
| 144 |
- List of individual rules to be applied. |
| 145 |
type: list |
| 146 |
elements: dict |
| 147 |
suboptions: |
| 148 |
action: |
| 149 |
description: |
| 150 |
- Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name. |
| 151 |
type: str |
| 152 |
required: true |
| 153 |
type: |
| 154 |
description: |
| 155 |
- Rule type. |
| 156 |
choices: |
| 157 |
- in |
| 158 |
- out |
| 159 |
- forward |
| 160 |
- group |
| 161 |
type: str |
| 162 |
required: true |
| 163 |
comment: |
| 164 |
description: |
| 165 |
- Optional comment for the specific rule. |
| 166 |
type: str |
| 167 |
dest: |
| 168 |
description: |
| 169 |
- Restrict packet destination address. |
| 170 |
- This can refer to a single IP address, an IP set ('+ipsetname') or an IP alias definition. |
| 171 |
- You can also specify an address range like '20.34.101.207-201.3.9.99', or a list of IP addresses and networks (entries are separated by comma). |
| 172 |
- Please do not mix IPv4 and IPv6 addresses inside such lists. |
| 173 |
type: str |
| 174 |
digest: |
| 175 |
description: |
| 176 |
- Prevent changes if current configuration file has a different digest. |
| 177 |
- This can be used to prevent concurrent modifications. |
| 178 |
- If not provided we will calculate at runtime. |
| 179 |
type: str |
| 180 |
dport: |
| 181 |
description: |
| 182 |
- Restrict TCP/UDP destination port. |
| 183 |
- You can use service names or simple numbers (0-65535), as defined in '/etc/services'. |
| 184 |
- Port ranges can be specified with '\d+:\d+', for example '80:85', and you can use comma separated list to match several ports or ranges. |
| 185 |
type: str |
| 186 |
enable: |
| 187 |
description: |
| 188 |
- Enable or disable the rule. |
| 189 |
type: bool |
| 190 |
icmp_type: |
| 191 |
description: |
| 192 |
- Specify icmp-type. Only valid if proto equals 'icmp' or 'icmpv6'/'ipv6-icmp'. |
| 193 |
type: str |
| 194 |
iface: |
| 195 |
description: |
| 196 |
- Network interface name. You have to use network configuration key names for VMs and containers ('net\d+'). |
| 197 |
- Host related rules can use arbitrary strings. |
| 198 |
type: str |
| 199 |
log: |
| 200 |
description: |
| 201 |
- Logging level for the rule. |
| 202 |
choices: |
| 203 |
- emerg |
| 204 |
- alert |
| 205 |
- crit |
| 206 |
- err |
| 207 |
- warning |
| 208 |
- notice |
| 209 |
- info |
| 210 |
- debug |
| 211 |
- nolog |
| 212 |
type: str |
| 213 |
macro: |
| 214 |
description: |
| 215 |
- Use predefined standard macro. |
| 216 |
type: str |
| 217 |
pos: |
| 218 |
description: |
| 219 |
- Position of the rule in the list. |
| 220 |
type: int |
| 221 |
required: true |
| 222 |
proto: |
| 223 |
description: |
| 224 |
- IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'. |
| 225 |
type: str |
| 226 |
source: |
| 227 |
description: |
| 228 |
- Restrict packet source address. |
| 229 |
- This can refer to a single IP address, an IP set ('+ipsetname') or an IP alias definition. |
| 230 |
- You can also specify an address range like '20.34.101.207-201.3.9.99', or a list of IP addresses and networks (entries are separated by comma). |
| 231 |
- Please do not mix IPv4 and IPv6 addresses inside such lists. |
| 232 |
type: str |
| 233 |
sport: |
| 234 |
description: |
| 235 |
- Restrict TCP/UDP source port. |
| 236 |
- You can use service names or simple numbers (0-65535), as defined in '/etc/services'. |
| 237 |
- Port ranges can be specified with '\d+:\d+', for example '80:85', and you can use comma separated list to match several ports or ranges. |
| 238 |
type: str |
| 239 |
extends_documentation_fragment: |
| 240 |
- community.proxmox.proxmox.actiongroup_proxmox |
| 241 |
- community.proxmox.proxmox.documentation |
| 242 |
- community.proxmox.attributes |
| 243 |
""" |
| 244 |
|
| 245 |
EXAMPLES = r""" |
| 246 |
- name: Create firewall rules at cluster level |
| 247 |
community.proxmox.proxmox_firewall: |
| 248 |
level: cluster |
| 249 |
state: present |
| 250 |
rules: |
| 251 |
- type: out |
| 252 |
action: ACCEPT |
| 253 |
source: 1.1.1.1 |
| 254 |
log: nolog |
| 255 |
pos: 9 |
| 256 |
enable: true |
| 257 |
- type: out |
| 258 |
action: ACCEPT |
| 259 |
source: 1.0.0.1 |
| 260 |
pos: 10 |
| 261 |
enable: true |
| 262 |
|
| 263 |
- name: Update Cluster level firewall rules |
| 264 |
community.proxmox.proxmox_firewall: |
| 265 |
level: cluster |
| 266 |
state: present |
| 267 |
update: true |
| 268 |
rules: |
| 269 |
- type: out |
| 270 |
action: ACCEPT |
| 271 |
source: 8.8.8.8 |
| 272 |
log: nolog |
| 273 |
pos: 9 |
| 274 |
enable: false |
| 275 |
- type: out |
| 276 |
action: ACCEPT |
| 277 |
source: 8.8.4.4 |
| 278 |
pos: 10 |
| 279 |
enable: false |
| 280 |
|
| 281 |
- name: Delete cluster level firewall rule at pos 10 |
| 282 |
community.proxmox.proxmox_firewall: |
| 283 |
level: cluster |
| 284 |
state: absent |
| 285 |
pos: 10 |
| 286 |
|
| 287 |
- name: Create security group |
| 288 |
community.proxmox.proxmox_firewall: |
| 289 |
group_conf: true |
| 290 |
state: present |
| 291 |
group: test |
| 292 |
|
| 293 |
- name: Delete security group |
| 294 |
community.proxmox.proxmox_firewall: |
| 295 |
group_conf: true |
| 296 |
state: absent |
| 297 |
group: test |
| 298 |
|
| 299 |
- name: Create FW aliases |
| 300 |
community.proxmox.proxmox_firewall: |
| 301 |
state: present |
| 302 |
aliases: |
| 303 |
- name: test1 |
| 304 |
cidr: '10.10.1.0/24' |
| 305 |
- name: test2 |
| 306 |
cidr: '10.10.2.0/24' |
| 307 |
|
| 308 |
- name: Update FW aliases |
| 309 |
community.proxmox.proxmox_firewall: |
| 310 |
state: present |
| 311 |
update: true |
| 312 |
aliases: |
| 313 |
- name: test1 |
| 314 |
cidr: '10.10.1.0/28' |
| 315 |
- name: test2 |
| 316 |
cidr: '10.10.2.0/28' |
| 317 |
|
| 318 |
- name: Delete FW aliases |
| 319 |
community.proxmox.proxmox_firewall: |
| 320 |
state: absent |
| 321 |
aliases: |
| 322 |
- name: test1 |
| 323 |
- name: test2 |
| 324 |
|
| 325 |
- name: Create IP SET |
| 326 |
community.proxmox.proxmox_firewall: |
| 327 |
ip_sets: |
| 328 |
- name: hypervisors |
| 329 |
comment: PVE hosts |
| 330 |
cidrs: |
| 331 |
- cidr: 192.168.1.10 |
| 332 |
nomatch: false |
| 333 |
comment: Proxmox pve-01 |
| 334 |
- cidr: 192.168.1.11 |
| 335 |
nomatch: true |
| 336 |
comment: Proxmox pve-02 |
| 337 |
- name: test |
| 338 |
comment: PVE hosts |
| 339 |
cidrs: |
| 340 |
- cidr: 10.10.1.0 |
| 341 |
comment: Proxmox pve-01 |
| 342 |
|
| 343 |
- name: Delete IP SETs |
| 344 |
community.proxmox.proxmox_firewall: |
| 345 |
state: absent |
| 346 |
ip_sets: |
| 347 |
- name: hypervisors |
| 348 |
|
| 349 |
- name: Delete specific CIDR from IP SET |
| 350 |
community.proxmox.proxmox_firewall: |
| 351 |
state: absent |
| 352 |
ip_sets: |
| 353 |
- name: test |
| 354 |
cidrs: |
| 355 |
- cidr: 10.10.1.0 |
| 356 |
""" |
| 357 |
|
| 358 |
RETURN = r""" |
| 359 |
group: |
| 360 |
description: group name which was created/deleted |
| 361 |
returned: on success |
| 362 |
type: str |
| 363 |
sample: |
| 364 |
test |
| 365 |
""" |
| 366 |
|
| 367 |
import ipaddress |
| 368 |
import re |
| 369 |
|
| 370 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox import ( |
| 371 |
ansible_to_proxmox_bool, |
| 372 |
compare_list_of_dicts, |
| 373 |
create_proxmox_module, |
| 374 |
) |
| 375 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox_sdn import ProxmoxSdnAnsible |
| 376 |
|
| 377 |
|
| 378 |
def module_args(): |
| 379 |
return dict( |
| 380 |
state=dict(type="str", choices=["present", "absent"], default="present"), |
| 381 |
update=dict(type="bool", default=True), |
| 382 |
level=dict(type="str", choices=["cluster", "node", "vm", "vnet", "group"], default="cluster", required=False), |
| 383 |
node=dict(type="str", required=False), |
| 384 |
vmid=dict(type="int", required=False), |
| 385 |
vnet=dict(type="str", required=False), |
| 386 |
pos=dict(type="int", required=False), |
| 387 |
group_conf=dict(type="bool", default=False), |
| 388 |
group=dict(type="str", required=False), |
| 389 |
comment=dict(type="str", required=False), |
| 390 |
ip_sets=dict( |
| 391 |
type="list", |
| 392 |
elements="dict", |
| 393 |
required=False, |
| 394 |
options=dict( |
| 395 |
name=dict(type="str", required=True), |
| 396 |
comment=dict(type="str", required=False), |
| 397 |
cidrs=dict( |
| 398 |
type="list", |
| 399 |
elements="dict", |
| 400 |
required=False, |
| 401 |
options=dict( |
| 402 |
cidr=dict(type="str", required=True), |
| 403 |
nomatch=dict(type="bool", default=False), |
| 404 |
comment=dict(type="str", required=False), |
| 405 |
), |
| 406 |
), |
| 407 |
), |
| 408 |
), |
| 409 |
aliases=dict( |
| 410 |
type="list", |
| 411 |
elements="dict", |
| 412 |
required=False, |
| 413 |
options=dict( |
| 414 |
name=dict(type="str", required=True), |
| 415 |
cidr=dict(type="str", required=False), |
| 416 |
comment=dict(type="str", required=False), |
| 417 |
), |
| 418 |
), |
| 419 |
rules=dict( |
| 420 |
type="list", |
| 421 |
elements="dict", |
| 422 |
required=False, |
| 423 |
options=dict( |
| 424 |
action=dict(type="str", required=True), |
| 425 |
type=dict(type="str", choices=["in", "out", "forward", "group"], required=True), |
| 426 |
comment=dict(type="str", required=False), |
| 427 |
dest=dict(type="str", required=False), |
| 428 |
digest=dict(type="str", required=False), |
| 429 |
dport=dict(type="str", required=False), |
| 430 |
enable=dict(type="bool", required=False), |
| 431 |
icmp_type=dict(type="str", required=False), |
| 432 |
iface=dict(type="str", required=False), |
| 433 |
log=dict( |
| 434 |
type="str", |
| 435 |
choices=["emerg", "alert", "crit", "err", "warning", "notice", "info", "debug", "nolog"], |
| 436 |
required=False, |
| 437 |
), |
| 438 |
macro=dict(type="str", required=False), |
| 439 |
pos=dict(type="int", required=True), |
| 440 |
proto=dict(type="str", required=False), |
| 441 |
source=dict(type="str", required=False), |
| 442 |
sport=dict(type="str", required=False), |
| 443 |
), |
| 444 |
), |
| 445 |
) |
| 446 |
|
| 447 |
|
| 448 |
def module_options(): |
| 449 |
return dict( |
| 450 |
supports_check_mode=False, |
| 451 |
required_if=[ |
| 452 |
("group_conf", True, ["group"]), |
| 453 |
("level", "vm", ["vmid"]), |
| 454 |
("level", "node", ["node"]), |
| 455 |
("level", "vnet", ["vnet"]), |
| 456 |
("level", "group", ["group"]), |
| 457 |
], |
| 458 |
mutually_exclusive=[ |
| 459 |
("aliases", "rules"), |
| 460 |
("aliases", "ip_sets"), |
| 461 |
("rules", "ip_sets"), |
| 462 |
], |
| 463 |
) |
| 464 |
|
| 465 |
|
| 466 |
class ProxmoxFirewallAnsible(ProxmoxSdnAnsible): |
| 467 |
def __init__(self, module): |
| 468 |
super().__init__(module) |
| 469 |
self.params = module.params |
| 470 |
|
| 471 |
def validate_params(self): |
| 472 |
if self.params.get("state") == "present": |
| 473 |
if self.params.get("group_conf") != bool( |
| 474 |
self.params.get("rules") or self.params.get("aliases") or self.params.get("ip_sets") |
| 475 |
): |
| 476 |
return True |
| 477 |
else: |
| 478 |
self.module.fail_json( |
| 479 |
msg="When state is present either group_conf should be true or " |
| 480 |
"rules/aliases/ip_sets must be present but not both" |
| 481 |
) |
| 482 |
elif self.params.get("state") == "absent": |
| 483 |
if self.params.get("group_conf") != bool( |
| 484 |
(self.params.get("pos") is not None) or self.params.get("aliases") or self.params.get("ip_sets") |
| 485 |
): |
| 486 |
return True |
| 487 |
else: |
| 488 |
self.module.fail_json( |
| 489 |
msg="When state is absent either group_conf should be true or " |
| 490 |
"pos/aliases/ip_sets must be present but not both" |
| 491 |
) |
| 492 |
|
| 493 |
def run(self): # noqa: PLR0912 |
| 494 |
self.validate_params() |
| 495 |
|
| 496 |
state = self.params.get("state") |
| 497 |
update = self.params.get("update") |
| 498 |
level = self.params.get("level") |
| 499 |
aliases = self.params.get("aliases") |
| 500 |
rules = self.params.get("rules") |
| 501 |
ip_sets = self.params.get("ip_sets") |
| 502 |
group = self.params.get("group") |
| 503 |
group_conf = self.params.get("group_conf") |
| 504 |
|
| 505 |
if rules: |
| 506 |
for rule in rules: |
| 507 |
rule["icmp-type"] = rule.get("icmp_type") |
| 508 |
rule["enable"] = ansible_to_proxmox_bool(rule.get("enable")) |
| 509 |
del rule["icmp_type"] |
| 510 |
|
| 511 |
if level == "vm": |
| 512 |
vm = self.get_vm(vmid=self.params.get("vmid")) |
| 513 |
node = self.proxmox_api.nodes(vm["node"]) |
| 514 |
virt = node(vm["type"]) |
| 515 |
firewall_obj = virt(str(vm["vmid"])).firewall |
| 516 |
rules_obj = firewall_obj().rules |
| 517 |
|
| 518 |
elif level == "node": |
| 519 |
firewall_obj = self.proxmox_api.nodes(self.params.get("node")).firewall |
| 520 |
rules_obj = firewall_obj().rules |
| 521 |
|
| 522 |
elif level == "vnet": |
| 523 |
firewall_obj = self.proxmox_api.cluster().sdn().vnets(self.params.get("vnet")).firewall |
| 524 |
rules_obj = firewall_obj().rules |
| 525 |
|
| 526 |
elif level == "group": |
| 527 |
firewall_obj = None |
| 528 |
rules_obj = self.proxmox_api.cluster().firewall().groups(group) |
| 529 |
|
| 530 |
else: |
| 531 |
firewall_obj = self.proxmox_api.cluster().firewall |
| 532 |
rules_obj = firewall_obj().rules |
| 533 |
|
| 534 |
if state == "present": |
| 535 |
if group_conf: |
| 536 |
self.group_present(group=group, comment=self.params.get("comment")) |
| 537 |
if rules: |
| 538 |
self.fw_rules_present(rules_obj=rules_obj, rules=rules, update=update) |
| 539 |
if aliases: |
| 540 |
self.aliases_present(firewall_obj=firewall_obj, level=level, aliases=aliases, update=update) |
| 541 |
if ip_sets: |
| 542 |
self.ip_set_present(ip_sets=ip_sets, update=update, firewall_obj=firewall_obj) |
| 543 |
elif state == "absent": |
| 544 |
if self.params.get("pos") is not None: |
| 545 |
self.fw_rule_absent(rules_obj=rules_obj, pos=self.params.get("pos")) |
| 546 |
if group_conf: |
| 547 |
self.group_absent(group_name=group) |
| 548 |
if aliases: |
| 549 |
self.aliases_absent(firewall_obj=firewall_obj, aliases=aliases) |
| 550 |
if ip_sets: |
| 551 |
self.ip_set_absent(ip_sets=ip_sets, firewall_obj=firewall_obj) |
| 552 |
|
| 553 |
def ip_set_present(self, ip_sets, update, firewall_obj): |
| 554 |
self.reformat_ipset_cidrs(ip_sets) |
| 555 |
existing_ip_sets = self.get_ip_sets(firewall_obj) |
| 556 |
existing_ip_set_names = [x["name"] for x in existing_ip_sets] |
| 557 |
changed = False |
| 558 |
try: |
| 559 |
for ip_set in ip_sets: |
| 560 |
ip_set_name = ip_set["name"] |
| 561 |
if ip_set_name not in existing_ip_set_names: |
| 562 |
firewall_obj.ipset().post(name=ip_set.get("name"), comment=ip_set.get("comment")) |
| 563 |
cidrs_to_create = ip_set["cidrs"] |
| 564 |
cidrs_to_update = [] |
| 565 |
else: |
| 566 |
existing_ip_set_cidrs = [x["cidrs"] for x in existing_ip_sets if x["name"] == ip_set_name][0] |
| 567 |
cidrs_to_create, cidrs_to_update = compare_list_of_dicts( |
| 568 |
existing_list=existing_ip_set_cidrs, |
| 569 |
new_list=ip_set["cidrs"], |
| 570 |
uid="cidr", |
| 571 |
params_to_ignore=["digest"], |
| 572 |
) |
| 573 |
|
| 574 |
if cidrs_to_update and not update: |
| 575 |
self.module.fail_json(f"IP set {ip_set_name} needs to be updated but update is false.") |
| 576 |
|
| 577 |
for cidr in cidrs_to_update: |
| 578 |
changed = True |
| 579 |
proxmoxer_cidr_obj = getattr(firewall_obj.ipset(ip_set_name), cidr["cidr"]) |
| 580 |
proxmoxer_cidr_obj.put( |
| 581 |
cidr=cidr["cidr"], |
| 582 |
name=ip_set_name, |
| 583 |
comment=cidr["comment"], |
| 584 |
nomatch=ansible_to_proxmox_bool(cidr.get("nomatch")), |
| 585 |
) |
| 586 |
|
| 587 |
for cidr in cidrs_to_create: |
| 588 |
changed = True |
| 589 |
firewall_obj.ipset(ip_set_name).post( |
| 590 |
cidr=cidr.get("cidr"), |
| 591 |
nomatch=ansible_to_proxmox_bool(cidr.get("nomatch")), |
| 592 |
comment=cidr.get("comment"), |
| 593 |
) |
| 594 |
|
| 595 |
self.module.exit_json(changed=changed, msg="All ipsets present.") |
| 596 |
except Exception as e: |
| 597 |
self.module.fail_json(f"Failed to create/update ipsets - {e}.") |
| 598 |
|
| 599 |
def ip_set_absent(self, ip_sets, firewall_obj): |
| 600 |
self.reformat_ipset_cidrs(ip_sets) |
| 601 |
existing_ip_sets = self.get_ip_sets(firewall_obj) |
| 602 |
existing_ip_set_names = [x["name"] for x in existing_ip_sets] |
| 603 |
changed = False |
| 604 |
try: |
| 605 |
for ip_set in ip_sets: |
| 606 |
delete_ipset = False |
| 607 |
ip_set_name = ip_set["name"] |
| 608 |
|
| 609 |
if ip_set_name not in existing_ip_set_names: |
| 610 |
continue |
| 611 |
|
| 612 |
existing_ip_set_cidrs = [x["cidrs"] for x in existing_ip_sets if x["name"] == ip_set_name][0] |
| 613 |
|
| 614 |
if not ip_set.get("cidrs"): |
| 615 |
cidrs_to_delete = existing_ip_set_cidrs |
| 616 |
delete_ipset = True |
| 617 |
else: |
| 618 |
cidrs_to_delete = ip_set["cidrs"] |
| 619 |
|
| 620 |
for cidr in cidrs_to_delete: |
| 621 |
if cidr["cidr"] not in [x["cidr"] for x in existing_ip_set_cidrs]: |
| 622 |
continue |
| 623 |
cidr_obj = getattr(firewall_obj.ipset(ip_set_name), cidr["cidr"]) |
| 624 |
cidr_obj.delete() |
| 625 |
changed = True |
| 626 |
|
| 627 |
if delete_ipset: |
| 628 |
firewall_obj.ipset(ip_set_name).delete() |
| 629 |
|
| 630 |
self.module.exit_json(changed=changed, msg="Ipsets are absent.") |
| 631 |
|
| 632 |
except Exception as e: |
| 633 |
self.module.fail_json(f"Failed to delete ipsets {e}") |
| 634 |
|
| 635 |
def aliases_present(self, firewall_obj, level, aliases, update): |
| 636 |
if not firewall_obj or level not in ["cluster", "vm"]: |
| 637 |
self.module.fail_json(msg="Aliases can only be created at cluster or VM level") |
| 638 |
|
| 639 |
aliases_to_create, aliases_to_update = compare_list_of_dicts( |
| 640 |
existing_list=self.get_aliases(firewall_obj=firewall_obj), |
| 641 |
new_list=aliases, |
| 642 |
uid="name", |
| 643 |
params_to_ignore=["digest", "ipversion"], |
| 644 |
) |
| 645 |
|
| 646 |
if len(aliases_to_create) == 0 and len(aliases_to_update) == 0: |
| 647 |
self.module.exit_json(changed=False, msg="No need to create/update any aliases") |
| 648 |
elif len(aliases_to_update) > 0 and not update: |
| 649 |
self.module.fail_json( |
| 650 |
msg=f"Need to update aliases - {[x['name'] for x in aliases_to_update]} but update is false" |
| 651 |
) |
| 652 |
|
| 653 |
for alias in aliases_to_create: |
| 654 |
try: |
| 655 |
firewall_obj().aliases().post(**alias) |
| 656 |
except Exception as e: |
| 657 |
self.module.fail_json(msg=f"Failed to create Alias {alias['name']} - {e}") |
| 658 |
for alias in aliases_to_update: |
| 659 |
try: |
| 660 |
firewall_obj().aliases(alias["name"]).put(**alias) |
| 661 |
except Exception as e: |
| 662 |
self.module.fail_json(msg=f"Failed to update Alias {alias['name']} - {e}") |
| 663 |
|
| 664 |
self.module.exit_json(changed=True, msg="Aliases created/updated") |
| 665 |
|
| 666 |
def aliases_absent(self, firewall_obj, aliases): |
| 667 |
existing_aliases = set([x.get("name") for x in self.get_aliases(firewall_obj=firewall_obj)]) |
| 668 |
aliases = set([x.get("name") for x in aliases]) |
| 669 |
aliases_to_delete = list(existing_aliases.intersection(aliases)) |
| 670 |
|
| 671 |
if len(aliases_to_delete) == 0: |
| 672 |
self.module.exit_json(changed=False, msg="No need to delete any alias") |
| 673 |
for alias_name in aliases_to_delete: |
| 674 |
try: |
| 675 |
alias_obj = getattr(firewall_obj().aliases(), alias_name) |
| 676 |
alias_obj().delete() |
| 677 |
except Exception as e: |
| 678 |
self.module.fail_json(msg=f"Failed to delete alias {alias_name} - {e}") |
| 679 |
self.module.exit_json(changed=True, msg="Successfully deleted aliases") |
| 680 |
|
| 681 |
def group_present(self, group, comment=None): |
| 682 |
if group in self.get_groups(): |
| 683 |
self.module.exit_json(changed=False, group=group, msg=f"security group {group} already exists") |
| 684 |
try: |
| 685 |
self.proxmox_api.cluster().firewall().groups.post(group=group, comment=comment) |
| 686 |
self.module.exit_json(changed=True, group=group, msg=f"successfully created security group {group}") |
| 687 |
except Exception as e: |
| 688 |
self.module.fail_json(msg=f"Failed to create security group: {e}") |
| 689 |
|
| 690 |
def group_absent(self, group_name): |
| 691 |
if group_name not in self.get_groups(): |
| 692 |
self.module.exit_json( |
| 693 |
changed=False, group=group_name, msg=f"security group {group_name} already doesn't exists" |
| 694 |
) |
| 695 |
try: |
| 696 |
group = getattr(self.proxmox_api.cluster().firewall().groups(), group_name) |
| 697 |
group.delete() |
| 698 |
self.module.exit_json( |
| 699 |
changed=True, group=group_name, msg=f"successfully deleted security group {group_name}" |
| 700 |
) |
| 701 |
except Exception as e: |
| 702 |
self.module.fail_json(msg=f"Failed to delete security group {group_name}: {e}") |
| 703 |
|
| 704 |
def fw_rule_absent(self, rules_obj, pos): |
| 705 |
try: |
| 706 |
for item in self.get_fw_rules(rules_obj): |
| 707 |
if item.get("pos") == pos: |
| 708 |
break |
| 709 |
else: |
| 710 |
self.module.exit_json(changed=False, msg="Firewall rule already doesn't exist") |
| 711 |
rule_obj = getattr(rules_obj(), str(pos)) |
| 712 |
digest = rule_obj.get().get("digest") |
| 713 |
rule_obj.delete(pos=pos, digest=digest) |
| 714 |
|
| 715 |
self.module.exit_json(changed=True, msg="successfully deleted firewall rules") |
| 716 |
except Exception as e: |
| 717 |
self.module.fail_json(msg=f"Failed to delete firewall rule at pos {pos}: {e}") |
| 718 |
|
| 719 |
def fw_rules_present(self, rules_obj, rules, update): |
| 720 |
existing_rules = self.get_fw_rules(rules_obj=rules_obj) |
| 721 |
rules_to_create, rules_to_update = compare_list_of_dicts( |
| 722 |
existing_list=existing_rules, new_list=rules, uid="pos", params_to_ignore=["digest", "ipversion"] |
| 723 |
) |
| 724 |
|
| 725 |
if len(rules_to_create) == 0 and len(rules_to_update) == 0: |
| 726 |
self.module.exit_json(changed=False, msg="No need to create/update any rule") |
| 727 |
elif len(rules_to_update) > 0 and not update: |
| 728 |
self.module.fail_json( |
| 729 |
msg=f"Need to update rules at pos - {[x['pos'] for x in rules_to_update]} but update is false" |
| 730 |
) |
| 731 |
|
| 732 |
for rule in rules_to_update: |
| 733 |
try: |
| 734 |
rule_obj = getattr(rules_obj(), str(rule["pos"])) |
| 735 |
rule["digest"] = rule_obj.get().get("digest") # Avoids concurrent changes |
| 736 |
rule_obj.put(**rule) |
| 737 |
|
| 738 |
except Exception as e: |
| 739 |
self.module.fail_json(msg=f"Failed to update firewall rule at pos {rule['pos']}: {e}") |
| 740 |
for rule in rules_to_create: |
| 741 |
try: |
| 742 |
rules_obj().post(**rule) |
| 743 |
self.move_rule_to_correct_pos(rules_obj, rule) |
| 744 |
|
| 745 |
except Exception as e: |
| 746 |
self.module.fail_json(msg=f"Failed to create firewall rule {rule}: {e}") |
| 747 |
self.module.exit_json(changed=True, msg="successfully created/updated firewall rules") |
| 748 |
|
| 749 |
def reformat_ipset_cidrs(self, ip_sets): |
| 750 |
"""Normalise every CIDR entry in-place so it matches Proxmox format.""" |
| 751 |
|
| 752 |
def _normalise(cidr_entry: str) -> str: |
| 753 |
"""Return Proxmox-compatible string for a single CIDR.""" |
| 754 |
# check if we deal with an alias, an arbitrary string, or something which resembles an ip addres |
| 755 |
# which we need to validate, to keep idempotence |
| 756 |
bare_ip_match = re.compile(r"(^\d+\.\d+\.\d+\.\d+(/\d+)?$)|(^.*:(.*)?:.*(/\d+)?$)") |
| 757 |
if re.search(bare_ip_match, cidr_entry): |
| 758 |
# /32 and /128 → plain address |
| 759 |
if cidr_entry.endswith(("/32", "/128")): |
| 760 |
return str(ipaddress.ip_address(cidr_entry.split("/", maxsplit=1)[0])) |
| 761 |
# bare address → itself |
| 762 |
if "/" not in cidr_entry: |
| 763 |
return str(ipaddress.ip_address(cidr_entry)) |
| 764 |
# real network → compressed network string |
| 765 |
return str(ipaddress.ip_network(cidr_entry, strict=False)) |
| 766 |
return cidr_entry |
| 767 |
|
| 768 |
try: |
| 769 |
for ipset in ip_sets: |
| 770 |
for cidr in ipset.get("cidrs") or []: |
| 771 |
cidr["cidr"] = _normalise(cidr["cidr"]) |
| 772 |
except ValueError as exc: |
| 773 |
self.module.fail_json(msg=f"Invalid CIDR in ipset: {exc}") |
| 774 |
|
| 775 |
def move_rule_to_correct_pos(self, rules_obj, rule): |
| 776 |
################################################################################################## |
| 777 |
# TODO: Once below mentioned issue is fixed. Remove this workaround. # |
| 778 |
# Currently Proxmox API doesn't honor pos. All new rules are created at pos 0 # |
| 779 |
# https://forum.proxmox.com/threads/issue-when-creating-a-firewall-rule.135878/ # |
| 780 |
# Not able to find it in BUGZILLA. So maybe this is expected behaviour. # |
| 781 |
# To workaround this issue we will check rule at pos 0 and if needed move it to correct position # |
| 782 |
################################################################################################## |
| 783 |
|
| 784 |
pos = rule.get("pos") |
| 785 |
rule = {k: v for k, v in rule.items() if v is not None} |
| 786 |
if pos is not None and pos != 0: |
| 787 |
try: |
| 788 |
fw_rule_at0 = getattr(rules_obj(), str(0)) |
| 789 |
for ( |
| 790 |
param, |
| 791 |
value, |
| 792 |
) in fw_rule_at0.get().items(): |
| 793 |
if param in rule and param != "pos" and value != rule.get(param): |
| 794 |
self.module.warn( |
| 795 |
msg=f"Skipping workaround for rule placement. " |
| 796 |
f"Verify rule is at correct pos " |
| 797 |
f"provided - {rule} rule_at0 - {fw_rule_at0.get()}" |
| 798 |
) |
| 799 |
break # No need to move this. Potentially the issue is resolved. |
| 800 |
else: |
| 801 |
fw_rule_at0.put(moveto=(pos + 1)) # moveto moves rule to one position before the value |
| 802 |
except Exception as e: |
| 803 |
self.module.fail_json(msg=f"Rule created but failed to move it to correct pos. {e}") |
| 804 |
|
| 805 |
|
| 806 |
def main(): |
| 807 |
module = create_proxmox_module(module_args(), **module_options()) |
| 808 |
proxmox = ProxmoxFirewallAnsible(module) |
| 809 |
|
| 810 |
try: |
| 811 |
proxmox.run() |
| 812 |
except Exception as e: |
| 813 |
module.fail_json(msg=f"An error occurred: {e}") |
| 814 |
|
| 815 |
|
| 816 |
if __name__ == "__main__": |
| 817 |
main() |