| 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_subnet |
| 10 |
short_description: Create/Update/Delete subnets from SDN |
| 11 |
version_added: "1.4.0" |
| 12 |
description: |
| 13 |
- Create, update, or delete subnets in Proxmox SDN. |
| 14 |
author: 'Jana Hoch <[email protected]> (!UNKNOWN)' |
| 15 |
attributes: |
| 16 |
check_mode: |
| 17 |
support: none |
| 18 |
diff_mode: |
| 19 |
support: none |
| 20 |
options: |
| 21 |
state: |
| 22 |
description: |
| 23 |
- Desired state of the subnet configuration. |
| 24 |
type: str |
| 25 |
choices: ['present', 'absent'] |
| 26 |
default: present |
| 27 |
update: |
| 28 |
description: |
| 29 |
- If O(state=present) then it will update the subnet if needed. |
| 30 |
type: bool |
| 31 |
default: True |
| 32 |
dhcp_range_update_mode: |
| 33 |
description: |
| 34 |
- Only applicable for O(state=present) and it will honor and only make changes when O(update=true) |
| 35 |
- If set to append and new dhcp_range passed it will just append to existing ranges. |
| 36 |
- And If no dhcp_range passed and there are existing ranges it will just ignore existing ranges and only update other params if needed |
| 37 |
- If set to overwrite and new dhcp_range passed it will overwrite existing ranges. |
| 38 |
- If no dhcp_range passed and there are existing ranges it will delete all dhcp_ranges |
| 39 |
type: str |
| 40 |
default: append |
| 41 |
choices: ['append', 'overwrite'] |
| 42 |
subnet: |
| 43 |
description: |
| 44 |
- Subnet CIDR. |
| 45 |
type: str |
| 46 |
required: true |
| 47 |
vnet: |
| 48 |
description: |
| 49 |
- The virtual network to which the subnet belongs. |
| 50 |
type: str |
| 51 |
required: true |
| 52 |
zone: |
| 53 |
description: |
| 54 |
- Vnet Zone. |
| 55 |
type: str |
| 56 |
dhcp_dns_server: |
| 57 |
description: |
| 58 |
- IP address for the DNS server. |
| 59 |
type: str |
| 60 |
dhcp_range: |
| 61 |
description: |
| 62 |
- Range of IP addresses for DHCP. |
| 63 |
type: list |
| 64 |
elements: dict |
| 65 |
suboptions: |
| 66 |
start: |
| 67 |
description: |
| 68 |
- Starting IP address of the DHCP range. |
| 69 |
type: str |
| 70 |
required: true |
| 71 |
end: |
| 72 |
description: |
| 73 |
- Ending IP address of the DHCP range. |
| 74 |
type: str |
| 75 |
required: true |
| 76 |
dnszoneprefix: |
| 77 |
description: |
| 78 |
- Prefix for the DNS zone. |
| 79 |
type: str |
| 80 |
gateway: |
| 81 |
description: |
| 82 |
- Subnet Gateway. Will be assign on vnet for layer3 zones. |
| 83 |
type: str |
| 84 |
lock_token: |
| 85 |
description: |
| 86 |
- the token for unlocking the global SDN configuration. |
| 87 |
type: str |
| 88 |
snat: |
| 89 |
description: |
| 90 |
- Enable Source NAT for the subnet. |
| 91 |
type: bool |
| 92 |
default: False |
| 93 |
delete: |
| 94 |
description: |
| 95 |
- A list of settings you want to delete. |
| 96 |
type: str |
| 97 |
extends_documentation_fragment: |
| 98 |
- community.proxmox.proxmox.actiongroup_proxmox |
| 99 |
- community.proxmox.proxmox.documentation |
| 100 |
- community.proxmox.attributes |
| 101 |
""" |
| 102 |
|
| 103 |
EXAMPLES = r""" |
| 104 |
- name: Create a subnet |
| 105 |
community.proxmox.proxmox_subnet: |
| 106 |
vnet: test |
| 107 |
subnet: 10.10.2.0/24 |
| 108 |
zone: ans1 |
| 109 |
state: present |
| 110 |
dhcp_range: |
| 111 |
- start: 10.10.2.5 |
| 112 |
end: 10.10.2.50 |
| 113 |
- start: 10.10.2.100 |
| 114 |
end: 10.10.2.150 |
| 115 |
snat: true |
| 116 |
|
| 117 |
- name: Delete a subnet |
| 118 |
community.proxmox.proxmox_subnet: |
| 119 |
vnet: test |
| 120 |
subnet: 10.10.2.0/24 |
| 121 |
zone: ans1 |
| 122 |
state: absent |
| 123 |
""" |
| 124 |
|
| 125 |
RETURN = r""" |
| 126 |
subnet: |
| 127 |
description: |
| 128 |
- Subnet ID which was created/updated/deleted |
| 129 |
returned: on success |
| 130 |
type: str |
| 131 |
sample: |
| 132 |
ans1-10.10.2.0-24 |
| 133 |
""" |
| 134 |
|
| 135 |
import copy |
| 136 |
from ipaddress import IPv4Address |
| 137 |
|
| 138 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox import ( |
| 139 |
ansible_to_proxmox_bool, |
| 140 |
compare_list_of_dicts, |
| 141 |
create_proxmox_module, |
| 142 |
) |
| 143 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox_sdn import ProxmoxSdnAnsible |
| 144 |
|
| 145 |
|
| 146 |
def get_dhcp_range(dhcp_range=None): |
| 147 |
if not dhcp_range: |
| 148 |
return None |
| 149 |
|
| 150 |
def extract(item): |
| 151 |
start = item.get("start-address") or item.get("start") |
| 152 |
end = item.get("end-address") or item.get("end") |
| 153 |
return f"start-address={start},end-address={end}" |
| 154 |
|
| 155 |
return [extract(x) for x in dhcp_range] |
| 156 |
|
| 157 |
|
| 158 |
def compare_dhcp_ranges(existing_ranges, new_ranges): |
| 159 |
def to_tuple(r): |
| 160 |
return int(IPv4Address(r["start-address"])), int(IPv4Address(r["end-address"])) |
| 161 |
|
| 162 |
existing_intervals = [to_tuple(r) for r in existing_ranges] |
| 163 |
|
| 164 |
new_dhcp_ranges = [] |
| 165 |
partial_overlap = False |
| 166 |
|
| 167 |
for dhcp_range in new_ranges: |
| 168 |
tuple_dhcp_range = to_tuple(dhcp_range) |
| 169 |
if tuple_dhcp_range not in existing_intervals: |
| 170 |
new_dhcp_ranges.append(dhcp_range) |
| 171 |
for start, end in existing_intervals: |
| 172 |
ranges_overlap = not (tuple_dhcp_range[1] < start or tuple_dhcp_range[0] > end) |
| 173 |
if ranges_overlap and tuple_dhcp_range != (start, end): |
| 174 |
partial_overlap = True |
| 175 |
return new_dhcp_ranges, partial_overlap |
| 176 |
|
| 177 |
|
| 178 |
def module_args(): |
| 179 |
return dict( |
| 180 |
state=dict(type="str", choices=["present", "absent"], default="present", required=False), |
| 181 |
update=dict(type="bool", default=True), |
| 182 |
subnet=dict(type="str", required=True), |
| 183 |
vnet=dict(type="str", required=True), |
| 184 |
zone=dict(type="str", required=False), |
| 185 |
dhcp_dns_server=dict(type="str", required=False), |
| 186 |
dhcp_range_update_mode=dict(type="str", choices=["append", "overwrite"], default="append"), |
| 187 |
dhcp_range=dict( |
| 188 |
type="list", |
| 189 |
elements="dict", |
| 190 |
required=False, |
| 191 |
options=dict(start=dict(type="str", required=True), end=dict(type="str", required=True)), |
| 192 |
), |
| 193 |
dnszoneprefix=dict(type="str", required=False), |
| 194 |
gateway=dict(type="str", required=False), |
| 195 |
lock_token=dict(type="str", required=False, no_log=False), |
| 196 |
snat=dict(type="bool", default=False, required=False), |
| 197 |
delete=dict(type="str", required=False), |
| 198 |
) |
| 199 |
|
| 200 |
|
| 201 |
def module_options(): |
| 202 |
return dict( |
| 203 |
supports_check_mode=False, |
| 204 |
required_if=[ |
| 205 |
("state", "present", ["subnet", "vnet", "zone"]), |
| 206 |
("state", "absent", ["zone", "vnet", "subnet"]), |
| 207 |
], |
| 208 |
) |
| 209 |
|
| 210 |
|
| 211 |
class ProxmoxSubnetAnsible(ProxmoxSdnAnsible): |
| 212 |
def __init__(self, module): |
| 213 |
super().__init__(module) |
| 214 |
self.params = module.params |
| 215 |
|
| 216 |
def run(self): |
| 217 |
state = self.params.get("state") |
| 218 |
|
| 219 |
subnet_params = { |
| 220 |
"subnet": self.params.get("subnet"), |
| 221 |
"type": "subnet", |
| 222 |
"vnet": self.params.get("vnet"), |
| 223 |
"dhcp-dns-server": self.params.get("dhcp_dns_server"), |
| 224 |
"dhcp-range": get_dhcp_range(dhcp_range=self.params.get("dhcp_range")), |
| 225 |
"dnszoneprefix": self.params.get("dnszoneprefix"), |
| 226 |
"gateway": self.params.get("gateway"), |
| 227 |
"lock-token": None, |
| 228 |
"snat": ansible_to_proxmox_bool(self.params.get("snat")), |
| 229 |
} |
| 230 |
|
| 231 |
if state == "present": |
| 232 |
self.subnet_present(**subnet_params) |
| 233 |
elif state == "absent": |
| 234 |
self.subnet_absent(**subnet_params) |
| 235 |
|
| 236 |
def get_subnets(self, vnet_name): |
| 237 |
try: |
| 238 |
return self.proxmox_api.cluster().sdn().vnets(vnet_name).subnets().get() |
| 239 |
except Exception as e: |
| 240 |
self.module.fail_json(f"Failed to retrieve subnets {e}") |
| 241 |
|
| 242 |
def update_subnet(self, **subnet_params): # noqa: PLR0912, PLR0915 |
| 243 |
new_subnet = copy.deepcopy(subnet_params) |
| 244 |
subnet_id = f"{self.params['zone']}-{new_subnet['subnet'].replace('/', '-')}" |
| 245 |
vnet_name = new_subnet["vnet"] |
| 246 |
dhcp_range_update_mode = self.params.get("dhcp_range_update_mode") |
| 247 |
|
| 248 |
new_subnet["cidr"] = new_subnet["subnet"] |
| 249 |
new_subnet["network"] = new_subnet["subnet"].split("/")[0] |
| 250 |
new_subnet["mask"] = new_subnet["subnet"].split("/")[1] |
| 251 |
new_subnet["zone"] = self.params.get("zone") |
| 252 |
new_subnet["id"] = subnet_id |
| 253 |
new_subnet["subnet"] = subnet_id |
| 254 |
|
| 255 |
subnet_params["delete"] = self.params.get("delete") |
| 256 |
|
| 257 |
existing_subnets = self.get_subnets(vnet_name) |
| 258 |
|
| 259 |
# Check for subnet params other than dhcp-range |
| 260 |
x, subnet_update = compare_list_of_dicts( |
| 261 |
existing_list=existing_subnets, |
| 262 |
new_list=[new_subnet], |
| 263 |
uid="id", |
| 264 |
params_to_ignore=["digest", "dhcp-range", "lock-token"], |
| 265 |
) |
| 266 |
|
| 267 |
existing_subnet = [x for x in existing_subnets if x["subnet"] == subnet_id][0] |
| 268 |
|
| 269 |
# Check dhcp-range |
| 270 |
update_dhcp = False |
| 271 |
if self.params.get("dhcp_range"): |
| 272 |
new_dhcp_range = [ |
| 273 |
{"start-address": d.get("start"), "end-address": d.get("end")} for d in self.params.get("dhcp_range") |
| 274 |
] |
| 275 |
new_dhcp, partial_overlap = compare_dhcp_ranges( |
| 276 |
existing_ranges=existing_subnet["dhcp-range"], new_ranges=new_dhcp_range |
| 277 |
) |
| 278 |
|
| 279 |
if dhcp_range_update_mode == "append": |
| 280 |
if partial_overlap: |
| 281 |
self.module.fail_json(msg="There are partially overlapping DHCP ranges. this is not allowed.") |
| 282 |
|
| 283 |
if len(new_dhcp) > 0: |
| 284 |
update_dhcp = True |
| 285 |
new_dhcp.extend(existing_subnet["dhcp-range"]) # By Default API overwrites DHCP Range |
| 286 |
subnet_params["dhcp-range"] = get_dhcp_range(new_dhcp) |
| 287 |
|
| 288 |
elif dhcp_range_update_mode == "overwrite" and new_dhcp: |
| 289 |
update_dhcp = True |
| 290 |
|
| 291 |
elif not self.params.get("dhcp_range") and existing_subnet["dhcp-range"]: |
| 292 |
if dhcp_range_update_mode == "append": |
| 293 |
self.module.warn( |
| 294 |
"dhcp_range_update_mode is set to append, but you didn't provide any DHCP ranges for the subnet. " |
| 295 |
"Existing ranges will be ignored." |
| 296 |
) |
| 297 |
|
| 298 |
elif dhcp_range_update_mode == "overwrite": |
| 299 |
update_dhcp = True |
| 300 |
self.module.warn( |
| 301 |
"dhcp_range_update_mode is set to overwrite, but no DHCP ranges were provided for the subnet. " |
| 302 |
"All existing DHCP ranges will be deleted." |
| 303 |
) |
| 304 |
if self.params.get("delete"): |
| 305 |
subnet_params["delete"] = f"{subnet_params['delete']},dhcp-range" |
| 306 |
else: |
| 307 |
subnet_params["delete"] = "dhcp-range" |
| 308 |
|
| 309 |
if subnet_update or update_dhcp: |
| 310 |
self.module.warn(f"{subnet_params}, {update_dhcp}") |
| 311 |
if self.params.get("update"): |
| 312 |
try: |
| 313 |
subnet_params["lock-token"] = self.get_global_sdn_lock() |
| 314 |
subnet = getattr(self.proxmox_api.cluster().sdn().vnets(vnet_name).subnets(), subnet_id) |
| 315 |
subnet_params["digest"] = subnet.get()["digest"] |
| 316 |
del subnet_params["type"] |
| 317 |
del subnet_params["subnet"] |
| 318 |
|
| 319 |
if not self.is_lock_and_rollback_supported: |
| 320 |
del subnet_params["lock-token"] |
| 321 |
subnet.put(**subnet_params) |
| 322 |
self.apply_sdn_changes_and_release_lock(lock=subnet_params.get("lock-token")) |
| 323 |
self.module.exit_json(changed=True, subnet=subnet_id, msg=f"Updated subnet {subnet_id}") |
| 324 |
except Exception as e: |
| 325 |
if self.is_lock_and_rollback_supported: |
| 326 |
self.rollback_sdn_changes_and_release_lock(lock=subnet_params["lock-token"]) |
| 327 |
self.module.fail_json(msg=f"Failed to update subnet. Rolling back all changes : {e}") |
| 328 |
else: |
| 329 |
self.module.fail_json(msg=f"Failed to update subnet. Rollback not supported : {e}") |
| 330 |
else: |
| 331 |
self.module.fail_json(msg=f"Subnet {subnet_id} needs to be updated but update is false.") |
| 332 |
else: |
| 333 |
self.module.exit_json( |
| 334 |
changed=False, subnet=subnet_id, msg=f"subnet {subnet_id} is already present with correct parameters." |
| 335 |
) |
| 336 |
|
| 337 |
def subnet_present(self, **subnet_params): |
| 338 |
vnet_name = subnet_params["vnet"] |
| 339 |
subnet_cidr = subnet_params["subnet"] |
| 340 |
subnet_id = f"{self.params['zone']}-{subnet_params['subnet'].replace('/', '-')}" |
| 341 |
|
| 342 |
try: |
| 343 |
existing_subnets = self.get_subnets(vnet_name) |
| 344 |
|
| 345 |
# Check if subnet already present |
| 346 |
if subnet_id in [x["subnet"] for x in existing_subnets]: |
| 347 |
if not self.is_lock_and_rollback_supported: |
| 348 |
del subnet_params["lock-token"] |
| 349 |
self.update_subnet(**subnet_params) |
| 350 |
else: |
| 351 |
subnet_params["lock-token"] = self.get_global_sdn_lock() |
| 352 |
if not self.is_lock_and_rollback_supported: |
| 353 |
del subnet_params["lock-token"] |
| 354 |
self.proxmox_api.cluster().sdn().vnets(vnet_name).subnets().post(**subnet_params) |
| 355 |
self.apply_sdn_changes_and_release_lock(lock=subnet_params.get("lock-token")) |
| 356 |
self.module.exit_json(changed=True, subnet=subnet_id, msg=f"Created new subnet {subnet_cidr}") |
| 357 |
except Exception as e: |
| 358 |
if self.is_lock_and_rollback_supported: |
| 359 |
self.rollback_sdn_changes_and_release_lock(lock=subnet_params["lock-token"]) |
| 360 |
self.module.fail_json(msg=f"Failed to create subnet. Rolling back all changes : {e}") |
| 361 |
else: |
| 362 |
self.module.fail_json(msg=f"Failed to create subnet. Rollback not supported : {e}") |
| 363 |
|
| 364 |
def subnet_absent(self, **subnet_params): |
| 365 |
vnet_name = subnet_params["vnet"] |
| 366 |
subnet_id = f"{self.params['zone']}-{subnet_params['subnet'].replace('/', '-')}" |
| 367 |
|
| 368 |
params = {"subnet": subnet_id, "vnet": vnet_name, "lock-token": None} |
| 369 |
|
| 370 |
existing_subnets = self.get_subnets(vnet_name) |
| 371 |
try: |
| 372 |
# Check if subnet already present |
| 373 |
if subnet_id in [x["subnet"] for x in existing_subnets]: |
| 374 |
params["lock-token"] = self.get_global_sdn_lock() |
| 375 |
if not self.is_lock_and_rollback_supported: |
| 376 |
del params["lock-token"] |
| 377 |
self.proxmox_api.cluster().sdn().vnets(vnet_name).subnets(subnet_id).delete(**params) |
| 378 |
self.apply_sdn_changes_and_release_lock(lock=params.get("lock-token")) |
| 379 |
self.module.exit_json(changed=True, subnet=subnet_id, msg=f"Deleted subnet {subnet_id}") |
| 380 |
else: |
| 381 |
self.module.exit_json(changed=False, subnet=subnet_id, msg=f"subnet {subnet_id} already not present.") |
| 382 |
except Exception as e: |
| 383 |
if self.is_lock_and_rollback_supported: |
| 384 |
self.rollback_sdn_changes_and_release_lock(lock=params["lock-token"]) |
| 385 |
self.module.fail_json(msg=f"Failed to delete subnet. Rolling back all changes. : {e}") |
| 386 |
else: |
| 387 |
self.module.fail_json(msg=f"Failed to delete subnet. Rollback not supported. : {e}") |
| 388 |
|
| 389 |
|
| 390 |
def main(): |
| 391 |
module = create_proxmox_module(module_args(), **module_options()) |
| 392 |
proxmox = ProxmoxSubnetAnsible(module) |
| 393 |
|
| 394 |
try: |
| 395 |
proxmox.run() |
| 396 |
except Exception as e: |
| 397 |
module.fail_json(msg=f"An error occurred: {e}") |
| 398 |
|
| 399 |
|
| 400 |
if __name__ == "__main__": |
| 401 |
main() |