Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_acme_plugin_dns.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_acme_plugin_dns
10 short_description: Manage ACME DNS plugins on a Proxmox VE.
11 version_added: "2.0.0"
12 author:
13 - Clément Cruau (@PendaGTP)
14 description:
15 - Create, update or delete a DNS challenge ACME plugin configuration.
16 - Requires C(root@pam) authentication.
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 state:
24 description:
25 - Desired state of the ACME DNS plugin.
26 type: str
27 choices:
28 - present
29 - absent
30 default: present
31 name:
32 description:
33 - The ACME plugin instance identifier.
34 type: str
35 required: true
36 aliases: ["id"]
37 plugin:
38 description:
39 - DNS API implementation name (for example V(cf) for Cloudflare or V(googledomains) for Google Cloud DNS).
40 type: str
41 data:
42 description:
43 - DNS plugin settings as string key/value pairs.
44 type: dict
45 disable:
46 description:
47 - Disable this plugin configuration.
48 type: bool
49 default: false
50 validation_delay:
51 description:
52 - Extra delay in seconds to wait before requesting validation. Allows to cope with a long TTL of DNS records (0 - 172800).
53 type: int
54 default: 30
55
56 seealso:
57 - name: ACME DNS API Challenge Plugin
58 description: ACME DNS API Challenge Plugin (Proxmox documentation)
59 link: https://pve.proxmox.com/pve-docs/chapter-sysadmin.html#sysadmin_certs_acme_dns_challenge
60
61 extends_documentation_fragment:
62 - community.proxmox.proxmox.actiongroup_proxmox
63 - community.proxmox.proxmox.documentation
64 - community.proxmox.attributes
65 """
66
67 EXAMPLES = r"""
68 - name: Configure ACME Plugin DNS (Cloudflare)
69 community.proxmox.proxmox_acme_plugin_dns:
70 name: cloudflare
71 plugin: cf
72 data:
73 CF_Account_ID: example
74 CF_Token: example
75
76 - name: Remove ACME DNS plugin
77 community.proxmox.proxmox_acme_plugin_dns:
78 name: cloudflare
79 state: absent
80 """
81
82 RETURN = r"""
83 name:
84 description: ACME plugin instance identifier.
85 returned: on success
86 type: str
87 plugin:
88 description: DNS API implementation name.
89 returned: on success when O(state=present)
90 type: str
91 data:
92 description: DNS plugin settings as string key/value pairs (value are masked).
93 returned: on success when O(state=present)
94 type: dict
95 disable:
96 description: Whether the plugin configuration is disabled.
97 returned: on success when O(state=present)
98 type: bool
99 validation_delay:
100 description: Validation delay in seconds.
101 returned: on success when O(state=present)
102 type: int
103 digest:
104 description: Digest of the plugin configuration.
105 returned: on success when O(state=present)
106 type: str
107 msg:
108 description: Short description of the action taken.
109 returned: always
110 type: str
111 """
112
113 import base64
114
115 from ansible.module_utils.common.text.converters import to_native
116
117 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
118 ProxmoxAnsible,
119 ansible_to_proxmox_bool,
120 create_proxmox_module,
121 )
122 from ansible_collections.community.proxmox.plugins.module_utils.proxmox_acme_plugin import (
123 acme_plugin_normalize_data_dict,
124 acme_plugin_to_ansible_result,
125 )
126
127 MIN_VALIDATION_DELAY = 0
128 MAX_VALIDATION_DELAY = 172800
129
130
131 def _data_to_api(data):
132 """Encode plugin data dict to the base64 string expected by the API."""
133 norm = acme_plugin_normalize_data_dict(data)
134 out = "\n".join(f"{k}={norm[k]}" for k in sorted(norm))
135 return base64.b64encode(out.encode("utf-8")).decode("ascii")
136
137
138 def module_args():
139 return dict(
140 state=dict(choices=["present", "absent"], default="present"),
141 name=dict(type="str", required=True, aliases=["id"]),
142 plugin=dict(type="str"),
143 data=dict(type="dict", no_log=True),
144 disable=dict(type="bool", default=False),
145 validation_delay=dict(type="int", default=30),
146 )
147
148
149 def module_options():
150 return dict(
151 required_if=[("state", "present", ["plugin"])],
152 )
153
154
155 class ProxmoxClusterAcmePluginDnsAnsible(ProxmoxAnsible):
156 def __init__(self, module):
157 super().__init__(module)
158 self.params = module.params
159
160 def validate_params(self):
161 delay = self.params.get("validation_delay")
162 if delay is not None and (delay < MIN_VALIDATION_DELAY or delay > MAX_VALIDATION_DELAY):
163 self.module.fail_json(
164 msg=f"validation_delay should be between {MIN_VALIDATION_DELAY} and {MAX_VALIDATION_DELAY}",
165 )
166
167 def run(self):
168 state = self.params["state"]
169 name = self.params["name"]
170
171 if state == "present":
172 self._ensure_present(name)
173 else:
174 self._ensure_absent(name)
175
176 def _ensure_present(self, name):
177 existing = self._fetch_plugin(name)
178
179 if existing is None:
180 if self.module.check_mode:
181 self.module.exit_json(
182 changed=True,
183 name=name,
184 msg=f"ACME DNS plugin {name} would be created",
185 )
186
187 result = self._create_plugin(name)
188 self.module.exit_json(**result)
189
190 result = self._reconcile_existing(name, existing)
191 self.module.exit_json(**result)
192
193 def _ensure_absent(self, name):
194 existing = self._fetch_plugin(name)
195
196 if existing is None:
197 self.module.exit_json(
198 changed=False,
199 name=name,
200 msg=f"ACME DNS plugin {name} does not exist",
201 )
202
203 if self.module.check_mode:
204 self.module.exit_json(
205 changed=True,
206 name=name,
207 msg=f"ACME DNS plugin {name} would be deleted",
208 )
209
210 self._delete_plugin(name)
211
212 self.module.exit_json(
213 changed=True,
214 name=name,
215 msg=f"ACME DNS plugin {name} successfully deleted",
216 )
217
218 def _reconcile_existing(self, name, existing):
219 current = acme_plugin_to_ansible_result(existing)
220 desired = self._build_desired(name)
221
222 if not self._is_update_required(current, desired):
223 return {
224 "changed": False,
225 "msg": f"ACME DNS plugin {name} already up to date",
226 **current,
227 }
228
229 if self.module.check_mode:
230 return {
231 "changed": True,
232 "name": name,
233 "msg": f"ACME DNS plugin {name} would be updated",
234 }
235
236 return self._update_plugin(name)
237
238 def _is_update_required(self, current, desired):
239 return (
240 current["plugin"] != desired["plugin"]
241 or current["disable"] != desired["disable"]
242 or current["validation_delay"] != desired["validation_delay"]
243 or (desired.get("data") is not None and current["data"] != desired["data"])
244 )
245
246 def _create_plugin(self, name):
247 payload = {"type": "dns", **self._build_params()}
248
249 try:
250 self._plugin_endpoint().post(id=name, **payload)
251 except Exception as e:
252 self.module.fail_json(msg=f"Failed to create ACME DNS plugin {name}: {to_native(e)}")
253
254 created = self._fetch_plugin(name)
255 if created is None:
256 self.module.fail_json(
257 msg=f"ACME DNS plugin {name} not found after create",
258 name=name,
259 )
260
261 result = acme_plugin_to_ansible_result(created)
262 return {
263 "changed": True,
264 "msg": f"ACME DNS plugin {name} successfully created",
265 **result,
266 }
267
268 def _update_plugin(self, name):
269 payload = self._build_params()
270
271 try:
272 self._plugin_endpoint(name).put(**payload)
273 except Exception as e:
274 self.module.fail_json(msg=f"Failed to update ACME DNS plugin {name}: {to_native(e)}")
275
276 updated = self._fetch_plugin(name)
277 if updated is None:
278 self.module.fail_json(
279 msg=f"ACME DNS plugin {name} not found after update",
280 name=name,
281 )
282
283 result = acme_plugin_to_ansible_result(updated)
284 return {
285 "changed": True,
286 "msg": f"ACME DNS plugin {name} successfully updated",
287 **result,
288 }
289
290 def _delete_plugin(self, name):
291 try:
292 self._plugin_endpoint(name).delete()
293 except Exception as e:
294 self.module.fail_json(msg=f"Failed to delete ACME DNS plugin {name}: {to_native(e)}")
295
296 def _fetch_plugin(self, name):
297 try:
298 return self._plugin_endpoint(name).get()
299 except Exception as e:
300 if "not defined" in str(e).lower():
301 return None
302 self.module.fail_json(msg=f"Failed to read ACME plugin {name}: {to_native(e)}")
303
304 def _plugin_endpoint(self, name=None):
305 base = self.proxmox_api.cluster().acme().plugins()
306 return base if not name else base(name)
307
308 def _build_desired(self, name):
309 p = self.params
310 raw_data = p.get("data")
311
312 return {
313 "name": name,
314 "plugin": p["plugin"],
315 "disable": p["disable"],
316 "validation_delay": p["validation_delay"],
317 "data": None if raw_data is None else acme_plugin_normalize_data_dict(raw_data),
318 }
319
320 def _build_params(self):
321 p = self.params
322
323 payload = {
324 "api": p["plugin"],
325 "validation-delay": p["validation_delay"],
326 "disable": ansible_to_proxmox_bool(p["disable"]),
327 }
328
329 if p.get("data") is not None:
330 payload["data"] = _data_to_api(p["data"])
331
332 return payload
333
334
335 def main():
336 module = create_proxmox_module(module_args(), **module_options())
337 proxmox = ProxmoxClusterAcmePluginDnsAnsible(module)
338 proxmox.validate_params()
339
340 try:
341 proxmox.run()
342 except Exception as e:
343 module.fail_json(msg=f"An error occurred: {to_native(e)}")
344
345
346 if __name__ == "__main__":
347 main()