Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_application_http.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_http
13 short_description: Manages BIG-IQ HTTP applications
14 description:
15 - Manages BIG-IQ applications used for load balancing an HTTP application on
16 port 80 on BIG-IP systems.
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 service environment to which the application is
78 deployed.
79 - When creating a new application, this parameter is required.
80 - The service environment type is automatically discovered by this module.
81 Therefore, it is crucial that you maintain unique names for items in the
82 different service environment types (at this time, SSGs and BIG-IPs).
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 an HTTP application on port 80 on BIG-IP
117 bigiq_application_http:
118 name: my-app
119 description: Redirect HTTP to HTTPS
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: 443
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 '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-HTTP-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 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 return None
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(link=response['items'][0]['selfLink'])
306 return result
307
308 @property
309 def ssg_reference(self):
310 filter = "name+eq+'{0}'".format(self.service_environment)
311 uri = "https://{0}:{1}/mgmt/cm/cloud/service-scaling-groups/?$filter={2}&$top=1&$select=selfLink".format(
312 self.client.provider['server'],
313 self.client.provider['server_port'],
314 filter
315 )
316 resp = self.client.api.get(uri)
317 try:
318 response = resp.json()
319 except ValueError as ex:
320 raise F5ModuleError(str(ex))
321 if resp.status == 200 and response['totalItems'] == 0:
322 return None
323 elif 'code' in response and response['code'] == 400:
324 if 'message' in response:
325 raise F5ModuleError(response['message'])
326 else:
327 raise F5ModuleError(resp._content)
328 result = dict(
329 link=response['items'][0]['selfLink']
330 )
331 return result
332
333
334 class Changes(Parameters):
335 def to_return(self):
336 result = {}
337 try:
338 for returnable in self.returnables:
339 result[returnable] = getattr(self, returnable)
340 result = self._filter_params(result)
341 except Exception:
342 pass
343 return result
344
345
346 class UsableChanges(Changes):
347 @property
348 def resources(self):
349 result = dict()
350 result.update(self.http_profile)
351 result.update(self.http_monitor)
352 result.update(self.virtual)
353 result.update(self.pool)
354 result.update(self.nodes)
355 return result
356
357 @property
358 def virtual(self):
359 result = dict()
360 result['ltm:virtual::b487671f29ba'] = [
361 dict(
362 parameters=dict(
363 name='virtual',
364 destinationAddress=self.inbound_virtual['address'],
365 mask=self.inbound_virtual['netmask'],
366 destinationPort=self.inbound_virtual.get('port', 80)
367 ),
368 subcollectionResources=self.profiles
369 )
370 ]
371 return result
372
373 @property
374 def profiles(self):
375 result = {
376 'profiles:9448fe71611e': [
377 dict(
378 parameters=dict()
379 )
380 ],
381 'profiles:03a4950ab656': [
382 dict(
383 parameters=dict()
384 )
385 ]
386 }
387 return result
388
389 @property
390 def pool(self):
391 result = dict()
392 result['ltm:pool:9a593d17495b'] = [
393 dict(
394 parameters=dict(
395 name='pool_0'
396 ),
397 subcollectionResources=self.pool_members
398 )
399 ]
400 return result
401
402 @property
403 def pool_members(self):
404 result = dict()
405 result['members:5109c66dfbac'] = []
406 for x in self.servers:
407 member = dict(
408 parameters=dict(
409 port=x.get('port', 80),
410 nodeReference=dict(
411 link='#/resources/ltm:node:9e76a6323321/{0}'.format(x['address']),
412 fullPath='# {0}'.format(x['address'])
413 )
414 )
415 )
416 result['members:5109c66dfbac'].append(member)
417 return result
418
419 @property
420 def http_profile(self):
421 result = dict()
422 result['ltm:profile:http:03a4950ab656'] = [
423 dict(
424 parameters=dict(
425 name='profile_http'
426 )
427 )
428 ]
429 return result
430
431 @property
432 def http_monitor(self):
433 result = dict()
434 result['ltm:monitor:http:ea4346e49cdf'] = [
435 dict(
436 parameters=dict(
437 name='monitor-http'
438 )
439 )
440 ]
441 return result
442
443 @property
444 def nodes(self):
445 result = dict()
446 result['ltm:node:9e76a6323321'] = []
447 for x in self.servers:
448 tmp = dict(
449 parameters=dict(
450 name=x['address'],
451 address=x['address']
452 )
453 )
454 result['ltm:node:9e76a6323321'].append(tmp)
455 return result
456
457 @property
458 def node_addresses(self):
459 result = [x['address'] for x in self.servers]
460 return result
461
462
463 class ReportableChanges(Changes):
464 pass
465
466
467 class Difference(object):
468 def __init__(self, want, have=None):
469 self.want = want
470 self.have = have
471
472 def compare(self, param):
473 try:
474 result = getattr(self, param)
475 return result
476 except AttributeError:
477 return self.__default(param)
478
479 def __default(self, param):
480 attr1 = getattr(self.want, param)
481 try:
482 attr2 = getattr(self.have, param)
483 if attr1 != attr2:
484 return attr1
485 except AttributeError:
486 return attr1
487
488
489 class ModuleManager(object):
490 def __init__(self, *args, **kwargs):
491 self.module = kwargs.get('module', None)
492 self.client = F5RestClient(**self.module.params)
493 self.want = ModuleParameters(params=self.module.params)
494 self.want.client = self.client
495 self.have = ApiParameters()
496 self.changes = UsableChanges()
497
498 def _set_changed_options(self):
499 changed = {}
500 for key in Parameters.returnables:
501 if getattr(self.want, key) is not None:
502 changed[key] = getattr(self.want, key)
503 if changed:
504 self.changes = UsableChanges(params=changed)
505
506 def _update_changed_options(self):
507 diff = Difference(self.want, self.have)
508 updatables = Parameters.updatables
509 changed = dict()
510 for k in updatables:
511 change = diff.compare(k)
512 if change is None:
513 continue
514 else:
515 if isinstance(change, dict):
516 changed.update(change)
517 else:
518 changed[k] = change
519 if changed:
520 self.changes = UsableChanges(params=changed)
521 return True
522 return False
523
524 def should_update(self):
525 result = self._update_changed_options()
526 if result:
527 return True
528 return False
529
530 def check_bigiq_version(self, version):
531 if Version(version) >= Version('6.1.0'):
532 raise F5ModuleError(
533 'Module supports only BIGIQ version 6.0.x or lower.'
534 )
535
536 def exec_module(self):
537 start = datetime.now().isoformat()
538 version = bigiq_version(self.client)
539 self.check_bigiq_version(version)
540 changed = False
541 result = dict()
542 state = self.want.state
543
544 if state == "present":
545 changed = self.present()
546 elif state == "absent":
547 changed = self.absent()
548
549 reportable = ReportableChanges(params=self.changes.to_return())
550 changes = reportable.to_return()
551 result.update(**changes)
552 result.update(dict(changed=changed))
553 self._announce_deprecations(result)
554 send_teem(start, self.client, self.module, version)
555 return result
556
557 def _announce_deprecations(self, result):
558 warnings = result.pop('__warnings', [])
559 for warning in warnings:
560 self.client.module.deprecate(
561 msg=warning['msg'],
562 version=warning['version']
563 )
564
565 def present(self):
566 if self.exists():
567 return False
568 else:
569 return self.create()
570
571 def exists(self):
572 uri = "https://{0}:{1}/mgmt/ap/query/v1/tenants/default/reports/AllApplicationsList" \
573 "?$filter=name+eq+'{2}'".format(self.client.provider['server'],
574 self.client.provider['server_port'],
575 self.want.name)
576 resp = self.client.api.get(uri)
577 try:
578 response = resp.json()
579 except ValueError as ex:
580 raise F5ModuleError(str(ex))
581 if (resp.status == 200 and 'result' in response
582 and 'totalItems' in response['result'] and response['result']['totalItems'] == 0):
583 return False
584 return True
585
586 def remove(self):
587 if self.module.check_mode:
588 return True
589 self_link = self.remove_from_device()
590 if self.want.wait:
591 self.wait_for_apply_template_task(self_link)
592 if self.exists():
593 raise F5ModuleError("Failed to delete the resource.")
594 return True
595
596 def has_no_service_environment(self):
597 if self.want.default_device_reference is None and self.want.ssg_reference is None:
598 return True
599 return False
600
601 def create(self):
602 if self.want.service_environment is None:
603 raise F5ModuleError(
604 "A 'service_environment' must be specified when creating a new application."
605 )
606 if self.want.servers is None:
607 raise F5ModuleError(
608 "At least one 'servers' item is needed when creating a new application."
609 )
610 if self.want.inbound_virtual is None:
611 raise F5ModuleError(
612 "An 'inbound_virtual' must be specified when creating a new application."
613 )
614 self._set_changed_options()
615
616 if self.has_no_service_environment():
617 raise F5ModuleError(
618 "The specified 'service_environment' ({0}) was not found.".format(self.want.service_environment)
619 )
620
621 if self.module.check_mode:
622 return True
623 self_link = self.create_on_device()
624 if self.want.wait:
625 self.wait_for_apply_template_task(self_link)
626 if not self.exists():
627 raise F5ModuleError(
628 "Failed to deploy application."
629 )
630 return True
631
632 def create_on_device(self):
633 params = self.changes.api_params()
634 params['mode'] = 'CREATE'
635
636 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
637 self.client.provider['server'],
638 self.client.provider['server_port']
639 )
640
641 resp = self.client.api.post(uri, json=params)
642 try:
643 response = resp.json()
644 except ValueError as ex:
645 raise F5ModuleError(str(ex))
646
647 if 'code' in response and response['code'] == 400:
648 if 'message' in response:
649 raise F5ModuleError(response['message'])
650 else:
651 raise F5ModuleError(resp._content)
652 return response['selfLink']
653
654 def absent(self):
655 if self.exists():
656 return self.remove()
657 return False
658
659 def remove_from_device(self):
660 params = dict(
661 configSetName=self.want.name,
662 mode='DELETE'
663 )
664 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
665 self.client.provider['server'],
666 self.client.provider['server_port']
667 )
668
669 resp = self.client.api.post(uri, json=params)
670 try:
671 response = resp.json()
672 except ValueError as ex:
673 raise F5ModuleError(str(ex))
674
675 if 'code' in response and response['code'] == 400:
676 if 'message' in response:
677 raise F5ModuleError(response['message'])
678 else:
679 raise F5ModuleError(resp._content)
680 return response['selfLink']
681
682 def wait_for_apply_template_task(self, self_link):
683 host = 'https://{0}:{1}'.format(
684 self.client.provider['server'],
685 self.client.provider['server_port']
686 )
687 uri = self_link.replace('https://localhost', host)
688
689 while True:
690 resp = self.client.api.get(uri)
691 try:
692 response = resp.json()
693 except ValueError as ex:
694 raise F5ModuleError(str(ex))
695
696 if response['status'] == 'FINISHED' and response.get('currentStep', None) == 'DONE':
697 return True
698 elif 'errorMessage' in response:
699 raise F5ModuleError(response['errorMessage'])
700 time.sleep(5)
701
702
703 class ArgumentSpec(object):
704 def __init__(self):
705 self.supports_check_mode = True
706 argument_spec = dict(
707 name=dict(required=True),
708 description=dict(),
709 servers=dict(
710 type='list',
711 elements='dict',
712 options=dict(
713 address=dict(required=True),
714 port=dict(type='int', default=80)
715 )
716 ),
717 inbound_virtual=dict(
718 type='dict',
719 options=dict(
720 address=dict(required=True),
721 netmask=dict(required=True),
722 port=dict(type='int', default=80)
723 )
724 ),
725 service_environment=dict(),
726 add_analytics=dict(type='bool', default='no'),
727 state=dict(
728 default='present',
729 choices=['present', 'absent']
730 ),
731 wait=dict(type='bool', default='yes')
732 )
733 self.argument_spec = {}
734 self.argument_spec.update(f5_argument_spec)
735 self.argument_spec.update(argument_spec)
736
737
738 def main():
739 spec = ArgumentSpec()
740
741 module = AnsibleModule(
742 argument_spec=spec.argument_spec,
743 supports_check_mode=spec.supports_check_mode
744 )
745
746 if not HAS_PACKAGING:
747 module.fail_json(
748 msg=missing_required_lib('packaging'),
749 exception=PACKAGING_IMPORT_ERROR
750 )
751
752 try:
753 mm = ModuleManager(module=module)
754 results = mm.exec_module()
755 module.exit_json(**results)
756 except F5ModuleError as ex:
757 module.fail_json(msg=str(ex))
758
759
760 if __name__ == '__main__':
761 main()