Debian Codegraph @

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