Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_dns_nameserver.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_dns_nameserver
13 short_description: Manage LTM DNS nameservers on a BIG-IP
14 description:
15 - Manages LTM DNS nameservers on a BIG-IP. These nameservers form part of what is
16 known as DNS Express on a BIG-IP. This module does not configure GTM (DNS module) related
17 functionality, nor does it configure system-level name servers that affect the
18 ability of the base system to resolve DNS names.
19 version_added: "1.0.0"
20 options:
21 name:
22 description:
23 - Specifies the name of the nameserver.
24 type: str
25 required: True
26 address:
27 description:
28 - Specifies the IP address on which the DNS nameserver (client) or back-end DNS
29 authoritative server (DNS Express server) listens for DNS messages.
30 - When creating a new nameserver, if this value is not specified, the default
31 is C(127.0.0.1).
32 type: str
33 service_port:
34 description:
35 - Specifies the service port on which the DNS nameserver (client) or back-end DNS
36 authoritative server (DNS Express server) listens for DNS messages.
37 - When creating a new nameserver, if this value is not specified, the default
38 is C(53).
39 type: str
40 route_domain:
41 description:
42 - Specifies the local route domain the DNS nameserver (client) or back-end
43 DNS authoritative server (DNS Express server) uses for outbound traffic.
44 - When creating a new nameserver, if this value is not specified, the default
45 is C(0).
46 type: str
47 tsig_key:
48 description:
49 - Specifies the TSIG key the system uses to communicate with this DNS nameserver
50 (client) or back-end DNS authoritative server (DNS Express server) for AXFR zone
51 transfers.
52 - If the nameserver is a client, then the system uses this TSIG key to verify the
53 request and sign the response.
54 - If this nameserver is a DNS Express server, then this TSIG key must match the
55 TSIG key for the zone on the back-end DNS authoritative server.
56 type: str
57 state:
58 description:
59 - When C(present), ensures the resource exists.
60 - When C(absent), ensures the resource is removed.
61 type: str
62 choices:
63 - present
64 - absent
65 default: present
66 partition:
67 description:
68 - Device partition to manage resources on.
69 type: str
70 default: Common
71 extends_documentation_fragment: f5networks.f5_modules.f5
72 author:
73 - Tim Rupp (@caphrim007)
74 '''
75
76 EXAMPLES = r'''
77 - name: Create a nameserver
78 bigip_dns_nameserver:
79 name: foo
80 address: 10.10.10.10
81 service_port: 53
82 state: present
83 provider:
84 password: secret
85 server: lb.mydomain.com
86 user: admin
87 delegate_to: localhost
88 '''
89
90 RETURN = r'''
91 address:
92 description: Address which the nameserver listens for DNS messages.
93 returned: changed
94 type: str
95 sample: 127.0.0.1
96 service_port:
97 description: Service port on which the nameserver listens for DNS messages.
98 returned: changed
99 type: int
100 sample: 53
101 '''
102 from datetime import datetime
103 from ansible.module_utils.basic import (
104 AnsibleModule, env_fallback
105 )
106
107 from ..module_utils.bigip import F5RestClient
108 from ..module_utils.common import (
109 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
110 )
111 from ..module_utils.icontrol import tmos_version
112 from ..module_utils.teem import send_teem
113
114
115 class Parameters(AnsibleF5Parameters):
116 api_map = {
117 'routeDomain': 'route_domain',
118 'port': 'service_port',
119 'tsigKey': 'tsig_key'
120 }
121
122 api_attributes = [
123 'address',
124 'routeDomain',
125 'port',
126 'tsigKey'
127 ]
128
129 returnables = [
130 'address',
131 'service_port',
132 'route_domain',
133 'tsig_key',
134 ]
135
136 updatables = [
137 'address',
138 'service_port',
139 'route_domain',
140 'tsig_key',
141 ]
142
143
144 class ApiParameters(Parameters):
145 pass
146
147
148 class ModuleParameters(Parameters):
149 @property
150 def tsig_key(self):
151 if self._values['tsig_key'] in [None, '']:
152 return self._values['tsig_key']
153 return fq_name(self.partition, self._values['tsig_key'])
154
155 @property
156 def route_domain(self):
157 if self._values['route_domain'] is None:
158 return None
159 return fq_name(self.partition, self._values['route_domain'])
160
161 @property
162 def service_port(self):
163 if self._values['service_port'] is None:
164 return None
165 try:
166 return int(self._values['service_port'])
167 except ValueError:
168 # Reserving the right to add well-known ports
169 raise F5ModuleError(
170 "The 'service_port' must be in numeric form."
171 )
172
173
174 class Changes(Parameters):
175 def to_return(self):
176 result = {}
177 try:
178 for returnable in self.returnables:
179 result[returnable] = getattr(self, returnable)
180 result = self._filter_params(result)
181 except Exception:
182 raise
183 return result
184
185
186 class UsableChanges(Changes):
187 pass
188
189
190 class ReportableChanges(Changes):
191 pass
192
193
194 class Difference(object):
195 def __init__(self, want, have=None):
196 self.want = want
197 self.have = have
198
199 def compare(self, param):
200 try:
201 result = getattr(self, param)
202 return result
203 except AttributeError:
204 return self.__default(param)
205
206 def __default(self, param):
207 attr1 = getattr(self.want, param)
208 try:
209 attr2 = getattr(self.have, param)
210 if attr1 != attr2:
211 return attr1
212 except AttributeError:
213 return attr1
214
215 @property
216 def tsig_key(self):
217 if self.want.tsig_key is None:
218 return None
219 if self.have.tsig_key is None and self.want.tsig_key == '':
220 return None
221 if self.want.tsig_key != self.have.tsig_key:
222 return self.want.tsig_key
223
224
225 class ModuleManager(object):
226 def __init__(self, *args, **kwargs):
227 self.module = kwargs.get('module', None)
228 self.client = F5RestClient(**self.module.params)
229 self.want = ModuleParameters(params=self.module.params)
230 self.have = ApiParameters()
231 self.changes = UsableChanges()
232
233 def _set_changed_options(self):
234 changed = {}
235 for key in Parameters.returnables:
236 if getattr(self.want, key) is not None:
237 changed[key] = getattr(self.want, key)
238 if changed:
239 self.changes = UsableChanges(params=changed)
240
241 def _update_changed_options(self):
242 diff = Difference(self.want, self.have)
243 updatables = Parameters.updatables
244 changed = dict()
245 for k in updatables:
246 change = diff.compare(k)
247 if change is None:
248 continue
249 else:
250 if isinstance(change, dict):
251 changed.update(change)
252 else:
253 changed[k] = change
254 if changed:
255 self.changes = UsableChanges(params=changed)
256 return True
257 return False
258
259 def should_update(self):
260 result = self._update_changed_options()
261 if result:
262 return True
263 return False
264
265 def exec_module(self):
266 start = datetime.now().isoformat()
267 version = tmos_version(self.client)
268 changed = False
269 result = dict()
270 state = self.want.state
271
272 if state == "present":
273 changed = self.present()
274 elif state == "absent":
275 changed = self.absent()
276
277 reportable = ReportableChanges(params=self.changes.to_return())
278 changes = reportable.to_return()
279 result.update(**changes)
280 result.update(dict(changed=changed))
281 self._announce_deprecations(result)
282 send_teem(start, self.client, self.module, version)
283 return result
284
285 def _announce_deprecations(self, result):
286 warnings = result.pop('__warnings', [])
287 for warning in warnings:
288 self.client.module.deprecate(
289 msg=warning['msg'],
290 version=warning['version']
291 )
292
293 def present(self):
294 if self.exists():
295 return self.update()
296 else:
297 return self.create()
298
299 def exists(self):
300 errors = [401, 403, 409, 500, 501, 502, 503, 504]
301 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/nameserver/{2}".format(
302 self.client.provider['server'],
303 self.client.provider['server_port'],
304 transform_name(self.want.partition, self.want.name)
305 )
306 resp = self.client.api.get(uri)
307 try:
308 response = resp.json()
309 except ValueError as ex:
310 raise F5ModuleError(str(ex))
311
312 if resp.status == 404 or 'code' in response and response['code'] == 404:
313 return False
314 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
315 return True
316
317 if resp.status in errors or 'code' in response and response['code'] in errors:
318 if 'message' in response:
319 raise F5ModuleError(response['message'])
320 else:
321 raise F5ModuleError(resp.content)
322
323 def update(self):
324 self.have = self.read_current_from_device()
325 if not self.should_update():
326 return False
327 if self.module.check_mode:
328 return True
329 self.update_on_device()
330 return True
331
332 def remove(self):
333 if self.module.check_mode:
334 return True
335 self.remove_from_device()
336 if self.exists():
337 raise F5ModuleError("Failed to delete the resource.")
338 return True
339
340 def create(self):
341 if self.want.address is None:
342 self.want.update({'address': '127.0.0.1'})
343 if self.want.service_port is None:
344 self.want.update({'service_port': '53'})
345 if self.want.route_domain is None:
346 self.want.update({'route_domain': '/Common/0'})
347 self._set_changed_options()
348 if self.module.check_mode:
349 return True
350 self.create_on_device()
351 return True
352
353 def create_on_device(self):
354 params = self.changes.api_params()
355 params['name'] = self.want.name
356 params['partition'] = self.want.partition
357 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/nameserver/".format(
358 self.client.provider['server'],
359 self.client.provider['server_port']
360 )
361 resp = self.client.api.post(uri, json=params)
362 try:
363 response = resp.json()
364 except ValueError as ex:
365 raise F5ModuleError(str(ex))
366
367 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
368 return True
369 raise F5ModuleError(resp.content)
370
371 def update_on_device(self):
372 params = self.changes.api_params()
373 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/nameserver/{2}".format(
374 self.client.provider['server'],
375 self.client.provider['server_port'],
376 transform_name(self.want.partition, self.want.name)
377 )
378 resp = self.client.api.patch(uri, json=params)
379 try:
380 response = resp.json()
381 except ValueError as ex:
382 raise F5ModuleError(str(ex))
383
384 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
385 return True
386 raise F5ModuleError(resp.content)
387
388 def absent(self):
389 if self.exists():
390 return self.remove()
391 return False
392
393 def remove_from_device(self):
394 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/nameserver/{2}".format(
395 self.client.provider['server'],
396 self.client.provider['server_port'],
397 transform_name(self.want.partition, self.want.name)
398 )
399 response = self.client.api.delete(uri)
400 if response.status == 200:
401 return True
402 raise F5ModuleError(response.content)
403
404 def read_current_from_device(self):
405 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/nameserver/{2}".format(
406 self.client.provider['server'],
407 self.client.provider['server_port'],
408 transform_name(self.want.partition, self.want.name)
409 )
410 resp = self.client.api.get(uri)
411 try:
412 response = resp.json()
413 except ValueError as ex:
414 raise F5ModuleError(str(ex))
415
416 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
417 return ApiParameters(params=response)
418 raise F5ModuleError(resp.content)
419
420
421 class ArgumentSpec(object):
422 def __init__(self):
423 self.supports_check_mode = True
424 argument_spec = dict(
425 name=dict(required=True),
426 address=dict(),
427 service_port=dict(),
428 route_domain=dict(),
429 tsig_key=dict(no_log=True),
430 state=dict(
431 default='present',
432 choices=['present', 'absent']
433 ),
434 partition=dict(
435 default='Common',
436 fallback=(env_fallback, ['F5_PARTITION'])
437 )
438 )
439 self.argument_spec = {}
440 self.argument_spec.update(f5_argument_spec)
441 self.argument_spec.update(argument_spec)
442
443
444 def main():
445 spec = ArgumentSpec()
446
447 module = AnsibleModule(
448 argument_spec=spec.argument_spec,
449 supports_check_mode=spec.supports_check_mode,
450 )
451
452 try:
453 mm = ModuleManager(module=module)
454 results = mm.exec_module()
455 module.exit_json(**results)
456 except F5ModuleError as ex:
457 module.fail_json(msg=str(ex))
458
459
460 if __name__ == '__main__':
461 main()