Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_application_https_offload.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_https_offload
13 short_description: Manages BIG-IQ HTTPS offload applications
14 description:
15 - Manages BIG-IQ applications used for load balancing an HTTPS application on
16 port 443 with SSL offloading on a BIG-IP.
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 type: int
46 default: 80
47 inbound_virtual:
48 description:
49 - Settings to configure the virtual which receives the inbound connection.
50 - This virtual is used to host the HTTPS endpoint of the application.
51 - Traffic destined to the C(redirect_virtual) is offloaded to this
52 parameter to ensure proper redirection from insecure to secure occurs.
53 type: dict
54 suboptions:
55 address:
56 description:
57 - Specifies destination IP address information to which the virtual server
58 sends traffic.
59 - This parameter is required when creating a new application.
60 type: str
61 required: True
62 netmask:
63 description:
64 - Specifies the netmask to associate with the given C(address).
65 - This parameter is required when creating a new application.
66 type: str
67 required: True
68 port:
69 description:
70 - The port on which the virtual listens for connections.
71 - When creating a new application, if this parameter is not specified, the
72 default value is C(443).
73 type: int
74 default: 443
75 redirect_virtual:
76 description:
77 - Settings to configure the virtual which receives the connection to be
78 redirected.
79 - This virtual is used to host the HTTP endpoint of the application.
80 - Traffic destined to this parameter is offloaded to the
81 C(inbound_virtual) parameter to ensure proper redirection from insecure
82 to secure occurs.
83 type: dict
84 suboptions:
85 address:
86 description:
87 - Specifies destination IP address information to which the virtual server
88 sends traffic.
89 - This parameter is required when creating a new application.
90 type: str
91 required: True
92 netmask:
93 description:
94 - Specifies the netmask to associate with the given C(address).
95 - This parameter is required when creating a new application.
96 type: str
97 required: True
98 port:
99 description:
100 - The port on which the virtual listens for connections.
101 - When creating a new application, if this parameter is not specified, the
102 default value is C(80).
103 type: int
104 default: 80
105 client_ssl_profile:
106 description:
107 - Specifies the SSL profile for managing client-side SSL traffic.
108 type: dict
109 suboptions:
110 name:
111 description:
112 - The name of the client SSL profile to created and used.
113 - When creating a new application, if this value is not specified, the
114 default value is C(clientssl).
115 type: str
116 default: clientssl
117 cert_key_chain:
118 description:
119 - One or more certificates and keys to associate with the SSL profile.
120 - This option is always a list. The keys in the list dictate the details
121 of the client/key/chain/passphrase combination.
122 - BIG-IPs can only have one of each type of each certificate/key
123 type. This means you can only have one RSA, one DSA, and one ECDSA
124 per profile.
125 - If you attempt to assign two RSA, DSA, or ECDSA certificate/key combo,
126 the device rejects it.
127 - This list is a complex list that specifies a number of keys.
128 - When creating a new profile, if this parameter is not specified, the
129 default value is C(inherit).
130 type: raw
131 suboptions:
132 cert:
133 description:
134 - Specifies a cert name for use.
135 type: str
136 key:
137 description:
138 - Specifies a key name.
139 type: str
140 chain:
141 description:
142 - Specifies a certificate chain that is relevant to the specified certificate and
143 key.
144 - This key is optional.
145 type: str
146 passphrase:
147 description:
148 - Contains the passphrase of the key file, should it require one.
149 - Passphrases are encrypted on the remote BIG-IP device.
150 type: str
151 service_environment:
152 description:
153 - Specifies the name of service environment or the hostname of the BIG-IP to which
154 the application will be deployed.
155 - When creating a new application, this parameter is required.
156 type: str
157 add_analytics:
158 description:
159 - Collects statistics of the BIG-IP to which the application is deployed.
160 - This parameter is only relevant when specifying a C(service_environment) which
161 is a BIG-IP; not an SSG.
162 type: bool
163 default: false
164 state:
165 description:
166 - The state of the resource on the system.
167 - When C(present), guarantees the resource exists with the provided attributes.
168 - When C(absent), removes the resource from the system.
169 type: str
170 choices:
171 - absent
172 - present
173 default: present
174 wait:
175 description:
176 - If the module should wait for the application to be created, deleted or updated.
177 type: bool
178 default: true
179 extends_documentation_fragment: f5networks.f5_modules.f5
180 notes:
181 - This module will not work on BIGIQ version 6.1.x or greater.
182 author:
183 - Tim Rupp (@caphrim007)
184 '''
185
186 EXAMPLES = r'''
187 - name: BIG-IQ CM an HTTPS application on port 443 with SSL offloading on BIG-IP
188 bigiq_application_https_offload:
189 name: my-app
190 description: Redirect HTTP to HTTPS
191 service_environment: my-ssg
192 servers:
193 - address: 1.2.3.4
194 port: 8080
195 - address: 5.6.7.8
196 port: 8080
197 inbound_virtual:
198 address: 2.2.2.2
199 netmask: 255.255.255.255
200 port: 443
201 redirect_virtual:
202 address: 2.2.2.2
203 netmask: 255.255.255.255
204 port: 80
205 provider:
206 password: secret
207 server: cm.mydomain.com
208 user: admin
209 state: present
210 delegate_to: localhost
211 '''
212
213 RETURN = r'''
214 description:
215 description: The new description of the application of the resource.
216 returned: changed
217 type: str
218 sample: My application
219 service_environment:
220 description: The environment to which the service was deployed.
221 returned: changed
222 type: str
223 sample: my-ssg1
224 inbound_virtual_destination:
225 description: The destination of the virtual that was created.
226 returned: changed
227 type: str
228 sample: 6.7.8.9
229 inbound_virtual_netmask:
230 description: The network mask of the provided inbound destination.
231 returned: changed
232 type: str
233 sample: 255.255.255.0
234 inbound_virtual_port:
235 description: The port on which the inbound virtual address listens.
236 returned: changed
237 type: int
238 sample: 80
239 servers:
240 description: List of servers, and their ports, that make up the application.
241 type: complex
242 returned: changed
243 contains:
244 address:
245 description: The IP address of the server.
246 returned: changed
247 type: str
248 sample: 2.3.4.5
249 port:
250 description: The port on which the server listens.
251 returned: changed
252 type: int
253 sample: 8080
254 sample: hash/dictionary of values
255 '''
256
257 import time
258 import traceback
259 from datetime import datetime
260
261 try:
262 from packaging.version import Version
263 except ImportError:
264 HAS_PACKAGING = False
265 Version = None
266 PACKAGING_IMPORT_ERROR = traceback.format_exc()
267 else:
268 HAS_PACKAGING = True
269 PACKAGING_IMPORT_ERROR = None
270
271 from ansible.module_utils.basic import (
272 AnsibleModule, missing_required_lib
273 )
274 from ansible.module_utils.six import string_types
275
276 from ..module_utils.bigip import F5RestClient
277 from ..module_utils.common import (
278 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, fq_name
279 )
280 from ..module_utils.icontrol import bigiq_version
281 from ..module_utils.ipaddress import is_valid_ip
282 from ..module_utils.teem import send_teem
283
284
285 class Parameters(AnsibleF5Parameters):
286 api_map = {
287 'templateReference': 'template_reference',
288 'subPath': 'sub_path',
289 'ssgReference': 'ssg_reference',
290 'configSetName': 'config_set_name',
291 'defaultDeviceReference': 'default_device_reference',
292 'addAnalytics': 'add_analytics'
293 }
294
295 api_attributes = [
296 'resources', 'description', 'configSetName', 'subPath', 'templateReference',
297 'ssgReference', 'defaultDeviceReference', 'addAnalytics'
298 ]
299
300 returnables = [
301 'resources', 'description', 'config_set_name', 'sub_path', 'template_reference',
302 'ssg_reference', 'default_device_reference', 'servers', 'inbound_virtual',
303 'redirect_virtual', 'client_ssl_profile', 'add_analytics'
304 ]
305
306 updatables = [
307 'resources', 'description', 'config_set_name', 'sub_path', 'template_reference',
308 'ssg_reference', 'default_device_reference', 'servers', 'add_analytics'
309 ]
310
311
312 class ApiParameters(Parameters):
313 pass
314
315
316 class ModuleParameters(Parameters):
317 @property
318 def http_profile(self):
319 return "profile_http"
320
321 @property
322 def config_set_name(self):
323 return self.name
324
325 @property
326 def sub_path(self):
327 return self.name
328
329 @property
330 def template_reference(self):
331 filter = "name+eq+'Default-f5-HTTPS-offload-lb-template'"
332 uri = "https://{0}:{1}/mgmt/cm/global/templates/?$filter={2}&$top=1&$select=selfLink".format(
333 self.client.provider['server'],
334 self.client.provider['server_port'],
335 filter
336 )
337 resp = self.client.api.get(uri)
338 try:
339 response = resp.json()
340 except ValueError as ex:
341 raise F5ModuleError(str(ex))
342 if resp.status == 200 and response['totalItems'] == 0:
343 raise F5ModuleError(
344 "No default HTTP LB template was found."
345 )
346 elif 'code' in response and response['code'] == 400:
347 if 'message' in response:
348 raise F5ModuleError(response['message'])
349 else:
350 raise F5ModuleError(resp._content)
351
352 result = dict(
353 link=response['items'][0]['selfLink']
354 )
355 return result
356
357 @property
358 def default_device_reference(self):
359 if is_valid_ip(self.service_environment):
360 # An IP address was specified
361 filter = "address+eq+'{0}'".format(self.service_environment)
362 else:
363 # Assume a hostname was specified
364 filter = "hostname+eq+'{0}'".format(self.service_environment)
365
366 uri = "https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-adccore-allbigipDevices/devices/" \
367 "?$filter={2}&$top=1&$select=selfLink".format(self.client.provider['server'],
368 self.client.provider['server_port'], filter
369 )
370 resp = self.client.api.get(uri)
371 try:
372 response = resp.json()
373 except ValueError as ex:
374 raise F5ModuleError(str(ex))
375 if resp.status == 200 and response['totalItems'] == 0:
376 return None
377 elif 'code' in response and response['code'] == 400:
378 if 'message' in response:
379 raise F5ModuleError(response['message'])
380 else:
381 raise F5ModuleError(resp._content)
382 result = dict(
383 link=response['items'][0]['selfLink']
384 )
385 return result
386
387 @property
388 def ssg_reference(self):
389 filter = "name+eq+'{0}'".format(self.service_environment)
390 uri = "https://{0}:{1}/mgmt/cm/cloud/service-scaling-groups/?$filter={2}&$top=1&$select=selfLink".format(
391 self.client.provider['server'],
392 self.client.provider['server_port'],
393 filter
394 )
395 resp = self.client.api.get(uri)
396 try:
397 response = resp.json()
398 except ValueError as ex:
399 raise F5ModuleError(str(ex))
400 if resp.status == 200 and response['totalItems'] == 0:
401 return None
402 elif 'code' in response and response['code'] == 400:
403 if 'message' in response:
404 raise F5ModuleError(response['message'])
405 else:
406 raise F5ModuleError(resp._content)
407 result = dict(
408 link=response['items'][0]['selfLink']
409 )
410 return result
411
412
413 class Changes(Parameters):
414 def to_return(self):
415 result = {}
416 try:
417 for returnable in self.returnables:
418 result[returnable] = getattr(self, returnable)
419 result = self._filter_params(result)
420 except Exception:
421 pass
422 return result
423
424
425 class UsableChanges(Changes):
426 @property
427 def resources(self):
428 result = dict()
429 result.update(self.http_profile)
430 result.update(self.http_monitor)
431 result.update(self.inbound_virtual_server)
432 result.update(self.redirect_virtual_server)
433 result.update(self.pool)
434 result.update(self.nodes)
435 result.update(self.ssl_profile)
436 return result
437
438 @property
439 def inbound_virtual_server(self):
440 result = dict()
441 result['ltm:virtual:7a5f7da91996'] = [
442 dict(
443 parameters=dict(
444 name='default_vs',
445 destinationAddress=self.inbound_virtual['address'],
446 mask=self.inbound_virtual['netmask'],
447 destinationPort=self.inbound_virtual['port']
448 ),
449 subcollectionResources=self.inbound_profiles
450 )
451 ]
452 return result
453
454 @property
455 def inbound_profiles(self):
456 result = {
457 'profiles:14c995c33411': [
458 dict(
459 parameters=dict()
460 )
461 ],
462 'profiles:8ba4bb101701': [
463 dict(
464 parameters=dict()
465 )
466 ],
467 'profiles:9448fe71611e': [
468 dict(
469 parameters=dict()
470 )
471 ]
472 }
473 return result
474
475 @property
476 def redirect_virtual_server(self):
477 result = dict()
478 result['ltm:virtual:40e8c4a6f542'] = [
479 dict(
480 parameters=dict(
481 name='default_redirect_vs',
482 destinationAddress=self.redirect_virtual['address'],
483 mask=self.redirect_virtual['netmask'],
484 destinationPort=self.redirect_virtual['port']
485 ),
486 subcollectionResources=self.redirect_profiles
487 )
488 ]
489 return result
490
491 @property
492 def redirect_profiles(self):
493 result = {
494 'profiles:8ba4bb101701': [
495 dict(
496 parameters=dict()
497 )
498 ],
499 'profiles:9448fe71611e': [
500 dict(
501 parameters=dict()
502 )
503 ]
504 }
505 return result
506
507 @property
508 def pool(self):
509 result = dict()
510 result['ltm:pool:be70d46c6d73'] = [
511 dict(
512 parameters=dict(
513 name='pool_0'
514 ),
515 subcollectionResources=self.pool_members
516 )
517 ]
518 return result
519
520 @property
521 def pool_members(self):
522 result = dict()
523 result['members:dec6d24dc625'] = []
524 for x in self.servers:
525 member = dict(
526 parameters=dict(
527 port=x['port'],
528 nodeReference=dict(
529 link='#/resources/ltm:node:45391b57b104/{0}'.format(x['address']),
530 fullPath='# {0}'.format(x['address'])
531 )
532 )
533 )
534 result['members:dec6d24dc625'].append(member)
535 return result
536
537 @property
538 def http_profile(self):
539 result = dict()
540 result['ltm:profile:http:8ba4bb101701'] = [
541 dict(
542 parameters=dict(
543 name='profile_http'
544 )
545 )
546 ]
547 return result
548
549 @property
550 def http_monitor(self):
551 result = dict()
552 result['ltm:monitor:http:fd07629373b0'] = [
553 dict(
554 parameters=dict(
555 name='monitor-http'
556 )
557 )
558 ]
559 return result
560
561 @property
562 def nodes(self):
563 result = dict()
564 result['ltm:node:45391b57b104'] = []
565 for x in self.servers:
566 tmp = dict(
567 parameters=dict(
568 name=x['address'],
569 address=x['address']
570 )
571 )
572 result['ltm:node:45391b57b104'].append(tmp)
573 return result
574
575 @property
576 def node_addresses(self):
577 result = [x['address'] for x in self.servers]
578 return result
579
580 @property
581 def ssl_profile(self):
582 result = dict()
583 result['ltm:profile:client-ssl:14c995c33411'] = [
584 dict(
585 parameters=dict(
586 name='clientssl',
587 certKeyChain=self.cert_key_chains
588 )
589 )
590 ]
591 return result
592
593 def _get_cert_references(self):
594 result = dict()
595 uri = "https://{0}:{1}/mgmt/cm/adc-core/working-config/sys/file/ssl-cert/".format(
596 self.client.provider['server'],
597 self.client.provider['server_port']
598 )
599
600 resp = self.client.api.get(uri)
601 try:
602 response = resp.json()
603 except ValueError as ex:
604 raise F5ModuleError(str(ex))
605 for cert in response['items']:
606 key = fq_name(cert['partition'], cert['name'])
607 result[key] = cert['selfLink']
608 return result
609
610 def _get_key_references(self):
611 result = dict()
612 uri = "https://{0}:{1}/mgmt/cm/adc-core/working-config/sys/file/ssl-key/".format(
613 self.client.provider['server'],
614 self.client.provider['server_port']
615 )
616 resp = self.client.api.get(uri)
617 try:
618 response = resp.json()
619 except ValueError as ex:
620 raise F5ModuleError(str(ex))
621 for cert in response['items']:
622 key = fq_name(cert['partition'], cert['name'])
623 result[key] = cert['selfLink']
624 return result
625
626 @property
627 def cert_key_chains(self):
628 result = []
629 if self.client_ssl_profile is None:
630 return None
631 if 'cert_key_chain' not in self.client_ssl_profile:
632 return None
633
634 kc = self.client_ssl_profile['cert_key_chain']
635 if isinstance(kc, string_types) and kc != 'inherit':
636 raise F5ModuleError(
637 "Only the 'inherit' setting is available when 'cert_key_chain' is a string."
638 )
639
640 if not isinstance(kc, list):
641 raise F5ModuleError(
642 "The value of 'cert_key_chain' is not one of the supported types."
643 )
644
645 cert_references = self._get_cert_references()
646 key_references = self._get_key_references()
647
648 for idx, x in enumerate(kc):
649 tmp = dict(
650 name='clientssl{0}'.format(idx)
651 )
652 if 'cert' not in x:
653 raise F5ModuleError(
654 "A 'cert' option is required when specifying the 'cert_key_chain' parameter.."
655 )
656 elif x['cert'] not in cert_references:
657 raise F5ModuleError(
658 "The specified 'cert' was not found. Did you specify its full path?"
659 )
660 else:
661 key = x['cert']
662 tmp['certReference'] = dict(
663 link=cert_references[key],
664 fullPath=key
665 )
666
667 if 'key' not in x:
668 raise F5ModuleError(
669 "A 'key' option is required when specifying the 'cert_key_chain' parameter.."
670 )
671 elif x['key'] not in key_references:
672 raise F5ModuleError(
673 "The specified 'key' was not found. Did you specify its full path?"
674 )
675 else:
676 key = x['key']
677 tmp['keyReference'] = dict(
678 link=key_references[key],
679 fullPath=key
680 )
681
682 if 'chain' in x and x['chain'] not in cert_references:
683 raise F5ModuleError(
684 "The specified 'key' was not found. Did you specify its full path?"
685 )
686 else:
687 key = x['chain']
688 tmp['chainReference'] = dict(
689 link=cert_references[key],
690 fullPath=key
691 )
692
693 if 'passphrase' in x:
694 tmp['passphrase'] = x['passphrase']
695 result.append(tmp)
696 return result
697
698
699 class ReportableChanges(Changes):
700 pass
701
702
703 class Difference(object):
704 def __init__(self, want, have=None):
705 self.want = want
706 self.have = have
707
708 def compare(self, param):
709 try:
710 result = getattr(self, param)
711 return result
712 except AttributeError:
713 return self.__default(param)
714
715 def __default(self, param):
716 attr1 = getattr(self.want, param)
717 try:
718 attr2 = getattr(self.have, param)
719 if attr1 != attr2:
720 return attr1
721 except AttributeError:
722 return attr1
723
724
725 class ModuleManager(object):
726 def __init__(self, *args, **kwargs):
727 self.module = kwargs.get('module', None)
728 self.client = F5RestClient(**self.module.params)
729 self.want = ModuleParameters(params=self.module.params)
730 self.want.client = self.client
731 self.have = ApiParameters()
732 self.changes = UsableChanges()
733
734 def _set_changed_options(self):
735 changed = {}
736 for key in Parameters.returnables:
737 if getattr(self.want, key) is not None:
738 changed[key] = getattr(self.want, key)
739 if changed:
740 self.changes = UsableChanges(params=changed)
741 self.changes.client = self.client
742
743 def _update_changed_options(self):
744 diff = Difference(self.want, self.have)
745 updatables = Parameters.updatables
746 changed = dict()
747 for k in updatables:
748 change = diff.compare(k)
749 if change is None:
750 continue
751 else:
752 if isinstance(change, dict):
753 changed.update(change)
754 else:
755 changed[k] = change
756 if changed:
757 self.changes = UsableChanges(params=changed)
758 self.changes.client = self.client
759 return True
760 return False
761
762 def should_update(self):
763 result = self._update_changed_options()
764 if result:
765 return True
766 return False
767
768 def check_bigiq_version(self, version):
769 if Version(version) >= Version('6.1.0'):
770 raise F5ModuleError(
771 'Module supports only BIGIQ version 6.0.x or lower.'
772 )
773
774 def exec_module(self):
775 start = datetime.now().isoformat()
776 version = bigiq_version(self.client)
777 self.check_bigiq_version(version)
778 changed = False
779 result = dict()
780 state = self.want.state
781
782 if state == "present":
783 changed = self.present()
784 elif state == "absent":
785 changed = self.absent()
786
787 reportable = ReportableChanges(params=self.changes.to_return())
788 changes = reportable.to_return()
789 result.update(**changes)
790 result.update(dict(changed=changed))
791 self._announce_deprecations(result)
792 send_teem(start, self.client, self.module, version)
793 return result
794
795 def _announce_deprecations(self, result):
796 warnings = result.pop('__warnings', [])
797 for warning in warnings:
798 self.client.module.deprecate(
799 msg=warning['msg'],
800 version=warning['version']
801 )
802
803 def present(self):
804 if self.exists():
805 return False
806 else:
807 return self.create()
808
809 def exists(self):
810 uri = "https://{0}:{1}/mgmt/ap/query/v1/tenants/default/reports/" \
811 "AllApplicationsList?$filter=name+eq+'{2}'".format(self.client.provider['server'],
812 self.client.provider['server_port'], self.want.name)
813 resp = self.client.api.get(uri)
814 try:
815 response = resp.json()
816 except ValueError as ex:
817 raise F5ModuleError(str(ex))
818 if (resp.status == 200 and 'result' in response and
819 'totalItems' in response['result'] and response['result']['totalItems'] == 0):
820 return False
821 return True
822
823 def remove(self):
824 if self.module.check_mode:
825 return True
826 self_link = self.remove_from_device()
827 if self.want.wait:
828 self.wait_for_apply_template_task(self_link)
829 if self.exists():
830 raise F5ModuleError("Failed to delete the resource.")
831 return True
832
833 def has_no_service_environment(self):
834 if self.want.default_device_reference is None and self.want.ssg_reference is None:
835 return True
836 return False
837
838 def create(self):
839 if self.want.service_environment is None:
840 raise F5ModuleError(
841 "A 'service_environment' must be specified when creating a new application."
842 )
843 if self.want.servers is None:
844 raise F5ModuleError(
845 "At least one 'servers' item is needed when creating a new application."
846 )
847 if self.want.inbound_virtual is None:
848 raise F5ModuleError(
849 "An 'inbound_virtual' must be specified when creating a new application."
850 )
851 self._set_changed_options()
852
853 if self.has_no_service_environment():
854 raise F5ModuleError(
855 "The specified 'service_environment' ({0}) was not found.".format(self.want.service_environment)
856 )
857
858 if self.module.check_mode:
859 return True
860 self_link = self.create_on_device()
861 if self.want.wait:
862 self.wait_for_apply_template_task(self_link)
863 if not self.exists():
864 raise F5ModuleError(
865 "Failed to deploy application."
866 )
867 return True
868
869 def create_on_device(self):
870 params = self.changes.api_params()
871 params['mode'] = 'CREATE'
872
873 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
874 self.client.provider['server'],
875 self.client.provider['server_port']
876 )
877
878 resp = self.client.api.post(uri, json=params)
879 try:
880 response = resp.json()
881 except ValueError as ex:
882 raise F5ModuleError(str(ex))
883
884 if 'code' in response and response['code'] == 400:
885 if 'message' in response:
886 raise F5ModuleError(response['message'])
887 else:
888 raise F5ModuleError(resp._content)
889 return response['selfLink']
890
891 def absent(self):
892 if self.exists():
893 return self.remove()
894 return False
895
896 def remove_from_device(self):
897 params = dict(
898 configSetName=self.want.name,
899 mode='DELETE'
900 )
901 uri = 'https://{0}:{1}/mgmt/cm/global/tasks/apply-template'.format(
902 self.client.provider['server'],
903 self.client.provider['server_port']
904 )
905
906 resp = self.client.api.post(uri, json=params)
907 try:
908 response = resp.json()
909 except ValueError as ex:
910 raise F5ModuleError(str(ex))
911
912 if 'code' in response and response['code'] == 400:
913 if 'message' in response:
914 raise F5ModuleError(response['message'])
915 else:
916 raise F5ModuleError(resp._content)
917 return response['selfLink']
918
919 def wait_for_apply_template_task(self, self_link):
920 host = 'https://{0}:{1}'.format(
921 self.client.provider['server'],
922 self.client.provider['server_port']
923 )
924 uri = self_link.replace('https://localhost', host)
925
926 while True:
927 resp = self.client.api.get(uri)
928 try:
929 response = resp.json()
930 except ValueError as ex:
931 raise F5ModuleError(str(ex))
932
933 if response['status'] == 'FINISHED' and response.get('currentStep', None) == 'DONE':
934 return True
935 elif 'errorMessage' in response:
936 raise F5ModuleError(response['errorMessage'])
937 time.sleep(5)
938
939
940 class ArgumentSpec(object):
941 def __init__(self):
942 self.supports_check_mode = True
943 argument_spec = dict(
944 name=dict(required=True),
945 description=dict(),
946 servers=dict(
947 type='list',
948 elements='dict',
949 options=dict(
950 address=dict(required=True),
951 port=dict(type='int', default=80)
952 )
953 ),
954 inbound_virtual=dict(
955 type='dict',
956 options=dict(
957 address=dict(required=True),
958 netmask=dict(required=True),
959 port=dict(type='int', default=443)
960 )
961 ),
962 redirect_virtual=dict(
963 type='dict',
964 options=dict(
965 address=dict(required=True),
966 netmask=dict(required=True),
967 port=dict(type='int', default=80)
968 )
969 ),
970 service_environment=dict(),
971 state=dict(
972 default='present',
973 choices=['present', 'absent']
974 ),
975 client_ssl_profile=dict(
976 type='dict',
977 options=dict(
978 name=dict(default='clientssl'),
979 cert_key_chain=dict(
980 type='raw',
981 no_log=True,
982 options=dict(
983 cert=dict(),
984 key=dict(no_log=True),
985 chain=dict(),
986 passphrase=dict(no_log=True)
987 )
988 )
989 )
990 ),
991 add_analytics=dict(type='bool', default='no'),
992 wait=dict(type='bool', default='yes')
993 )
994 self.argument_spec = {}
995 self.argument_spec.update(f5_argument_spec)
996 self.argument_spec.update(argument_spec)
997
998
999 def main():
1000 spec = ArgumentSpec()
1001
1002 module = AnsibleModule(
1003 argument_spec=spec.argument_spec,
1004 supports_check_mode=spec.supports_check_mode,
1005 )
1006
1007 if not HAS_PACKAGING:
1008 module.fail_json(
1009 msg=missing_required_lib('packaging'),
1010 exception=PACKAGING_IMPORT_ERROR
1011 )
1012
1013 try:
1014 mm = ModuleManager(module=module)
1015 results = mm.exec_module()
1016 module.exit_json(**results)
1017 except F5ModuleError as ex:
1018 module.fail_json(msg=str(ex))
1019
1020
1021 if __name__ == '__main__':
1022 main()