Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_cluster_firewall.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2026, Clément Cruau (@PendaGTP) <[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_cluster_firewall
10 short_description: Cluster-level firewall options management for Proxmox VE cluster
11 version_added: "2.0.0"
12 author:
13 - Clément Cruau (@PendaGTP)
14 description:
15 - Manage firewall options at the cluster level in Proxmox VE.
16 - Enable or disable the firewall cluster-wide, set default policies, ebtables, and log ratelimiting.
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 state:
24 description:
25 - Enable or disable the firewall cluster-wide.
26 choices:
27 - enabled
28 - disabled
29 type: str
30 default: disabled
31 ebtables:
32 description:
33 - Enable ebtables rules cluster-wide.
34 type: bool
35 default: true
36 input_policy:
37 description:
38 - Default policy for incoming traffic.
39 choices:
40 - ACCEPT
41 - REJECT
42 - DROP
43 type: str
44 default: DROP
45 output_policy:
46 description:
47 - Default policy for outgoing traffic.
48 choices:
49 - ACCEPT
50 - REJECT
51 - DROP
52 type: str
53 default: ACCEPT
54 forward_policy:
55 description:
56 - Default policy for forwarded traffic.
57 choices:
58 - ACCEPT
59 - DROP
60 type: str
61 default: ACCEPT
62 log_ratelimit:
63 description:
64 - Log ratelimiting settings.
65 type: dict
66 suboptions:
67 enabled:
68 description:
69 - Enable or disable log ratelimiting.
70 type: bool
71 default: true
72 burst:
73 description:
74 - Initial burst of packages which will always get logged before the rate is applied.
75 type: int
76 default: 5
77 rate:
78 description:
79 - Frequency with which the burst bucket gets refilled.
80 - Must match the pattern C([1-9][0-9]*/(second|minute|hour|day)), e.g. C(1/second).
81 type: str
82 default: 1/second
83
84 seealso:
85 - name: Proxmox VE Firewall configuration
86 description: Complete reference of Proxmox VE Firewall
87 link: https://pve.proxmox.com/pve-docs/chapter-pve-firewall.html
88 - name: Proxmox VE cluster-wide configuration
89 description: Complete reference of Proxmox VE Firewall
90 link: https://pve.proxmox.com/pve-docs/chapter-pve-firewall.html#pve_firewall_cluster_wide_setup
91
92 extends_documentation_fragment:
93 - community.proxmox.proxmox.actiongroup_proxmox
94 - community.proxmox.proxmox.documentation
95 - community.proxmox.attributes
96 """
97
98 EXAMPLES = r"""
99 - name: Set cluster-wide firewall options
100 community.proxmox.proxmox_cluster_firewall:
101 state: enabled
102 ebtables: true
103 input_policy: DROP
104 output_policy: ACCEPT
105 forward_policy: ACCEPT
106 log_ratelimit:
107 enabled: false
108 burst: 10
109 rate: 5/second
110
111 - name: Block ingress and allow egress traffic
112 community.proxmox.proxmox_cluster_firewall:
113 state: enabled
114 ebtables: true
115 input_policy: DROP
116 output_policy: ACCEPT
117 forward_policy: ACCEPT
118
119 - name: Set cluster-wide firewall ratelimiting options
120 community.proxmox.proxmox_cluster_firewall:
121 state: enabled
122 ebtables: true
123 log_ratelimit:
124 enabled: false
125 burst: 10
126 rate: 5/second
127
128 - name: Disable cluster-wide firewall
129 community.proxmox.proxmox_cluster_firewall:
130 state: disabled
131 """
132
133 RETURN = r"""
134 enabled:
135 description: Whether the firewall is enabled cluster-wide.
136 returned: on success
137 type: bool
138 sample: true
139 ebtables:
140 description: Whether ebtables is enabled cluster-wide.
141 returned: on success
142 type: bool
143 sample: false
144 input_policy:
145 description: Default policy for incoming traffic.
146 returned: on success
147 type: str
148 sample: DROP
149 output_policy:
150 description: Default policy for outgoing traffic.
151 returned: on success
152 type: str
153 sample: ACCEPT
154 forward_policy:
155 description: Default policy for forwarded traffic.
156 returned: on success
157 type: str
158 sample: ACCEPT
159 log_ratelimit:
160 description: Log ratelimiting settings (when present in cluster options).
161 returned: on success
162 type: dict
163 sample: {"enabled": true, "burst": 5, "rate": "1/second"}
164 msg:
165 description: A short message on what the module did.
166 returned: always
167 type: str
168 sample: "Cluster firewall options updated"
169 """
170
171 import re
172
173 from ansible.module_utils.common.text.converters import to_native
174
175 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
176 ProxmoxAnsible,
177 ansible_to_proxmox_bool,
178 create_proxmox_module,
179 proxmox_to_ansible_bool,
180 )
181
182 LOG_RATELIMIT_RATE_PATTERN = re.compile(r"^[1-9][0-9]*/(second|minute|hour|day)$")
183
184
185 def _validate_log_ratelimit_rate(rate):
186 if rate is None:
187 return True
188 return bool(LOG_RATELIMIT_RATE_PATTERN.match(rate))
189
190
191 def _parse_log_ratelimit_string(value):
192 """Parse Proxmox log_ratelimit string (e.g. enable=1,burst=5,rate=1/second) into a dict."""
193 if not value or not isinstance(value, str):
194 return None
195 result = {}
196 for raw_part in value.strip().split(","):
197 part = raw_part.strip()
198 if "=" not in part:
199 continue
200 key, val = part.split("=", 1)
201 key = key.strip().lower()
202 val = val.strip()
203 if key == "enable":
204 result["enabled"] = proxmox_to_ansible_bool(1 if val == "1" else 0)
205 elif key == "burst":
206 try:
207 result["burst"] = int(val)
208 except ValueError:
209 pass
210 elif key == "rate":
211 result["rate"] = val
212 return result
213
214
215 def _build_log_ratelimit_string(enabled, burst, rate):
216 """Build a Proxmox log_ratelimit string (e.g. enable=1,burst=5,rate=1/second) from parts."""
217 parts = []
218 if enabled is not None:
219 parts.append(f"enable={ansible_to_proxmox_bool(enabled)}")
220 if burst is not None:
221 parts.append(f"burst={int(burst)}")
222 if rate is not None:
223 parts.append(f"rate={rate}")
224 return ",".join(parts) if parts else None
225
226
227 def module_args():
228 return dict(
229 state=dict(choices=["enabled", "disabled"], default="disabled"),
230 ebtables=dict(type="bool", default=True),
231 input_policy=dict(type="str", choices=["ACCEPT", "REJECT", "DROP"], default="DROP"),
232 output_policy=dict(type="str", choices=["ACCEPT", "REJECT", "DROP"], default="ACCEPT"),
233 forward_policy=dict(type="str", choices=["ACCEPT", "DROP"], default="ACCEPT"),
234 log_ratelimit=dict(
235 type="dict",
236 options=dict(
237 enabled=dict(type="bool", default=True),
238 burst=dict(type="int", default=5),
239 rate=dict(type="str", default="1/second"),
240 ),
241 ),
242 )
243
244
245 def module_options():
246 return {}
247
248
249 class ProxmoxClusterFirewallAnsible(ProxmoxAnsible):
250 def __init__(self, module):
251 super().__init__(module)
252 self.params = module.params
253
254 def run(self):
255 self._apply()
256
257 def validate_params(self):
258 lr = self.params.get("log_ratelimit")
259 if not lr or lr.get("rate") is None:
260 return
261 lr_rate = lr["rate"]
262 if not _validate_log_ratelimit_rate(lr_rate):
263 self.module.fail_json(
264 msg="log_ratelimit.rate must be a valid rate expression, e.g. '1/second'",
265 rate=lr_rate,
266 )
267
268 def _get_fw_options(self):
269 try:
270 return self.proxmox_api.cluster().firewall().options.get()
271 except Exception as e:
272 self.module.fail_json(msg=f"Failed to retrieve cluster firewall options: {to_native(e)}")
273
274 def _current_to_ansible(self, current):
275 """Translate a raw Proxmox API options dict into Ansible-format keys and types."""
276 if not current:
277 return {}
278
279 out = {}
280 if "enable" in current:
281 out["enabled"] = proxmox_to_ansible_bool(current["enable"])
282 if "ebtables" in current:
283 out["ebtables"] = proxmox_to_ansible_bool(current["ebtables"])
284 if "policy_in" in current:
285 out["input_policy"] = current["policy_in"]
286 if "policy_out" in current:
287 out["output_policy"] = current["policy_out"]
288 if "policy_forward" in current:
289 out["forward_policy"] = current["policy_forward"]
290 if "log_ratelimit" in current and current["log_ratelimit"]:
291 out["log_ratelimit"] = _parse_log_ratelimit_string(current["log_ratelimit"])
292
293 return out
294
295 def _desired_ansible(self):
296 """Build the desired state as an Ansible-format dict."""
297 out = {
298 "enabled": self.params["state"] == "enabled",
299 "ebtables": self.params["ebtables"],
300 "input_policy": self.params["input_policy"],
301 "output_policy": self.params["output_policy"],
302 "forward_policy": self.params["forward_policy"],
303 }
304 lr = self.params.get("log_ratelimit")
305 if lr:
306 out["log_ratelimit"] = {
307 "enabled": lr["enabled"],
308 "burst": lr["burst"],
309 "rate": lr["rate"],
310 }
311 return out
312
313 def _ansible_to_api_payload(self, desired):
314 """Convert an Ansible-format desired dict to the API payload for PUT."""
315 payload = {
316 "enable": ansible_to_proxmox_bool(desired["enabled"]),
317 "ebtables": ansible_to_proxmox_bool(desired["ebtables"]),
318 "policy_in": desired["input_policy"],
319 "policy_out": desired["output_policy"],
320 "policy_forward": desired["forward_policy"],
321 }
322 lr = desired.get("log_ratelimit")
323 if lr:
324 log_ratelimit_str = _build_log_ratelimit_string(
325 lr.get("enabled"),
326 lr.get("burst"),
327 lr.get("rate"),
328 )
329 if log_ratelimit_str:
330 payload["log_ratelimit"] = log_ratelimit_str
331 return payload
332
333 def _fw_options_differ(self, current_ansible, desired_ansible):
334 return any(current_ansible.get(key) != desired_value for key, desired_value in desired_ansible.items())
335
336 def _apply(self):
337 current = self._get_fw_options()
338 current_ansible = self._current_to_ansible(current)
339 desired = self._desired_ansible()
340
341 if not self._fw_options_differ(current_ansible, desired):
342 self.module.exit_json(
343 changed=False,
344 msg="Cluster firewall options already match desired state",
345 **current_ansible,
346 )
347
348 if self.module.check_mode:
349 self.module.exit_json(
350 changed=True,
351 msg="Cluster firewall options would be updated",
352 **{**current_ansible, **desired},
353 )
354
355 payload = self._ansible_to_api_payload(desired)
356 try:
357 self.proxmox_api.cluster().firewall().options.put(**payload)
358 except Exception as e:
359 self.module.fail_json(msg=f"Failed to set cluster firewall options: {to_native(e)}")
360
361 updated = self._get_fw_options()
362 result = self._current_to_ansible(updated)
363 msg = "Cluster firewall options updated"
364 self.module.exit_json(changed=True, msg=msg, **result)
365
366
367 def main():
368 module = create_proxmox_module(module_args(), **module_options())
369 proxmox = ProxmoxClusterFirewallAnsible(module)
370 proxmox.validate_params()
371
372 try:
373 proxmox.run()
374 except Exception as e:
375 module.fail_json(msg=f"An error occurred: {to_native(e)}")
376
377
378 if __name__ == "__main__":
379 main()