Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/modules/zone_rrset.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2025, Hetzner Cloud GmbH <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6
7 from __future__ import annotations
8
9 DOCUMENTATION = """
10 ---
11 module: zone_rrset
12
13 short_description: Create and manage Zone RRSets on the Hetzner Cloud.
14
15 description:
16 - Create, update and delete Zone RRSets on the Hetzner Cloud.
17 - See the L(Zone RRSets API documentation,https://docs.hetzner.cloud/reference/cloud#zone-rrsets) for more details.
18
19 author:
20 - Jonas Lammler (@jooola)
21
22 options:
23 zone:
24 description:
25 - Name or ID of the parent Zone.
26 type: str
27 required: true
28 id:
29 description:
30 - ID of the Zone RRSet to manage.
31 - Only required if no Zone RRSet O(name) and O(type) are given.
32 type: int
33 name:
34 description:
35 - Name of the Zone RRSet to manage.
36 - Only required if no Zone RRSet O(id) is given or the Zone RRSet does not exist.
37 type: str
38 type:
39 description:
40 - Type of the Zone RRSet to manage.
41 - Only required if no Zone RRSet O(id) is given or the Zone RRSet does not exist.
42 type: str
43 ttl:
44 description:
45 - TTL of the Zone RRSet.
46 type: int
47 records:
48 description:
49 - Records of the Zone RRSet.
50 type: list
51 elements: dict
52 suboptions:
53 value:
54 description:
55 - Value of the record.
56 type: str
57 comment:
58 description:
59 - Comment of the record.
60 type: str
61 change_protection:
62 description:
63 - Protect the Zone RRSet from changes (deletion and updates).
64 type: bool
65 labels:
66 description:
67 - User-defined key-value pairs.
68 type: dict
69 state:
70 description:
71 - State of the Zone RRSet.
72 default: present
73 choices: [absent, present]
74 type: str
75
76 extends_documentation_fragment:
77 - hetzner.hcloud.hcloud
78 """
79
80 EXAMPLES = """
81 - name: Create a Zone RRSet
82 hetzner.hcloud.zone_rrset:
83 zone: example.com
84 name: www
85 type: A
86 ttl: 300
87 records:
88 - value: 201.118.10.2
89 comment: web server 1
90 - value: 201.118.10.3
91 comment: web server 2
92 state: present
93
94 - name: Create a TXT record
95 hetzner.hcloud.zone_rrset:
96 zone: example.com
97 name: "@"
98 type: "TXT"
99 records:
100 - value: "{{ 'v=spf1 include:_spf.example.net ~all' | hetzner.hcloud.txt_record }}"
101 state: present
102
103 - name: Delete a Zone RRSet
104 hetzner.hcloud.zone_rrset:
105 zone: 42
106 name: www
107 type: A
108 state: absent
109 """
110
111 RETURN = """
112 hcloud_zone_rrset:
113 description: Zone RRSet instance.
114 returned: always
115 type: dict
116 contains:
117 zone:
118 description: ID of the parent Zone.
119 type: int
120 returned: always
121 sample: 42
122 id:
123 description: ID of the Zone RRSet.
124 type: str
125 returned: always
126 sample: www/A
127 name:
128 description: Name of the Zone RRSet.
129 type: str
130 returned: always
131 sample: my-zone
132 type:
133 description: Type of the Zone RRSet.
134 type: str
135 returned: always
136 sample: A
137 ttl:
138 description: TTL of the Zone RRSet.
139 type: int
140 returned: always
141 sample: 3600
142 labels:
143 description: User-defined labels (key-value pairs)
144 type: dict
145 returned: always
146 sample:
147 key: value
148 change_protection:
149 description: Protect the Zone RRSet from changes (deletion and updates).
150 type: bool
151 returned: always
152 sample: false
153 records:
154 description: Records of the Zone RRSet.
155 returned: always
156 type: list
157 elements: dict
158 contains:
159 value:
160 description: Value of the Record.
161 returned: always
162 type: str
163 sample: 203.0.113.1
164 comment:
165 description: Comment of the Record.
166 returned: always
167 type: str
168 sample: webserver 1
169 """
170
171 from typing import Literal
172
173 from ansible.module_utils.basic import AnsibleModule
174
175 from ..module_utils._base import AnsibleHCloud
176 from ..module_utils._vendor.hcloud import APIException, HCloudException
177 from ..module_utils._vendor.hcloud.actions import BoundAction
178 from ..module_utils._vendor.hcloud.zones import BoundZoneRRSet, Zone, ZoneRecord
179
180
181 class AnsibleHCloudZoneRRSet(AnsibleHCloud):
182 represent = "hcloud_zone_rrset"
183
184 hcloud_zone_rrset: BoundZoneRRSet | None = None
185
186 def _prepare_result(self):
187 return {
188 # Do not use the zone name to prevent a request to the API.
189 "zone": self.hcloud_zone_rrset.zone.id,
190 "id": self.hcloud_zone_rrset.id,
191 "name": self.hcloud_zone_rrset.name,
192 "type": self.hcloud_zone_rrset.type,
193 "ttl": self.hcloud_zone_rrset.ttl,
194 "labels": self.hcloud_zone_rrset.labels,
195 "change_protection": self.hcloud_zone_rrset.protection["change"],
196 "records": [self._prepare_result_record(o) for o in self.hcloud_zone_rrset.records or []],
197 }
198
199 def _prepare_result_record(self, record: ZoneRecord):
200 return {
201 "value": record.value,
202 "comment": record.comment or "", # API defaults to "", this ensure idempotency
203 }
204
205 def _get(self):
206 try:
207 if self.module.params.get("id") is not None:
208 # pylint: disable=disallowed-name
209 rrset_name, _, rrset_type = self.module.params.get("id").partition("/")
210 else:
211 rrset_name, rrset_type = self.module.params.get("name"), self.module.params.get("type")
212
213 try:
214 self.hcloud_zone_rrset = self.client.zones.get_rrset(
215 # zone name and id are interchangeable
216 zone=Zone(self.module.params.get("zone")),
217 name=rrset_name,
218 type=rrset_type,
219 )
220 except APIException as api_exception:
221 if api_exception.code != "not_found":
222 raise
223 except HCloudException as exception:
224 self.fail_json_hcloud(exception)
225
226 def _create(self):
227 self.module.fail_on_missing_params(required_params=["name", "type"])
228 params = {
229 "name": self.module.params.get("name"),
230 "type": self.module.params.get("type"),
231 }
232
233 if self.module.params.get("ttl") is not None:
234 params["ttl"] = self.module.params.get("ttl")
235
236 if self.module.params.get("labels") is not None:
237 params["labels"] = self.module.params.get("labels")
238
239 if self.module.params.get("records") is not None:
240 params["records"] = [ZoneRecord.from_dict(o) for o in self.module.params.get("records")]
241
242 if not self.module.check_mode:
243 try:
244 resp = self.client.zones.create_rrset(
245 # zone name and id are interchangeable
246 zone=Zone(self.module.params.get("zone")),
247 **params,
248 )
249 resp.action.wait_until_finished()
250
251 self.hcloud_zone_rrset = resp.rrset
252
253 if self.module.params.get("change_protection") is not None:
254 action = self.hcloud_zone_rrset.change_rrset_protection(
255 change=self.module.params.get("change_protection"),
256 )
257 action.wait_until_finished()
258
259 except HCloudException as exception:
260 self.fail_json_hcloud(exception)
261
262 self._mark_as_changed()
263 self._get()
264
265 def _update(self):
266 try:
267 # The "change" protection prevents us from updating the rrset. To reach the
268 # state the user provided, we must update the "change" protection:
269 # - before other updates if the current change protection is enabled,
270 # - after other updates if the current change protection is disabled.
271 update_protection_when: Literal["after", "before"] | None = None
272
273 change_protection = self.module.params.get("change_protection")
274 if change_protection is not None and change_protection != self.hcloud_zone_rrset.protection["change"]:
275 update_protection_when = "before" if self.hcloud_zone_rrset.protection["change"] else "after"
276
277 if update_protection_when == "before":
278 if not self.module.check_mode:
279 action = self.hcloud_zone_rrset.change_rrset_protection(change=change_protection)
280 action.wait_until_finished()
281 self._mark_as_changed()
282
283 actions: list[BoundAction] = []
284
285 ttl = self.module.params.get("ttl")
286 if ttl is not None and ttl != self.hcloud_zone_rrset.ttl:
287 if not self.module.check_mode:
288 action = self.hcloud_zone_rrset.change_rrset_ttl(ttl=ttl)
289 actions.append(action)
290 self._mark_as_changed()
291
292 records = self.module.params.get("records")
293 if records is not None and self._diff_records():
294 if not self.module.check_mode:
295 action = self.hcloud_zone_rrset.set_rrset_records(
296 records=[ZoneRecord.from_dict(o) for o in records]
297 )
298 actions.append(action)
299 self._mark_as_changed()
300
301 for action in actions:
302 action.wait_until_finished()
303
304 labels = self.module.params.get("labels")
305 if labels is not None and labels != self.hcloud_zone_rrset.labels:
306 if not self.module.check_mode:
307 self.hcloud_zone_rrset.update_rrset(labels=labels)
308 self._mark_as_changed()
309
310 if update_protection_when == "after":
311 if not self.module.check_mode:
312 action = self.hcloud_zone_rrset.change_rrset_protection(change=change_protection)
313 action.wait_until_finished()
314 self._mark_as_changed()
315
316 self._get()
317 except HCloudException as exception:
318 self.fail_json_hcloud(exception)
319
320 def _diff_records(self) -> bool:
321 current = [self._prepare_result_record(o) for o in self.hcloud_zone_rrset.records]
322 wanted = [self._prepare_result_record(ZoneRecord.from_dict(o)) for o in self.module.params.get("records")]
323
324 current = sorted(current, key=lambda x: x["value"])
325 wanted = sorted(wanted, key=lambda x: x["value"])
326
327 return current != wanted
328
329 def present(self):
330 self._get()
331 if self.hcloud_zone_rrset is None:
332 self._create()
333 else:
334 self._update()
335
336 def absent(self):
337 try:
338 self._get()
339 if self.hcloud_zone_rrset is not None:
340 if not self.module.check_mode:
341 resp = self.hcloud_zone_rrset.delete_rrset()
342 resp.action.wait_until_finished()
343 self._mark_as_changed()
344
345 self.hcloud_zone_rrset = None
346 except HCloudException as exception:
347 self.fail_json_hcloud(exception)
348
349 @classmethod
350 def define_module(cls):
351 return AnsibleModule(
352 argument_spec=dict(
353 zone={"type": "str", "required": True},
354 id={"type": "int"},
355 name={"type": "str"},
356 type={"type": "str"},
357 ttl={"type": "int"},
358 labels={"type": "dict"},
359 records={
360 "type": "list",
361 "elements": "dict",
362 "options": dict(
363 value={"type": "str"},
364 comment={"type": "str"},
365 ),
366 },
367 change_protection={"type": "bool"},
368 state={
369 "choices": ["absent", "present"],
370 "default": "present",
371 },
372 **super().base_module_arguments(),
373 ),
374 required_one_of=[["id", "name"]],
375 required_together=[["name", "type"]],
376 supports_check_mode=True,
377 )
378
379
380 def main():
381 module = AnsibleHCloudZoneRRSet.define_module()
382
383 hcloud = AnsibleHCloudZoneRRSet(module)
384 state = module.params.get("state")
385 if state == "absent":
386 hcloud.absent()
387 else:
388 hcloud.present()
389
390 module.exit_json(**hcloud.get_result())
391
392
393 if __name__ == "__main__":
394 main()