Debian Codegraph @

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