Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_application_fastl4_udp.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: bigiq_application_fastl4_udp
13 short_description: Manages BIG-IQ FastL4 UDP applications
14 description:
15 - Manages BIG-IQ applications used for load balancing a UDP-based application.
16 with a FastL4 profile.
17 version_added: "1.0.0"
18 options:
19 name:
20 description:
21 - Name of the new application.
22 type: str
23 required: True
24 description:
25 description:
26 - Description of the application.
27 type: str
28 servers:
29 description:
30 - A list of servers on which the application is hosted.
31 - If you are familiar with other BIG-IP settings, you might also refer to this
32 list as the list of pool members.
33 - When creating a new application, at least one server is required.
34 type: list
35 elements: dict
36 suboptions:
37 address:
38 description:
39 - The IP address of the server.
40 type: str
41 required: True
42 port:
43 description:
44 - The port of the server.
45 - When creating a new application and specifying a server, if this parameter
46 is not provided, the default is C(8000).
47 type: int
48 default: 8000
49 inbound_virtual:
50 description:
51 - Settings to configure the virtual which receives the inbound connection.
52 type: dict
53 suboptions:
54 address:
55 description:
56 - Specifies destination IP address information to which the virtual server
57 sends traffic.
58 - This parameter is required when creating a new application.
59 type: str
60 required: True
61 netmask:
62 description:
63 - Specifies the netmask to associate with the given C(destination).
64 - This parameter is required when creating a new application.
65 type: str
66 required: True
67 port:
68 description:
69 - The port on which the virtual listens for connections.
70 - When creating a new application, if this parameter is not specified, the
71 default value is C(53).
72 type: int
73 default: 53
74 service_environment:
75 description:
76 - Specifies the name of service environment to which the application is
77 deployed.
78 - When creating a new application, this parameter is required.
79 - The service environment type is automatically discovered by this module.
80 Therefore, it is crucial you maintain unique names for items in the
81 different service environment types.
82 - SSGs are not supported for this type of application.
83 type: str
84 add_analytics:
85 description:
86 - Collects statistics of the BIG-IP to which the application is deployed.
87 - This parameter is only relevant when specifying a C(service_environment) which
88 is a BIG-IP; not an SSG.
89 type: bool
90 default: false
91 state:
92 description:
93 - The state of the resource on the system.
94 - When C(present), guarantees the resource exists with the provided attributes.
95 - When C(absent), removes the resource from the system.
96 type: str
97 choices:
98 - absent
99 - present
100 default: present
101 wait:
102 description:
103 - If the module should wait for the application to be created, deleted, or updated.
104 type: bool
105 default: true
106 extends_documentation_fragment: f5networks.f5_modules.f5
107 notes:
108 - This module does not support updating of your application (whether deployed or not).
109 If you need to update the application, we recommend removing and recreating it.
110 - This module will not work on BIG-IQ version 6.1.x or greater.
111 author:
112 - Tim Rupp (@caphrim007)
113 '''
114
115 EXAMPLES = r'''
116 - name: BIG-IQ CM a UDP-based application with a FastL4 profile
117 bigiq_application_fastl4_udp:
118 name: my-app
119 description: My description
120 service_environment: my-bigip-device
121 servers:
122 - address: 1.2.3.4
123 port: 8080
124 - address: 5.6.7.8
125 port: 8080
126 inbound_virtual:
127 name: foo
128 address: 2.2.2.2
129 netmask: 255.255.255.255
130 port: 53
131 provider:
132 password: secret
133 server: cm.mydomain.com
134 user: admin
135 state: present
136 delegate_to: localhost
137 '''
138
139 RETURN = r'''
140 description:
141 description: The new description of the application of the resource.
142 returned: changed
143 type: str
144 sample: My application
145 service_environment:
146 description: The environment to which the service was deployed.
147 returned: changed
148 type: str
149 sample: my-ssg1
150 inbound_virtual_destination:
151 description: The destination of the virtual that was created.
152 returned: changed
153 type: str
154 sample: 6.7.8.9
155 inbound_virtual_netmask:
156 description: The network mask of the provided inbound destination.
157 returned: changed
158 type: str
159 sample: 255.255.255.0
160 inbound_virtual_port:
161 description: The port on which the inbound virtual address listens.
162 returned: changed
163 type: int
164 sample: 80
165 servers:
166 description: List of servers, and their ports, that make up the application.
167 type: complex
168 returned: changed
169 contains:
170 address:
171 description: The IP address of the server.
172 returned: changed
173 type: str
174 sample: 2.3.4.5
175 port:
176 description: The port on which the server listens.
177 returned: changed
178 type: int
179 sample: 8080
180 sample: hash/dictionary of values
181 '''
182
183 import time
184 import traceback
185 from datetime import datetime
186
187 try:
188 from packaging.version import Version
189 except ImportError:
190 HAS_PACKAGING = False
191 Version = None
192 PACKAGING_IMPORT_ERROR = traceback.format_exc()
193 else:
194 HAS_PACKAGING = True
195 PACKAGING_IMPORT_ERROR = None
196
197 from ansible.module_utils.basic import (
198 AnsibleModule, missing_required_lib
199 )
200
201 from ..module_utils.bigip import F5RestClient
202 from ..module_utils.common import (
203 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
204 )
205 from ..module_utils.icontrol import bigiq_version
206 from ..module_utils.ipaddress import is_valid_ip
207 from ..module_utils.teem import send_teem
208
209
210 class Parameters(AnsibleF5Parameters):
211 api_map = {
212 'templateReference': 'template_reference',
213 'subPath': 'sub_path',
214 'configSetName': 'config_set_name',
215 'defaultDeviceReference': 'default_device_reference',
216 'addAnalytics': 'add_analytics'
217 }
218
219 api_attributes = [
220 'resources', 'description', 'configSetName', 'subPath', 'templateReference',
221 'defaultDeviceReference', 'addAnalytics'
222 ]
223
224 returnables = [
225 'resources', 'description', 'config_set_name', 'sub_path', 'template_reference',
226 'default_device_reference', 'servers', 'inbound_virtual', 'add_analytics'
227 ]
228
229 updatables = [
230 'resources', 'description', 'config_set_name', 'sub_path', 'template_reference',
231 'default_device_reference', 'servers', 'add_analytics'
232 ]
233
234
235 class ApiParameters(Parameters):
236 pass
237
238
239 class ModuleParameters(Parameters):
240 @property
241 def http_profile(self):
242 return "profile_http"
243
244 @property
245 def config_set_name(self):
246 return self.name
247
248 @property
249 def sub_path(self):
250 return self.name
251
252 @property
253 def template_reference(self):
254 filter = "name+eq+'Default-f5-FastL4-UDP-lb-template'"
255 uri = "https://{0}:{1}/mgmt/cm/global/templates/?$filter={2}&$top=1&$select=selfLink".format(
256 self.client.provider['server'],
257 self.client.provider['server_port'],
258 filter
259 )
260 resp = self.client.api.get(uri)
261 try:
262 response = resp.json()
263 except ValueError as ex:
264 raise F5ModuleError(str(ex))
265 if resp.status == 200 and response['totalItems'] == 0:
266 raise F5ModuleError(
267 "No default HTTP LB template was found."
268 )
269 elif 'code' in response and response['code'] == 400:
270 if 'message' in response:
271 raise F5ModuleError(response['message'])
272 else:
273 raise F5ModuleError(resp._content)
274
275 result = dict(link=response['items'][0]['selfLink'])
276 return result
277
278 @property
279 def default_device_reference(self):
280 if is_valid_ip(self.service_environment):
281 # An IP address was specified
282 filter = "address+eq+'{0}'".format(self.service_environment)
283 else:
284 # Assume a hostname was specified
285 filter = "hostname+eq+'{0}'".format(self.service_environment)
286
287 uri = "https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-adccore-allbigipDevices/devices/" \
288 "?$filter={2}&$top=1&$select=selfLink".format(self.client.provider['server'],
289 self.client.provider['server_port'],
290 filter)
291 resp = self.client.api.get(uri)
292 try:
293 response = resp.json()
294 except ValueError as ex:
295 raise F5ModuleError(str(ex))
296 if resp.status == 200 and response['totalItems'] == 0:
297 raise F5ModuleError(
298 "The specified service_environment '{0}' was found.".format(self.service_environment)
299 )
300 elif 'code' in response and response['code'] == 400:
301 if 'message' in response:
302 raise F5ModuleError(response['message'])
303 else:
304 raise F5ModuleError(resp._content)
305 result = dict(
306 link=response['items'][0]['selfLink']
307 )
308 return result
309
310
311 class Changes(Parameters):
312 def to_return(self):
313 result = {}
314 try:
315 for returnable in self.returnables:
316 result[returnable] = getattr(self, returnable)
317 result = self._filter_params(result)
318 except Exception:
319 pass
320 return result
321
322
323 class UsableChanges(Changes):
324 @property
325 def resources(self):
326 result = dict()
327 result.update(self.udp_monitor)
328 result.update(self.virtual)
329 result.update(self.pool)
330 result.update(self.nodes)
331 return result
332
333 @property
334 def virtual(self):
335 result = dict()
336 result['ltm:virtual:c2e739ba116f'] = [
337 dict(
338 parameters=dict(
339 name='virtual',
340 destinationAddress=self.inbound_virtual['address'],
341 mask=self.inbound_virtual['netmask'],
342 destinationPort=self.inbound_virtual.get('port', 53)
343 ),
344 subcollectionResources=self.profiles
345 )
346 ]
347 return result
348
349 @property
350 def profiles(self):
351 result = {
352 'profiles:53f9b3028d90': [
353 dict(
354 parameters=dict()
355 )
356 ]
357 }
358 return result
359
360 @property
361 def pool(self):
362 result = dict()
363 result['ltm:pool:e6879775458c'] = [
364 dict(
365 parameters=dict(
366 name='pool_0'
367 ),
368 subcollectionResources=self.pool_members
369 )
370 ]
371 return result
372
373 @property
374 def pool_members(self):
375 result = dict()
376 result['members:b19842fe713a'] = []
377 for x in self.servers:
378 member = dict(
379 parameters=dict(
380 port=x.get('port', 8000),
381 nodeReference=dict(
382 link='#/resources/ltm:node:b19842fe713a/{0}'.format(x['address']),
383 fullPath='# {0}'.format(x['address'])
384 )
385 )
386 )
387 result['members:b19842fe713a'].append(member)
388 return result
389
390 @property
391 def udp_monitor(self):
392 result = dict()
393 result['ltm:monitor:udp:22cdcfda0a40'] = [
394 dict(
395 parameters=dict(
396 name='monitor-udp'
397 )
398 )
399 ]
400 return result
401
402 @property
403 def nodes(self):
404 result = dict()
405 result['ltm:node:b19842fe713a'] = []
406 for x in self.servers:
407 tmp = dict(
408 parameters=dict(
409 name=x['address'],
410 address=x['address']
411 )
412 )
413 result['ltm:node:b19842fe713a'].append(tmp)
414 return result
415
416 @property
417 def node_addresses(self):
418 result = [x['address'] for x in self.servers]
419 return result
420
421
422 class ReportableChanges(Changes):
423 pass
424
425
426 class Difference(object):
427 def __init__(self, want, have=None):
428 self.want = want
429 self.have = have
430
431 def compare(self, param):
432 try:
433 result = getattr(self, param)
434 return result
435 except AttributeError:
436 return self.__default(param)
437
438 def __default(self, param):
439 attr1 = getattr(self.want, param)
440 try:
441 attr2 = getattr(self.have, param)
442 if attr1 != attr2:
443 return attr1
444 except AttributeError:
445 return attr1
446
447
448 class ModuleManager(object):
449 def __init__(self, *args, **kwargs):
450 self.module = kwargs.get('module', None)
451 self.client = F5RestClient(**self.module.params)
452 self.want = ModuleParameters(params=self.module.params)
453 self.want.client = self.client
454 self.have = ApiParameters()
455 self.changes = UsableChanges()
456
457 def _set_changed_options(self):
458 changed = {}
459 for key in Parameters.returnables:
460 if getattr(self.want, key) is not None:
461 changed[key] = getattr(self.want, key)
462 if changed:
463 self.changes = UsableChanges(params=changed)
464
465 def _update_changed_options(self):
466 diff = Difference(self.want, self.have)
467 updatables = Parameters.updatables
468 changed = dict()
469 for k in updatables:
470 change = diff.compare(k)
471 if change is None:
472 continue
473 else:
474 if isinstance(change, dict):
475 changed.update(change)
476 else:
477 changed[k] = change
478 if changed:
479 self.changes = UsableChanges(params=changed)
480 return True
481 return False
482
483 def should_update(self):
484 result = self._update_changed_options()
485 if result:
486 return True
487 return False
488
489 def check_bigiq_version(self, version):
490 if Version(version) >= Version('6.1.0'):
491 raise F5ModuleError(
492 'Module supports only BIGIQ version 6.0.x or lower.'
493 )
494
495 def exec_module(self):
496 start = datetime.now().isoformat()
497 version = bigiq_version(self.client)
498 self.check_bigiq_version(version)
499 changed = False
500 result = dict()
501 state = self.want.state
502
503 if state == "present":
504 changed = self.present()
505 elif state == "absent":
506 changed = self.absent()
507
508 reportable = ReportableChanges(params=self.changes.to_return())
509 changes = reportable.to_return()
510 result.update(**changes)
511 result.update(dict(changed=changed))
512 self._announce_deprecations(result)
513 send_teem(start, self.client, self.module, version)
514 return result
515
516 def _announce_deprecations(self, result):
517 warnings = result.pop('__warnings', [])
518 for warning in warnings:
519 self.client.module.deprecate(
520 msg=warning['msg'],
521 version=warning['version']
522 )
523
524 def present(self):
525 if self.exists():
526 return False
527 else:
528 return self.create()
529
530 def exists(self):
531 uri = "https://{0}:{1}/mgmt/ap/query/v1/tenants/default/reports/AllApplicationsList" \
532 "?$filter=name+eq+'{2}'".format(self.client.provider['server'],
533 self.client.provider['server_port'], self.want.name)
534 resp = self.client.api.get(uri)
535 try:
536 response = resp.json()
537 except ValueError as ex:
538 raise F5ModuleError(str(ex))
539 if (resp.status == 200 and 'result' in response and
540 'totalItems' in response['result'] and response['result']['totalItems'] == 0):
541 return False
542 return True
543
544 def remove(self):
545 if self.module.check_mode:
546 return True
547 self_link = self.remove_from_device()
548 if self.want.wait:
549 self.wait_for_apply_template_task(self_link)
550 if self.exists():
551 raise F5ModuleError("Failed to delete the resource.")
552 return True
553
554 def create(self):
555 if self.want.service_environment is None:
556 raise F5ModuleError(
557 "A 'service_environment' must be specified when creating a new application."
558 )
559 if self.want.servers is None:
560 raise F5ModuleError(
561 "At least one 'servers' item is needed when creating a new application."
562 )
563 if self.want.inbound_virtual is None:
564 raise F5ModuleError(
565 "An 'inbound_virtual' must be specified when creating a new application."
566 )
567 self._set_changed_options()
568 if self.module.check_mode:
569 return True
570 self_link = self.create_on_device()
571 if self.want.wait:
572 self.wait_for_apply_template_task(self_link)
573 if not self.exists():
574 raise F5ModuleError(
575 "Failed to deploy application."
576 )
577 return True
578
579 def create_on_device(self):
580 params = self.changes.api_params()
581 params['mode'] = 'CREATE'
582
583 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
584 self.client.provider['server'],
585 self.client.provider['server_port']
586 )
587
588 resp = self.client.api.post(uri, json=params)
589 try:
590 response = resp.json()
591 except ValueError as ex:
592 raise F5ModuleError(str(ex))
593
594 if 'code' in response and response['code'] == 400:
595 if 'message' in response:
596 raise F5ModuleError(response['message'])
597 else:
598 raise F5ModuleError(resp._content)
599 return response['selfLink']
600
601 def absent(self):
602 if self.exists():
603 return self.remove()
604 return False
605
606 def remove_from_device(self):
607 params = dict(
608 configSetName=self.want.name,
609 mode='DELETE'
610 )
611 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
612 self.client.provider['server'],
613 self.client.provider['server_port']
614 )
615
616 resp = self.client.api.post(uri, json=params)
617 try:
618 response = resp.json()
619 except ValueError as ex:
620 raise F5ModuleError(str(ex))
621
622 if 'code' in response and response['code'] == 400:
623 if 'message' in response:
624 raise F5ModuleError(response['message'])
625 else:
626 raise F5ModuleError(resp._content)
627 return response['selfLink']
628
629 def wait_for_apply_template_task(self, self_link):
630 host = 'https://{0}:{1}'.format(
631 self.client.provider['server'],
632 self.client.provider['server_port']
633 )
634 uri = self_link.replace('https://localhost', host)
635
636 while True:
637 resp = self.client.api.get(uri)
638 try:
639 response = resp.json()
640 except ValueError as ex:
641 raise F5ModuleError(str(ex))
642
643 if response['status'] == 'FINISHED' and response.get('currentStep', None) == 'DONE':
644 return True
645 elif 'errorMessage' in response:
646 raise F5ModuleError(response['errorMessage'])
647 time.sleep(5)
648
649
650 class ArgumentSpec(object):
651 def __init__(self):
652 self.supports_check_mode = True
653 argument_spec = dict(
654 name=dict(required=True),
655 description=dict(),
656 servers=dict(
657 type='list',
658 elements='dict',
659 options=dict(
660 address=dict(required=True),
661 port=dict(type='int', default=8000)
662 )
663 ),
664 inbound_virtual=dict(
665 type='dict',
666 options=dict(
667 address=dict(required=True),
668 netmask=dict(required=True),
669 port=dict(type='int', default=53)
670 )
671 ),
672 service_environment=dict(),
673 add_analytics=dict(type='bool', default='no'),
674 state=dict(
675 default='present',
676 choices=['present', 'absent']
677 ),
678 wait=dict(type='bool', default='yes')
679 )
680 self.argument_spec = {}
681 self.argument_spec.update(f5_argument_spec)
682 self.argument_spec.update(argument_spec)
683
684
685 def main():
686 spec = ArgumentSpec()
687
688 module = AnsibleModule(
689 argument_spec=spec.argument_spec,
690 supports_check_mode=spec.supports_check_mode
691 )
692
693 if not HAS_PACKAGING:
694 module.fail_json(
695 msg=missing_required_lib('packaging'),
696 exception=PACKAGING_IMPORT_ERROR
697 )
698
699 try:
700 mm = ModuleManager(module=module)
701 results = mm.exec_module()
702 module.exit_json(**results)
703 except F5ModuleError as ex:
704 module.fail_json(msg=str(ex))
705
706
707 if __name__ == '__main__':
708 main()