Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_gandi_livedns_api.py

raw
1 # Copyright (c) 2019 Gregory Thiemonge <[email protected]>
2 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import json
11 import typing as t
12 from http import HTTPStatus
13
14 from ansible.module_utils.urls import fetch_url
15
16 if t.TYPE_CHECKING:
17 from ansible.module_utils.basic import AnsibleModule
18
19
20 class GandiLiveDNSAPI:
21 api_endpoint = "https://api.gandi.net/v5/livedns"
22 changed = False
23
24 error_strings = {
25 400: "Bad request",
26 401: "Permission denied",
27 404: "Resource not found",
28 }
29
30 attribute_map = {"record": "rrset_name", "type": "rrset_type", "ttl": "rrset_ttl", "values": "rrset_values"}
31
32 def __init__(self, module: AnsibleModule) -> None:
33 self.module = module
34 self.api_key = module.params["api_key"]
35 self.personal_access_token = module.params["personal_access_token"]
36
37 def _build_error_message(self, module, info):
38 s = ""
39 body = info.get("body")
40 if body:
41 errors = module.from_json(body).get("errors")
42 if errors:
43 error = errors[0]
44 name = error.get("name")
45 if name:
46 s += f"{name} :"
47 description = error.get("description")
48 if description:
49 s += description
50 return s
51
52 def _gandi_api_call(self, api_call, method="GET", payload=None, error_on_404=True):
53 authorization_header = (
54 f"Bearer {self.personal_access_token}" if self.personal_access_token else f"Apikey {self.api_key}"
55 )
56 headers = {"Authorization": authorization_header, "Content-Type": "application/json"}
57 data = None
58 if payload:
59 try:
60 data = json.dumps(payload)
61 except Exception as e:
62 self.module.fail_json(msg=f"Failed to encode payload as JSON: {e} ")
63
64 resp, info = fetch_url(self.module, self.api_endpoint + api_call, headers=headers, data=data, method=method)
65
66 error_msg = ""
67 if info["status"] >= HTTPStatus.BAD_REQUEST and (info["status"] != HTTPStatus.NOT_FOUND or error_on_404):
68 err_s = self.error_strings.get(info["status"], "")
69
70 error_msg = f"API Error {err_s}: {self._build_error_message(self.module, info)}"
71
72 result = None
73 try:
74 content = resp.read()
75 except AttributeError:
76 content = None
77
78 if content:
79 try:
80 result = json.loads(content)
81 except getattr(json, "JSONDecodeError", ValueError) as e:
82 error_msg += f"; Failed to parse API response with error {e}: {content}"
83
84 if error_msg:
85 self.module.fail_json(msg=error_msg)
86
87 return result, info["status"]
88
89 def build_result(self, result, domain):
90 if result is None:
91 return None
92
93 res = {}
94 for k in self.attribute_map:
95 v = result.get(self.attribute_map[k], None)
96 if v is not None:
97 if k == "record" and v == "@":
98 v = ""
99 res[k] = v
100
101 res["domain"] = domain
102
103 return res
104
105 def build_results(self, results, domain):
106 if results is None:
107 return []
108 return [self.build_result(r, domain) for r in results]
109
110 def get_records(self, record, type, domain):
111 url = f"/domains/{domain}/records"
112 if record:
113 url += f"/{record}"
114 if type:
115 url += f"/{type}"
116
117 records, status = self._gandi_api_call(url, error_on_404=False)
118
119 if status == HTTPStatus.NOT_FOUND:
120 return []
121
122 if not isinstance(records, list):
123 records = [records]
124
125 # filter by type if record is not set
126 if not record and type:
127 records = [r for r in records if r["rrset_type"] == type]
128
129 return records
130
131 def create_record(self, record, type, values, ttl, domain):
132 url = f"/domains/{domain}/records"
133 new_record = {
134 "rrset_name": record,
135 "rrset_type": type,
136 "rrset_values": values,
137 "rrset_ttl": ttl,
138 }
139 record, status = self._gandi_api_call(url, method="POST", payload=new_record)
140
141 if status in (
142 HTTPStatus.OK,
143 HTTPStatus.CREATED,
144 ):
145 return new_record
146
147 return None
148
149 def update_record(self, record, type, values, ttl, domain):
150 url = f"/domains/{domain}/records/{record}/{type}"
151 new_record = {
152 "rrset_values": values,
153 "rrset_ttl": ttl,
154 }
155 record = self._gandi_api_call(url, method="PUT", payload=new_record)[0]
156 return record
157
158 def delete_record(self, record, type, domain):
159 url = f"/domains/{domain}/records/{record}/{type}"
160
161 self._gandi_api_call(url, method="DELETE")
162
163 def delete_dns_record(self, record, type, values, domain):
164 if record == "":
165 record = "@"
166
167 records = self.get_records(record, type, domain)
168
169 if records:
170 cur_record = records[0]
171 before = cur_record
172
173 self.changed = True
174
175 if values is not None and set(cur_record["rrset_values"]) != set(values):
176 new_values = set(cur_record["rrset_values"]) - set(values)
177 if new_values:
178 # Removing one or more values from a record, we update the record with the remaining values
179 self.update_record(record, type, list(new_values), cur_record["rrset_ttl"], domain)
180 records = self.get_records(record, type, domain)
181 return before, records[0], self.changed
182
183 if not self.module.check_mode:
184 self.delete_record(record, type, domain)
185 else:
186 before = None
187
188 return before, None, self.changed
189
190 def ensure_dns_record(self, record, type, ttl, values, domain):
191 if record == "":
192 record = "@"
193
194 records = self.get_records(record, type, domain)
195
196 if records:
197 cur_record = records[0]
198 before = cur_record
199
200 do_update = False
201 if ttl is not None and cur_record["rrset_ttl"] != ttl:
202 do_update = True
203 if values is not None and set(cur_record["rrset_values"]) != set(values):
204 do_update = True
205
206 if do_update:
207 if self.module.check_mode:
208 result = dict(rrset_type=type, rrset_name=record, rrset_values=values, rrset_ttl=ttl)
209 else:
210 self.update_record(record, type, values, ttl, domain)
211
212 records = self.get_records(record, type, domain)
213 result = records[0]
214 self.changed = True
215 return before, result, self.changed
216 else:
217 return before, cur_record, self.changed
218
219 before = None
220 if self.module.check_mode:
221 new_record = dict(rrset_type=type, rrset_name=record, rrset_values=values, rrset_ttl=ttl)
222 result = new_record
223 else:
224 result = self.create_record(record, type, values, ttl, domain)
225
226 self.changed = True
227 return before, result, self.changed