Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_application_fasthttp.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_fasthttp
13 short_description: Manages BIG-IQ FastHTTP applications
14 description:
15 - Manages BIG-IQ applications used for load balancing an HTTP-based application, speeding
16 up connections and reducing the number of connections to the back-end server.
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(80).
47 type: int
48 default: 80
49 inbound_virtual:
50 description:
51 - Settings to configure the virtual which receives the inbound connection.
52 - This virtual is used to host the HTTP endpoint of the application.
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(80).
72 type: int
73 default: 80
74 type: dict
75 service_environment:
76 description:
77 - Specifies the name of the service environment to which the application is.
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 (at this time, SSGs and BIGIPs).
82 type: str
83 add_analytics:
84 description:
85 - Collects statistics of the BIG-IP to which the application is deployed.
86 - This parameter is only relevant when specifying a C(service_environment) which
87 is a BIG-IP; not an SSG.
88 type: bool
89 default: false
90 state:
91 description:
92 - The state of the resource on the system.
93 - When C(present), guarantees the resource exists with the provided attributes.
94 - When C(absent), removes the resource from the system.
95 type: str
96 choices:
97 - absent
98 - present
99 default: present
100 wait:
101 description:
102 - If the module should wait for the application to be created, deleted, or updated.
103 type: bool
104 default: true
105 extends_documentation_fragment: f5networks.f5_modules.f5
106 notes:
107 - This module does not support updating of your application (whether deployed or not).
108 If you need to update the application, we recommended removing and
109 re-creating it.
110 - This module does 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 an HTTP application on port 80 on BIG-IP
117 bigiq_application_fasthttp:
118 name: my-app
119 description: Fast HTTP
120 service_environment: my-ssg
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: 80
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 the server listens on.
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 'ssgReference': 'ssg_reference',
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 'ssgReference', 'defaultDeviceReference', 'addAnalytics'
223 ]
224
225 returnables = [
226 'resources', 'description', 'config_set_name', 'sub_path', 'template_reference',
227 'ssg_reference', 'default_device_reference', 'servers', 'inbound_virtual',
228 'add_analytics'
229 ]
230
231 updatables = [
232 'resources', 'description', 'config_set_name', 'sub_path', 'template_reference',
233 'ssg_reference', 'default_device_reference', 'servers', 'add_analytics'
234 ]
235
236
237 class ApiParameters(Parameters):
238 pass
239
240
241 class ModuleParameters(Parameters):
242 @property
243 def http_profile(self):
244 return "profile_http"
245
246 @property
247 def config_set_name(self):
248 return self.name
249
250 @property
251 def sub_path(self):
252 return self.name
253
254 @property
255 def template_reference(self):
256 filter = "name+eq+'Default-f5-fastHTTP-lb-template'"
257 uri = "https://{0}:{1}/mgmt/cm/global/templates/?$filter={2}&$top=1&$select=selfLink".format(
258 self.client.provider['server'],
259 self.client.provider['server_port'],
260 filter
261 )
262 resp = self.client.api.get(uri)
263 try:
264 response = resp.json()
265 except ValueError as ex:
266 raise F5ModuleError(str(ex))
267 if resp.status == 200 and response['totalItems'] == 0:
268 raise F5ModuleError(
269 "No default HTTP LB template was found."
270 )
271 elif 'code' in response and response['code'] == 400:
272 if 'message' in response:
273 raise F5ModuleError(response['message'])
274 else:
275 raise F5ModuleError(resp._content)
276
277 result = dict(
278 link=response['items'][0]['selfLink']
279 )
280 return result
281
282 @property
283 def default_device_reference(self):
284 if is_valid_ip(self.service_environment):
285 # An IP address was specified
286 filter = "address+eq+'{0}'".format(self.service_environment)
287 else:
288 # Assume a hostname was specified
289 filter = "hostname+eq+'{0}'".format(self.service_environment)
290
291 uri = "https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-adccore-allbigipDevices/devices/" \
292 "?$filter={2}&$top=1&$select=selfLink".format(self.client.provider['server'],
293 self.client.provider['server_port'], filter)
294 resp = self.client.api.get(uri)
295 try:
296 response = resp.json()
297 except ValueError as ex:
298 raise F5ModuleError(str(ex))
299 if resp.status == 200 and response['totalItems'] == 0:
300 return None
301 elif 'code' in response and response['code'] == 400:
302 if 'message' in response:
303 raise F5ModuleError(response['message'])
304 else:
305 raise F5ModuleError(resp._content)
306 result = dict(
307 link=response['items'][0]['selfLink']
308 )
309 return result
310
311 @property
312 def ssg_reference(self):
313 filter = "name+eq+'{0}'".format(self.service_environment)
314 uri = "https://{0}:{1}/mgmt/cm/cloud/service-scaling-groups/?$filter={2}&$top=1&$select=selfLink".format(
315 self.client.provider['server'],
316 self.client.provider['server_port'],
317 filter
318 )
319 resp = self.client.api.get(uri)
320 try:
321 response = resp.json()
322 except ValueError as ex:
323 raise F5ModuleError(str(ex))
324 if resp.status == 200 and response['totalItems'] == 0:
325 return None
326 elif 'code' in response and response['code'] == 400:
327 if 'message' in response:
328 raise F5ModuleError(response['message'])
329 else:
330 raise F5ModuleError(resp._content)
331 result = dict(
332 link=response['items'][0]['selfLink']
333 )
334 return result
335
336
337 class Changes(Parameters):
338 def to_return(self):
339 result = {}
340 try:
341 for returnable in self.returnables:
342 result[returnable] = getattr(self, returnable)
343 result = self._filter_params(result)
344 except Exception:
345 pass
346 return result
347
348
349 class UsableChanges(Changes):
350 @property
351 def resources(self):
352 result = dict()
353 result.update(self.http_profile)
354 result.update(self.http_monitor)
355 result.update(self.virtual)
356 result.update(self.pool)
357 result.update(self.nodes)
358 return result
359
360 @property
361 def virtual(self):
362 result = dict()
363 result['ltm:virtual:0257bb9bb997'] = [
364 dict(
365 parameters=dict(
366 name='virtual',
367 destinationAddress=self.inbound_virtual['address'],
368 mask=self.inbound_virtual['netmask'],
369 destinationPort=self.inbound_virtual['port']
370 ),
371 subcollectionResources=self.profiles
372 )
373 ]
374 return result
375
376 @property
377 def profiles(self):
378 result = {
379 'profiles:53f9b3028d90': [
380 dict(
381 parameters=dict()
382 )
383 ],
384 'profiles:b2f39bda63fd': [
385 dict(
386 parameters=dict()
387 )
388 ]
389 }
390 return result
391
392 @property
393 def pool(self):
394 result = dict()
395 result['ltm:pool:f76ae78f1de6'] = [
396 dict(
397 parameters=dict(
398 name='pool_0'
399 ),
400 subcollectionResources=self.pool_members
401 )
402 ]
403 return result
404
405 @property
406 def pool_members(self):
407 result = dict()
408 result['members:15ad51f7229e'] = []
409 for x in self.servers:
410 member = dict(
411 parameters=dict(
412 port=x['port'],
413 nodeReference=dict(
414 link='#/resources/ltm:node:0783ce16685f/{0}'.format(x['address']),
415 fullPath='# {0}'.format(x['address'])
416 )
417 )
418 )
419 result['members:15ad51f7229e'].append(member)
420 return result
421
422 @property
423 def http_profile(self):
424 result = dict()
425 result['ltm:profile:http:b2f39bda63fd'] = [
426 dict(
427 parameters=dict(
428 name='profile_http'
429 )
430 )
431 ]
432 return result
433
434 @property
435 def http_monitor(self):
436 result = dict()
437 result['ltm:monitor:http:cf6f6e7ae758'] = [
438 dict(
439 parameters=dict(
440 name='monitor-http'
441 )
442 )
443 ]
444 return result
445
446 @property
447 def nodes(self):
448 result = dict()
449 result['ltm:node:0783ce16685f'] = []
450 for x in self.servers:
451 tmp = dict(
452 parameters=dict(
453 name=x['address'],
454 address=x['address']
455 )
456 )
457 result['ltm:node:0783ce16685f'].append(tmp)
458 return result
459
460 @property
461 def node_addresses(self):
462 result = [x['address'] for x in self.servers]
463 return result
464
465
466 class ReportableChanges(Changes):
467 pass
468
469
470 class Difference(object):
471 def __init__(self, want, have=None):
472 self.want = want
473 self.have = have
474
475 def compare(self, param):
476 try:
477 result = getattr(self, param)
478 return result
479 except AttributeError:
480 return self.__default(param)
481
482 def __default(self, param):
483 attr1 = getattr(self.want, param)
484 try:
485 attr2 = getattr(self.have, param)
486 if attr1 != attr2:
487 return attr1
488 except AttributeError:
489 return attr1
490
491
492 class ModuleManager(object):
493 def __init__(self, *args, **kwargs):
494 self.module = kwargs.get('module', None)
495 self.client = F5RestClient(**self.module.params)
496 self.want = ModuleParameters(params=self.module.params)
497 self.want.client = self.client
498 self.have = ApiParameters()
499 self.changes = UsableChanges()
500
501 def _set_changed_options(self):
502 changed = {}
503 for key in Parameters.returnables:
504 if getattr(self.want, key) is not None:
505 changed[key] = getattr(self.want, key)
506 if changed:
507 self.changes = UsableChanges(params=changed)
508
509 def _update_changed_options(self):
510 diff = Difference(self.want, self.have)
511 updatables = Parameters.updatables
512 changed = dict()
513 for k in updatables:
514 change = diff.compare(k)
515 if change is None:
516 continue
517 else:
518 if isinstance(change, dict):
519 changed.update(change)
520 else:
521 changed[k] = change
522 if changed:
523 self.changes = UsableChanges(params=changed)
524 return True
525 return False
526
527 def should_update(self):
528 result = self._update_changed_options()
529 if result:
530 return True
531 return False
532
533 def check_bigiq_version(self, version):
534 if Version(version) >= Version('6.1.0'):
535 raise F5ModuleError(
536 'Module supports only BIGIQ version 6.0.x or lower.'
537 )
538
539 def exec_module(self):
540 start = datetime.now().isoformat()
541 version = bigiq_version(self.client)
542 self.check_bigiq_version(version)
543 changed = False
544 result = dict()
545 state = self.want.state
546
547 if state == "present":
548 changed = self.present()
549 elif state == "absent":
550 changed = self.absent()
551
552 reportable = ReportableChanges(params=self.changes.to_return())
553 changes = reportable.to_return()
554 result.update(**changes)
555 result.update(dict(changed=changed))
556 self._announce_deprecations(result)
557 send_teem(start, self.client, self.module, version)
558 return result
559
560 def _announce_deprecations(self, result):
561 warnings = result.pop('__warnings', [])
562 for warning in warnings:
563 self.client.module.deprecate(
564 msg=warning['msg'],
565 version=warning['version']
566 )
567
568 def present(self):
569 if self.exists():
570 return False
571 else:
572 return self.create()
573
574 def exists(self):
575 uri = "https://{0}:{1}/mgmt/ap/query/v1/tenants/default/reports/" \
576 "AllApplicationsList?$filter=name+eq+'{2}'".format(self.client.provider['server'],
577 self.client.provider['server_port'], self.want.name)
578 resp = self.client.api.get(uri)
579 try:
580 response = resp.json()
581 except ValueError as ex:
582 raise F5ModuleError(str(ex))
583 if (resp.status == 200 and 'result' in response and
584 'totalItems' in response['result'] and response['result']['totalItems'] == 0):
585 return False
586 return True
587
588 def remove(self):
589 if self.module.check_mode:
590 return True
591 self_link = self.remove_from_device()
592 if self.want.wait:
593 self.wait_for_apply_template_task(self_link)
594 if self.exists():
595 raise F5ModuleError("Failed to delete the resource.")
596 return True
597
598 def has_no_service_environment(self):
599 if self.want.default_device_reference is None and self.want.ssg_reference is None:
600 return True
601 return False
602
603 def create(self):
604 if self.want.service_environment is None:
605 raise F5ModuleError(
606 "A 'service_environment' must be specified when creating a new application."
607 )
608 if self.want.servers is None:
609 raise F5ModuleError(
610 "At least one 'servers' item is needed when creating a new application."
611 )
612 if self.want.inbound_virtual is None:
613 raise F5ModuleError(
614 "An 'inbound_virtual' must be specified when creating a new application."
615 )
616 self._set_changed_options()
617
618 if self.has_no_service_environment():
619 raise F5ModuleError(
620 "The specified 'service_environment' ({0}) was not found.".format(self.want.service_environment)
621 )
622
623 if self.module.check_mode:
624 return True
625 self_link = self.create_on_device()
626 if self.want.wait:
627 self.wait_for_apply_template_task(self_link)
628 if not self.exists():
629 raise F5ModuleError(
630 "Failed to deploy application."
631 )
632 return True
633
634 def create_on_device(self):
635 params = self.changes.api_params()
636 params['mode'] = 'CREATE'
637
638 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
639 self.client.provider['server'],
640 self.client.provider['server_port']
641 )
642
643 resp = self.client.api.post(uri, json=params)
644 try:
645 response = resp.json()
646 except ValueError as ex:
647 raise F5ModuleError(str(ex))
648
649 if 'code' in response and response['code'] == 400:
650 if 'message' in response:
651 raise F5ModuleError(response['message'])
652 else:
653 raise F5ModuleError(resp._content)
654 return response['selfLink']
655
656 def absent(self):
657 if self.exists():
658 return self.remove()
659 return False
660
661 def remove_from_device(self):
662 params = dict(
663 configSetName=self.want.name,
664 mode='DELETE'
665 )
666 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
667 self.client.provider['server'],
668 self.client.provider['server_port']
669 )
670
671 resp = self.client.api.post(uri, json=params)
672 try:
673 response = resp.json()
674 except ValueError as ex:
675 raise F5ModuleError(str(ex))
676
677 if 'code' in response and response['code'] == 400:
678 if 'message' in response:
679 raise F5ModuleError(response['message'])
680 else:
681 raise F5ModuleError(resp._content)
682 return response['selfLink']
683
684 def wait_for_apply_template_task(self, self_link):
685 host = 'https://{0}:{1}'.format(
686 self.client.provider['server'],
687 self.client.provider['server_port']
688 )
689 uri = self_link.replace('https://localhost', host)
690
691 while True:
692 resp = self.client.api.get(uri)
693 try:
694 response = resp.json()
695 except ValueError as ex:
696 raise F5ModuleError(str(ex))
697
698 if response['status'] == 'FINISHED' and response.get('currentStep', None) == 'DONE':
699 return True
700 elif 'errorMessage' in response:
701 raise F5ModuleError(response['errorMessage'])
702 time.sleep(5)
703
704
705 class ArgumentSpec(object):
706 def __init__(self):
707 self.supports_check_mode = True
708 argument_spec = dict(
709 name=dict(required=True),
710 description=dict(),
711 servers=dict(
712 type='list',
713 elements='dict',
714 options=dict(
715 address=dict(required=True),
716 port=dict(type='int', default=80)
717 )
718 ),
719 inbound_virtual=dict(
720 type='dict',
721 options=dict(
722 address=dict(required=True),
723 netmask=dict(required=True),
724 port=dict(type='int', default=80)
725 )
726 ),
727 service_environment=dict(),
728 add_analytics=dict(type='bool', default='no'),
729 state=dict(
730 default='present',
731 choices=['present', 'absent']
732 ),
733 wait=dict(type='bool', default='yes')
734 )
735 self.argument_spec = {}
736 self.argument_spec.update(f5_argument_spec)
737 self.argument_spec.update(argument_spec)
738
739
740 def main():
741 spec = ArgumentSpec()
742
743 module = AnsibleModule(
744 argument_spec=spec.argument_spec,
745 supports_check_mode=spec.supports_check_mode
746 )
747
748 if not HAS_PACKAGING:
749 module.fail_json(
750 msg=missing_required_lib('packaging'),
751 exception=PACKAGING_IMPORT_ERROR
752 )
753
754 try:
755 mm = ModuleManager(module=module)
756 results = mm.exec_module()
757 module.exit_json(**results)
758 except F5ModuleError as ex:
759 module.fail_json(msg=str(ex))
760
761
762 if __name__ == '__main__':
763 main()