Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_gtm_server.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, 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: bigip_gtm_server
13 short_description: Manages F5 BIG-IP GTM servers
14 description:
15 - Manage BIG-IP GTM (now BIG-IP DNS) server configuration. This module is able to manipulate the server
16 definitions in a BIG-IP.
17 version_added: "1.0.0"
18 options:
19 name:
20 description:
21 - The name of the server.
22 - If the virtual server is auto-discovered from the LTM,then the partition name needs to be included as
23 part of the virtual server name when referencing from the module e.g. "/Common/vsname".
24 type: str
25 required: True
26 state:
27 description:
28 - The server state. If C(absent), the module attempts to delete the server.
29 This will only succeed if this server is not in use by a virtual server.
30 C(present) creates the server and enables it. If C(enabled), enables the server
31 if it exists. If C(disabled), creates the server if needed, and sets state to
32 C(disabled).
33 type: str
34 choices:
35 - present
36 - absent
37 - enabled
38 - disabled
39 default: present
40 datacenter:
41 description:
42 - Data center to which the server belongs. When creating a new GTM server, this value
43 is required.
44 type: str
45 devices:
46 description:
47 - Lists the self IP addresses and translations for each device. When creating a
48 new GTM server, this value is required. This list is a complex list that
49 specifies a number of keys.
50 - The C(name) key specifies a name for the device. The device name must
51 be unique per server. This key is required.
52 - The C(address) key contains an IP address, or list of IP addresses, for the
53 destination server. This key is required.
54 - The C(translation) key contains an IP address to translate the C(address)
55 value above to. This key is optional.
56 - Specifying duplicate C(name) fields is a supported means of providing device
57 addresses. In this scenario, the addresses will be assigned to the C(name)'s list
58 of addresses.
59 type: raw
60 server_type:
61 description:
62 - Specifies the server type. The server type determines the metrics the
63 system can collect from the server. When creating a new GTM server, the default
64 value C(bigip) is used.
65 type: str
66 choices:
67 - alteon-ace-director
68 - cisco-css
69 - cisco-server-load-balancer
70 - generic-host
71 - radware-wsd
72 - windows-nt-4.0
73 - bigip
74 - cisco-local-director-v2
75 - extreme
76 - generic-load-balancer
77 - sun-solaris
78 - cacheflow
79 - cisco-local-director-v3
80 - foundry-server-iron
81 - netapp
82 - windows-2000-server
83 aliases:
84 - product
85 link_discovery:
86 description:
87 - Specifies whether the system auto-discovers the links for this server. When
88 creating a new GTM server, if this parameter is not specified, the default
89 value C(disabled) is used.
90 - If you set this parameter to C(enabled) or C(enabled-no-delete), you must
91 also ensure the C(virtual_server_discovery) parameter is also set to
92 C(enabled) or C(enabled-no-delete).
93 type: str
94 choices:
95 - enabled
96 - disabled
97 - enabled-no-delete
98 virtual_server_discovery:
99 description:
100 - Specifies whether the system auto-discovers the virtual servers for this server.
101 When creating a new GTM server, if this parameter is not specified, the default
102 value C(disabled) is used.
103 type: str
104 choices:
105 - enabled
106 - disabled
107 - enabled-no-delete
108 partition:
109 description:
110 - Device partition to manage resources on.
111 type: str
112 default: Common
113 iquery_options:
114 description:
115 - Specifies whether the Global Traffic Manager uses this BIG-IP
116 system to conduct a variety of probes before delegating traffic to it.
117 suboptions:
118 allow_path:
119 description:
120 - Specifies the system verifies the logical network route between a data
121 center server and a local DNS server.
122 type: bool
123 allow_service_check:
124 description:
125 - Specifies the system verifies that an application on a server is running,
126 by remotely running the application using an external service checker program.
127 type: bool
128 allow_snmp:
129 description:
130 - Specifies the system checks the performance of a server running an SNMP
131 agent.
132 type: bool
133 type: dict
134 monitors:
135 description:
136 - Specifies the health monitors the system currently uses to monitor this resource.
137 - When C(availability_requirements.type) is C(require), you may only have a single monitor in the
138 C(monitors) list.
139 type: list
140 elements: str
141 availability_requirements:
142 description:
143 - If you activate more than one health monitor, specifies the number of health
144 monitors that must receive successful responses in order for the link to be
145 considered available.
146 type: dict
147 suboptions:
148 type:
149 description:
150 - Monitor rule type when C(monitors) is specified.
151 - When creating a new pool, if this value is not specified, the default of B(all) will be used.
152 type: str
153 required: True
154 choices:
155 - all
156 - at_least
157 - require
158 at_least:
159 description:
160 - Specifies the minimum number of active health monitors that must be successful
161 before the link is considered up.
162 - This parameter is only relevant when a C(type) of C(at_least) is used.
163 - This parameter will be ignored if a type of either C(all) or C(require) is used.
164 type: int
165 number_of_probes:
166 description:
167 - Specifies the minimum number of probes that must succeed for this server to be declared up.
168 - When creating a new virtual server, if this parameter is specified, then the C(number_of_probers)
169 parameter must also be specified.
170 - The value of this parameter should always be B(lower) than, or B(equal to),
171 the value of C(number_of_probers).
172 - This parameter is only relevant when a C(type) of C(require) is used.
173 - This parameter will be ignored if a type of either C(all) or C(at_least) is used.
174 type: int
175 number_of_probers:
176 description:
177 - Specifies the number of probers that should be used when running probes.
178 - When creating a new virtual server, if this parameter is specified, the C(number_of_probes)
179 parameter must also be specified.
180 - The value of this parameter should always be B(higher) than, or B(equal to),
181 the value of C(number_of_probers).
182 - This parameter is only relevant when a C(type) of C(require) is used.
183 - This parameter will be ignored if a type of either C(all) or C(at_least) is used.
184 type: int
185 prober_preference:
186 description:
187 - Specifies the type of prober to use to monitor this server's resources.
188 - This option is ignored in C(TMOS) version C(12.x).
189 - From C(TMOS) version C(13.x) and up, when prober_preference is set to C(pool)
190 a C(prober_pool) parameter must be specified.
191 type: str
192 choices:
193 - inside-datacenter
194 - outside-datacenter
195 - inherit
196 - pool
197 prober_fallback:
198 description:
199 - Specifies the type of prober to use to monitor this server's resources
200 when the preferred prober is not available.
201 - This option is ignored in C(TMOS) version C(12.x).
202 - From C(TMOS) version C(13.x) and up, when prober_preference is set to C(pool)
203 a C(prober_pool) parameter must be specified.
204 - The choices are mutually exclusive with prober_preference parameter,
205 with the exception of the C(any-available) or C(none) options.
206 type: str
207 choices:
208 - any
209 - inside-datacenter
210 - outside-datacenter
211 - inherit
212 - pool
213 - none
214 prober_pool:
215 description:
216 - Specifies the name of the prober pool to use to monitor this server's resources.
217 - In C(TMOS) version C(13.x) and later, this parameter is mandatory when C(prober_preference) is set to C(pool).
218 - The format of the name can be either be prepended by partition (C(/Common/foo)), or specified
219 just as an object name (C(foo)).
220 - In C(TMOS) version C(12.x), prober_pool can be set to an empty string to revert to default setting of C(inherit).
221 type: str
222 limits:
223 description:
224 - Specifies resource thresholds or limit requirements at the pool member level.
225 - When you enable one or more limit settings, the system then uses that data to take
226 members in and out of service.
227 - You can define limits for any or all of the limit settings. However, when a
228 member does not meet the resource threshold limit requirement, the system marks
229 the member as unavailable and directs load balancing traffic to another resource.
230 suboptions:
231 bits_enabled:
232 description:
233 - Whether the bits limit it enabled or not.
234 - This parameter allows you to switch on or off the effect of the limit.
235 type: bool
236 packets_enabled:
237 description:
238 - Whether the packets limit it enabled or not.
239 - This parameter allows you to switch on or off the effect of the limit.
240 type: bool
241 connections_enabled:
242 description:
243 - Whether the current connections limit it enabled or not.
244 - This parameter allows you to switch on or off the effect of the limit.
245 type: bool
246 cpu_enabled:
247 description:
248 - Whether the CPU limit it enabled or not.
249 - This parameter allows you to switch on or off the effect of the limit.
250 type: bool
251 memory_enabled:
252 description:
253 - Whether the memory limit it enabled or not.
254 - This parameter allows you to switch on or off the effect of the limit.
255 type: bool
256 bits_limit:
257 description:
258 - Specifies the maximum allowable data throughput rate for the member,
259 in bits per second.
260 - If the network traffic volume exceeds this limit, the system marks the
261 member as unavailable.
262 type: int
263 packets_limit:
264 description:
265 - Specifies the maximum allowable data transfer rate for the member,
266 in packets per second.
267 - If the network traffic volume exceeds this limit, the system marks the
268 member as unavailable.
269 type: int
270 connections_limit:
271 description:
272 - Specifies the maximum number of concurrent connections, combined, for all of
273 the members.
274 - If the connections exceed this limit, the system marks the server as
275 unavailable.
276 type: int
277 cpu_limit:
278 description:
279 - Specifies the percent of CPU usage.
280 - If percent of CPU usage goes above the limit, the system marks the server as unavailable.
281 type: int
282 memory_limit:
283 description:
284 - Specifies the available memory required by the virtual servers on the server.
285 - If available memory falls below this limit, the system marks the server as unavailable.
286 type: int
287 type: dict
288 extends_documentation_fragment: f5networks.f5_modules.f5
289 author:
290 - Robert Teller (@r-teller)
291 - Tim Rupp (@caphrim007)
292 - Wojciech Wypior (@wojtek0806)
293 '''
294
295 EXAMPLES = r'''
296 - name: Create server "GTM_Server"
297 bigip_gtm_server:
298 name: GTM_Server
299 datacenter: /Common/New York
300 server_type: bigip
301 link_discovery: disabled
302 virtual_server_discovery: disabled
303 devices:
304 - name: server_1
305 address: 1.1.1.1
306 - name: server_2
307 address: 2.2.2.1
308 translation: 192.168.2.1
309 - name: server_2
310 address: 2.2.2.2
311 - name: server_3
312 addresses:
313 - address: 3.3.3.1
314 - address: 3.3.3.2
315 - name: server_4
316 addresses:
317 - address: 4.4.4.1
318 translation: 192.168.14.1
319 - address: 4.4.4.2
320 provider:
321 user: admin
322 password: secret
323 server: lb.mydomain.com
324 delegate_to: localhost
325
326 - name: Create server "GTM_Server" with expanded keys
327 bigip_gtm_server:
328 server: lb.mydomain.com
329 user: admin
330 password: secret
331 name: GTM_Server
332 datacenter: /Common/New York
333 server_type: bigip
334 link_discovery: disabled
335 virtual_server_discovery: disabled
336 devices:
337 - name: server_1
338 address: 1.1.1.1
339 - name: server_2
340 address: 2.2.2.1
341 translation: 192.168.2.1
342 - name: server_2
343 address: 2.2.2.2
344 - name: server_3
345 addresses:
346 - address: 3.3.3.1
347 - address: 3.3.3.2
348 - name: server_4
349 addresses:
350 - address: 4.4.4.1
351 translation: 192.168.14.1
352 - address: 4.4.4.2
353 provider:
354 user: admin
355 password: secret
356 server: lb.mydomain.com
357 delegate_to: localhost
358 '''
359
360 RETURN = r'''
361 bits_enabled:
362 description: Whether the bits limit is enabled.
363 returned: changed
364 type: bool
365 sample: true
366 bits_limit:
367 description: The new bits_enabled limit.
368 returned: changed
369 type: int
370 sample: 100
371 connections_enabled:
372 description: Whether the connections limit is enabled.
373 returned: changed
374 type: bool
375 sample: true
376 connections_limit:
377 description: The new connections_limit limit.
378 returned: changed
379 type: int
380 sample: 100
381 monitors:
382 description: The new list of monitors for the resource.
383 returned: changed
384 type: list
385 sample: ['/Common/monitor1', '/Common/monitor2']
386 link_discovery:
387 description: The new C(link_discovery) configured on the remote device.
388 returned: changed
389 type: str
390 sample: enabled
391 virtual_server_discovery:
392 description: The new C(virtual_server_discovery) name for the trap destination.
393 returned: changed
394 type: str
395 sample: disabled
396 server_type:
397 description: The new type of the server.
398 returned: changed
399 type: str
400 sample: bigip
401 datacenter:
402 description: The new C(datacenter) which the server is a part of.
403 returned: changed
404 type: str
405 sample: datacenter01
406 packets_enabled:
407 description: Whether the packets limit is enabled.
408 returned: changed
409 type: bool
410 sample: true
411 packets_limit:
412 description: The new packets_limit limit.
413 returned: changed
414 type: int
415 sample: 100
416 '''
417
418 import re
419 import traceback
420 from datetime import datetime
421
422 try:
423 from packaging.version import Version
424 except ImportError:
425 HAS_PACKAGING = False
426 Version = None
427 PACKAGING_IMPORT_ERROR = traceback.format_exc()
428 else:
429 HAS_PACKAGING = True
430 PACKAGING_IMPORT_ERROR = None
431
432 from ansible.module_utils.basic import (
433 AnsibleModule, env_fallback, missing_required_lib
434 )
435
436 from ..module_utils.bigip import F5RestClient
437 from ..module_utils.common import (
438 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, is_empty_list, fq_name
439 )
440 from ..module_utils.icontrol import (
441 module_provisioned, tmos_version
442 )
443 from ..module_utils.teem import send_teem
444
445 try:
446 from collections import OrderedDict
447 except ImportError:
448 try:
449 from ordereddict import OrderedDict
450 except ImportError:
451 pass
452
453
454 class Parameters(AnsibleF5Parameters):
455 api_map = {
456 'product': 'server_type',
457 'virtualServerDiscovery': 'virtual_server_discovery',
458 'linkDiscovery': 'link_discovery',
459 'addresses': 'devices',
460 'iqAllowPath': 'iquery_allow_path',
461 'iqAllowServiceCheck': 'iquery_allow_service_check',
462 'iqAllowSnmp': 'iquery_allow_snmp',
463 'monitor': 'monitors',
464 'proberPreference': 'prober_preference',
465 'proberPool': 'prober_pool',
466 'proberFallback': 'prober_fallback',
467 'limitMaxBps': 'bits_limit',
468 'limitMaxBpsStatus': 'bits_enabled',
469 'limitMaxConnections': 'connections_limit',
470 'limitMaxConnectionsStatus': 'connections_enabled',
471 'limitMaxPps': 'packets_limit',
472 'limitMaxPpsStatus': 'packets_enabled',
473 'limitCpuUsage': 'cpu_limit',
474 'limitCpuUsageStatus': 'cpu_enabled',
475 'limitMemAvail': 'memory_limit',
476 'limitMemAvailStatus': 'memory_enabled',
477 }
478
479 api_attributes = [
480 'linkDiscovery',
481 'virtualServerDiscovery',
482 'product',
483 'addresses',
484 'datacenter',
485 'enabled',
486 'disabled',
487 'iqAllowPath',
488 'iqAllowServiceCheck',
489 'iqAllowSnmp',
490 'monitor',
491 'proberPreference',
492 'proberPool',
493 'proberFallback',
494 'limitMaxBps',
495 'limitMaxBpsStatus',
496 'limitMaxConnections',
497 'limitMaxConnectionsStatus',
498 'limitMaxPps',
499 'limitMaxPpsStatus',
500 'limitCpuUsage',
501 'limitCpuUsageStatus',
502 'limitMemAvail',
503 'limitMemAvailStatus',
504 ]
505
506 updatables = [
507 'link_discovery',
508 'virtual_server_discovery',
509 'server_type_and_devices',
510 'datacenter',
511 'state',
512 'iquery_allow_path',
513 'iquery_allow_service_check',
514 'iquery_allow_snmp',
515 'monitors',
516 'prober_preference',
517 'prober_pool',
518 'prober_fallback',
519 'bits_enabled',
520 'bits_limit',
521 'connections_enabled',
522 'connections_limit',
523 'packets_enabled',
524 'packets_limit',
525 'cpu_enabled',
526 'cpu_limit',
527 'memory_enabled',
528 'memory_limit',
529 ]
530
531 returnables = [
532 'link_discovery',
533 'virtual_server_discovery',
534 'server_type',
535 'datacenter',
536 'enabled',
537 'iquery_allow_path',
538 'iquery_allow_service_check',
539 'iquery_allow_snmp',
540 'devices',
541 'monitors',
542 'availability_requirements',
543 'prober_preference',
544 'prober_pool',
545 'prober_fallback',
546 'bits_enabled',
547 'bits_limit',
548 'connections_enabled',
549 'connections_limit',
550 'packets_enabled',
551 'packets_limit',
552 'cpu_enabled',
553 'cpu_limit',
554 'memory_enabled',
555 'memory_limit',
556 ]
557
558
559 class ApiParameters(Parameters):
560 @property
561 def devices(self):
562 if self._values['devices'] is None:
563 return None
564 return self._values['devices']
565
566 @property
567 def server_type(self):
568 if self._values['server_type'] is None:
569 return None
570 elif self._values['server_type'] in ['single-bigip', 'redundant-bigip']:
571 return 'bigip'
572 else:
573 return self._values['server_type']
574
575 @property
576 def raw_server_type(self):
577 if self._values['server_type'] is None:
578 return None
579 return self._values['server_type']
580
581 @property
582 def enabled(self):
583 if self._values['enabled'] is None:
584 return None
585 return True
586
587 @property
588 def disabled(self):
589 if self._values['disabled'] is None:
590 return None
591 return True
592
593 @property
594 def iquery_allow_path(self):
595 if self._values['iquery_allow_path'] is None:
596 return None
597 elif self._values['iquery_allow_path'] == 'yes':
598 return True
599 return False
600
601 @property
602 def iquery_allow_service_check(self):
603 if self._values['iquery_allow_service_check'] is None:
604 return None
605 elif self._values['iquery_allow_service_check'] == 'yes':
606 return True
607 return False
608
609 @property
610 def iquery_allow_snmp(self):
611 if self._values['iquery_allow_snmp'] is None:
612 return None
613 elif self._values['iquery_allow_snmp'] == 'yes':
614 return True
615 return False
616
617 @property
618 def availability_requirement_type(self):
619 if self._values['monitors'] is None:
620 return None
621 if 'min ' in self._values['monitors']:
622 return 'at_least'
623 elif 'require ' in self._values['monitors']:
624 return 'require'
625 else:
626 return 'all'
627
628 @property
629 def monitors_list(self):
630 if self._values['monitors'] is None:
631 return []
632 try:
633 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
634 result.sort()
635 return result
636 except Exception:
637 return self._values['monitors']
638
639 @property
640 def monitors(self):
641 if self._values['monitors'] is None:
642 return None
643 if self._values['monitors'] == '/Common/bigip':
644 return '/Common/bigip'
645 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
646 if self.availability_requirement_type == 'at_least':
647 monitors = ' '.join(monitors)
648 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
649 elif self.availability_requirement_type == 'require':
650 monitors = ' '.join(monitors)
651 result = 'require {0} from {1} {{ {2} }}'.format(self.number_of_probes, self.number_of_probers, monitors)
652 else:
653 result = ' and '.join(monitors).strip()
654 return result
655
656 @property
657 def number_of_probes(self):
658 """Returns the probes value from the monitor string.
659
660 The monitor string for a Require monitor looks like this.
661
662 require 1 from 2 { /Common/tcp }
663
664 This method parses out the first of the numeric values. This values represents
665 the "probes" value that can be updated in the module.
666
667 Returns:
668 int: The probes value if found. None otherwise.
669 """
670 if self._values['monitors'] is None:
671 return None
672 pattern = r'require\s+(?P<probes>\d+)\s+from'
673 matches = re.search(pattern, self._values['monitors'])
674 if matches is None:
675 return None
676 return matches.group('probes')
677
678 @property
679 def number_of_probers(self):
680 """Returns the probers value from the monitor string.
681
682 The monitor string for a Require monitor looks like this.
683
684 require 1 from 2 { /Common/tcp }
685
686 This method parses out the first of the numeric values. This values represents
687 the "probers" value that can be updated in the module.
688
689 Returns:
690 int: The probers value if found. None otherwise.
691 """
692 if self._values['monitors'] is None:
693 return None
694 pattern = r'require\s+\d+\s+from\s+(?P<probers>\d+)\s+'
695 matches = re.search(pattern, self._values['monitors'])
696 if matches is None:
697 return None
698 return matches.group('probers')
699
700 @property
701 def at_least(self):
702 """Returns the 'at least' value from the monitor string.
703
704 The monitor string for a Require monitor looks like this.
705
706 min 1 of { /Common/gateway_icmp }
707
708 This method parses out the first of the numeric values. This values represents
709 the "at_least" value that can be updated in the module.
710
711 Returns:
712 int: The at_least value if found. None otherwise.
713 """
714 if self._values['monitors'] is None:
715 return None
716 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
717 matches = re.search(pattern, self._values['monitors'])
718 if matches is None:
719 return None
720 return matches.group('least')
721
722
723 class ModuleParameters(Parameters):
724 def _get_limit_value(self, type):
725 if self._values['limits'] is None:
726 return None
727 if self._values['limits'][type] is None:
728 return None
729 return int(self._values['limits'][type])
730
731 def _get_limit_status(self, type):
732 if self._values['limits'] is None:
733 return None
734 if self._values['limits'][type] is None:
735 return None
736 if self._values['limits'][type]:
737 return 'enabled'
738 return 'disabled'
739
740 @property
741 def devices(self):
742 if self._values['devices'] is None:
743 return None
744 result = []
745
746 for device in self._values['devices']:
747 if not any(x for x in ['address', 'addresses'] if x in device):
748 raise F5ModuleError(
749 "The specified device list must contain an 'address' or 'addresses' key"
750 )
751
752 if 'address' in device:
753 translation = self._determine_translation(device)
754 name = device['address']
755 device_name = device['name']
756 result.append({
757 'name': name,
758 'deviceName': device_name,
759 'translation': translation
760 })
761 elif 'addresses' in device:
762 for address in device['addresses']:
763 translation = self._determine_translation(address)
764 name = address['address']
765 device_name = device['name']
766 result.append({
767 'name': name,
768 'deviceName': device_name,
769 'translation': translation
770 })
771 return result
772
773 @property
774 def enabled(self):
775 if self._values['state'] in ['present', 'enabled']:
776 return True
777 return False
778
779 @property
780 def datacenter(self):
781 if self._values['datacenter'] is None:
782 return None
783 return fq_name(self.partition, self._values['datacenter'])
784
785 def _determine_translation(self, device):
786 if 'translation' not in device:
787 return 'none'
788 return device['translation']
789
790 @property
791 def state(self):
792 if self._values['state'] == 'enabled':
793 return 'present'
794 return self._values['state']
795
796 @property
797 def iquery_allow_path(self):
798 if self._values['iquery_options'] is None:
799 return None
800 elif self._values['iquery_options']['allow_path'] is None:
801 return None
802 return self._values['iquery_options']['allow_path']
803
804 @property
805 def iquery_allow_service_check(self):
806 if self._values['iquery_options'] is None:
807 return None
808 elif self._values['iquery_options']['allow_service_check'] is None:
809 return None
810 return self._values['iquery_options']['allow_service_check']
811
812 @property
813 def iquery_allow_snmp(self):
814 if self._values['iquery_options'] is None:
815 return None
816 elif self._values['iquery_options']['allow_snmp'] is None:
817 return None
818 return self._values['iquery_options']['allow_snmp']
819
820 @property
821 def monitors_list(self):
822 if self._values['monitors'] is None:
823 return []
824 try:
825 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
826 result.sort()
827 return result
828 except Exception:
829 return self._values['monitors']
830
831 @property
832 def monitors(self):
833 if self._values['monitors'] is None:
834 return None
835 if is_empty_list(self._values['monitors']):
836 return '/Common/bigip'
837 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
838 if self.availability_requirement_type == 'at_least':
839 if self.at_least > len(self.monitors_list):
840 raise F5ModuleError(
841 "The 'at_least' value must not exceed the number of 'monitors'."
842 )
843 monitors = ' '.join(monitors)
844 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
845 elif self.availability_requirement_type == 'require':
846 monitors = ' '.join(monitors)
847 if self.number_of_probes > self.number_of_probers:
848 raise F5ModuleError(
849 "The 'number_of_probes' must not exceed the 'number_of_probers'."
850 )
851 result = 'require {0} from {1} {{ {2} }}'.format(self.number_of_probes, self.number_of_probers, monitors)
852 else:
853 result = ' and '.join(monitors).strip()
854
855 return result
856
857 def _get_availability_value(self, type):
858 if self._values['availability_requirements'] is None:
859 return None
860 if self._values['availability_requirements'][type] is None:
861 return None
862 return int(self._values['availability_requirements'][type])
863
864 @property
865 def availability_requirement_type(self):
866 if self._values['availability_requirements'] is None:
867 return None
868 return self._values['availability_requirements']['type']
869
870 @property
871 def number_of_probes(self):
872 return self._get_availability_value('number_of_probes')
873
874 @property
875 def number_of_probers(self):
876 return self._get_availability_value('number_of_probers')
877
878 @property
879 def at_least(self):
880 return self._get_availability_value('at_least')
881
882 @property
883 def prober_pool(self):
884 if self._values['prober_pool'] is None:
885 return None
886 if self._values['prober_pool'] == '':
887 return self._values['prober_pool']
888 result = fq_name(self.partition, self._values['prober_pool'])
889 return result
890
891 @property
892 def prober_fallback(self):
893 if self._values['prober_fallback'] == 'any':
894 return 'any-available'
895 return self._values['prober_fallback']
896
897 @property
898 def bits_limit(self):
899 return self._get_limit_value('bits_limit')
900
901 @property
902 def packets_limit(self):
903 return self._get_limit_value('packets_limit')
904
905 @property
906 def connections_limit(self):
907 return self._get_limit_value('connections_limit')
908
909 @property
910 def cpu_limit(self):
911 return self._get_limit_value('cpu_limit')
912
913 @property
914 def memory_limit(self):
915 return self._get_limit_value('memory_limit')
916
917 @property
918 def bits_enabled(self):
919 return self._get_limit_status('bits_enabled')
920
921 @property
922 def packets_enabled(self):
923 return self._get_limit_status('packets_enabled')
924
925 @property
926 def connections_enabled(self):
927 return self._get_limit_status('connections_enabled')
928
929 @property
930 def cpu_enabled(self):
931 return self._get_limit_status('cpu_enabled')
932
933 @property
934 def memory_enabled(self):
935 return self._get_limit_status('memory_enabled')
936
937
938 class Changes(Parameters):
939 def to_return(self):
940 result = {}
941 try:
942 for returnable in self.returnables:
943 result[returnable] = getattr(self, returnable)
944 result = self._filter_params(result)
945 except Exception:
946 raise
947 return result
948
949
950 class UsableChanges(Changes):
951 @property
952 def monitors(self):
953 monitor_string = self._values['monitors']
954 if monitor_string is None:
955 return None
956
957 if '{' in monitor_string and '}' in monitor_string:
958 tmp = monitor_string.strip('}').split('{')
959 monitor = ''.join(tmp).rstrip()
960 return monitor
961
962 return monitor_string
963
964 @property
965 def iquery_allow_path(self):
966 if self._values['iquery_allow_path'] is None:
967 return None
968 elif self._values['iquery_allow_path']:
969 return 'yes'
970 return 'no'
971
972 @property
973 def iquery_allow_service_check(self):
974 if self._values['iquery_allow_service_check'] is None:
975 return None
976 elif self._values['iquery_allow_service_check']:
977 return 'yes'
978 return 'no'
979
980 @property
981 def iquery_allow_snmp(self):
982 if self._values['iquery_allow_snmp'] is None:
983 return None
984 elif self._values['iquery_allow_snmp']:
985 return 'yes'
986 return 'no'
987
988
989 class ReportableChanges(Changes):
990 @property
991 def server_type(self):
992 if self._values['server_type'] in ['single-bigip', 'redundant-bigip']:
993 return 'bigip'
994 return self._values['server_type']
995
996 @property
997 def monitors(self):
998 if self._values['monitors'] is None:
999 return []
1000 try:
1001 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
1002 result.sort()
1003 return result
1004 except Exception:
1005 return self._values['monitors']
1006
1007 @property
1008 def availability_requirement_type(self):
1009 if self._values['monitors'] is None:
1010 return None
1011 if 'min ' in self._values['monitors']:
1012 return 'at_least'
1013 elif 'require ' in self._values['monitors']:
1014 return 'require'
1015 else:
1016 return 'all'
1017
1018 @property
1019 def number_of_probes(self):
1020 """Returns the probes value from the monitor string.
1021
1022 The monitor string for a Require monitor looks like this.
1023
1024 require 1 from 2 { /Common/tcp }
1025
1026 This method parses out the first of the numeric values. This values represents
1027 the "probes" value that can be updated in the module.
1028
1029 Returns:
1030 int: The probes value if found. None otherwise.
1031 """
1032 if self._values['monitors'] is None:
1033 return None
1034 pattern = r'require\s+(?P<probes>\d+)\s+from'
1035 matches = re.search(pattern, self._values['monitors'])
1036 if matches is None:
1037 return None
1038 return int(matches.group('probes'))
1039
1040 @property
1041 def number_of_probers(self):
1042 """Returns the probers value from the monitor string.
1043
1044 The monitor string for a Require monitor looks like this.
1045
1046 require 1 from 2 { /Common/tcp }
1047
1048 This method parses out the first of the numeric values. This values represents
1049 the "probers" value that can be updated in the module.
1050
1051 Returns:
1052 int: The probers value if found. None otherwise.
1053 """
1054 if self._values['monitors'] is None:
1055 return None
1056 pattern = r'require\s+\d+\s+from\s+(?P<probers>\d+)\s+'
1057 matches = re.search(pattern, self._values['monitors'])
1058 if matches is None:
1059 return None
1060 return int(matches.group('probers'))
1061
1062 @property
1063 def at_least(self):
1064 """Returns the 'at least' value from the monitor string.
1065
1066 The monitor string for a Require monitor looks like this.
1067
1068 min 1 of { /Common/gateway_icmp }
1069
1070 This method parses out the first of the numeric values. This values represents
1071 the "at_least" value that can be updated in the module.
1072
1073 Returns:
1074 int: The at_least value if found. None otherwise.
1075 """
1076 if self._values['monitors'] is None:
1077 return None
1078 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
1079 matches = re.search(pattern, self._values['monitors'])
1080 if matches is None:
1081 return None
1082 return int(matches.group('least'))
1083
1084 @property
1085 def availability_requirements(self):
1086 if self._values['monitors'] is None:
1087 return None
1088 result = dict()
1089 result['type'] = self.availability_requirement_type
1090 result['at_least'] = self.at_least
1091 result['number_of_probers'] = self.number_of_probers
1092 result['number_of_probes'] = self.number_of_probes
1093 return result
1094
1095 @property
1096 def prober_fallback(self):
1097 if self._values['prober_fallback'] == 'any-available':
1098 return 'any'
1099 return self._values['prober_fallback']
1100
1101
1102 class Difference(object):
1103 def __init__(self, want, have=None):
1104 self.want = want
1105 self.have = have
1106
1107 def compare(self, param):
1108 try:
1109 result = getattr(self, param)
1110 return result
1111 except AttributeError:
1112 return self.__default(param)
1113
1114 def __default(self, param):
1115 want = getattr(self.want, param)
1116 try:
1117 have = getattr(self.have, param)
1118 if want != have:
1119 return want
1120 except AttributeError:
1121 return want
1122
1123 def _discovery_constraints(self):
1124 if self.want.virtual_server_discovery is None:
1125 virtual_server_discovery = self.have.virtual_server_discovery
1126 else:
1127 virtual_server_discovery = self.want.virtual_server_discovery
1128
1129 if self.want.link_discovery is None:
1130 link_discovery = self.have.link_discovery
1131 else:
1132 link_discovery = self.want.link_discovery
1133
1134 if link_discovery in ['enabled', 'enabled-no-delete'] and virtual_server_discovery == 'disabled':
1135 raise F5ModuleError(
1136 "Virtual server discovery must be enabled if link discovery is enabled"
1137 )
1138
1139 def _devices_changed(self):
1140 if self.want.devices is None and self.want.server_type is None:
1141 return None
1142 if self.want.devices is None:
1143 devices = self.have.devices
1144 else:
1145 devices = self.want.devices
1146 if self.have.devices is None:
1147 have_devices = []
1148 else:
1149 have_devices = self.have.devices
1150 if len(devices) == 0:
1151 raise F5ModuleError(
1152 "A GTM server must have at least one device associated with it."
1153 )
1154 want = [OrderedDict(sorted(d.items())) for d in devices]
1155 have = [OrderedDict(sorted(d.items())) for d in have_devices]
1156 if len(have_devices) > 0:
1157 if self._false_positive(devices, have_devices):
1158 return False
1159 if want != have:
1160 return True
1161 return False
1162
1163 def _false_positive(self, devices, have_devices):
1164 match = 0
1165 for w in devices:
1166 for h in have_devices:
1167 if w.items() == h.items():
1168 match = match + 1
1169 if match == len(devices):
1170 return True
1171
1172 def _server_type_changed(self):
1173 if self.want.server_type is None:
1174 self.want.update({'server_type': self.have.server_type})
1175 if self.want.server_type != self.have.server_type:
1176 return True
1177 return False
1178
1179 @property
1180 def link_discovery(self):
1181 self._discovery_constraints()
1182 if self.want.link_discovery != self.have.link_discovery:
1183 return self.want.link_discovery
1184
1185 @property
1186 def virtual_server_discovery(self):
1187 self._discovery_constraints()
1188 if self.want.virtual_server_discovery != self.have.virtual_server_discovery:
1189 return self.want.virtual_server_discovery
1190
1191 def _handle_current_server_type_and_devices(self, devices_change, server_change):
1192 result = {}
1193 if devices_change:
1194 result['devices'] = self.want.devices
1195 if server_change:
1196 result['server_type'] = self.want.server_type
1197 return result
1198
1199 def _handle_legacy_server_type_and_devices(self, devices_change, server_change):
1200 result = {}
1201 if server_change and devices_change:
1202 result['devices'] = self.want.devices
1203 if len(self.want.devices) > 1 and self.want.server_type == 'bigip':
1204 if self.have.raw_server_type != 'redundant-bigip':
1205 result['server_type'] = 'redundant-bigip'
1206 elif self.want.server_type == 'bigip':
1207 if self.have.raw_server_type != 'single-bigip':
1208 result['server_type'] = 'single-bigip'
1209 else:
1210 result['server_type'] = self.want.server_type
1211
1212 elif devices_change:
1213 result['devices'] = self.want.devices
1214 if len(self.want.devices) > 1 and self.have.server_type == 'bigip':
1215 if self.have.raw_server_type != 'redundant-bigip':
1216 result['server_type'] = 'redundant-bigip'
1217 elif self.have.server_type == 'bigip':
1218 if self.have.raw_server_type != 'single-bigip':
1219 result['server_type'] = 'single-bigip'
1220 else:
1221 result['server_type'] = self.want.server_type
1222
1223 elif server_change:
1224 if len(self.have.devices) > 1 and self.want.server_type == 'bigip':
1225 if self.have.raw_server_type != 'redundant-bigip':
1226 result['server_type'] = 'redundant-bigip'
1227 elif self.want.server_type == 'bigip':
1228 if self.have.raw_server_type != 'single-bigip':
1229 result['server_type'] = 'single-bigip'
1230 else:
1231 result['server_type'] = self.want.server_type
1232 return result
1233
1234 @property
1235 def server_type_and_devices(self):
1236 """Compares difference between server type and devices list
1237
1238 These two parameters are linked with each other and, therefore, must be
1239 compared together to ensure that the correct setting is sent to BIG-IP
1240
1241 :return:
1242 """
1243 devices_change = self._devices_changed()
1244 server_change = self._server_type_changed()
1245 if not devices_change and not server_change:
1246 return None
1247 tmos = tmos_version(self.client)
1248 if Version(tmos) >= Version('13.0.0'):
1249 result = self._handle_current_server_type_and_devices(
1250 devices_change, server_change
1251 )
1252 return result
1253 else:
1254 result = self._handle_legacy_server_type_and_devices(
1255 devices_change, server_change
1256 )
1257 return result
1258
1259 @property
1260 def state(self):
1261 if self.want.state == 'disabled' and self.have.enabled:
1262 return dict(disabled=True)
1263 elif self.want.state in ['present', 'enabled'] and self.have.disabled:
1264 return dict(enabled=True)
1265
1266 @property
1267 def monitors(self):
1268 if self.want.monitors is None:
1269 return None
1270 if self.want.monitors == '/Common/bigip' and self.have.monitors == '/Common/bigip':
1271 return None
1272 if self.want.monitors == '/Common/bigip' and self.have.monitors is None:
1273 return None
1274 if self.want.monitors == '/Common/bigip' and len(self.have.monitors) > 0:
1275 return '/Common/bigip'
1276 if self.have.monitors is None:
1277 return self.want.monitors
1278 if self.have.monitors != self.want.monitors:
1279 return self.want.monitors
1280
1281 @property
1282 def prober_pool(self):
1283 if self.want.prober_pool is None:
1284 return None
1285 if self.have.prober_pool is None:
1286 if self.want.prober_pool == '':
1287 return None
1288 if self.want.prober_pool != self.have.prober_pool:
1289 return self.want.prober_pool
1290
1291 @property
1292 def prober_preference(self):
1293 if self.want.prober_preference is None:
1294 return None
1295 if self.want.prober_preference == self.have.prober_preference:
1296 return None
1297 if self.want.prober_preference == 'pool' and self.want.prober_pool is None:
1298 raise F5ModuleError(
1299 "A prober_pool needs to be set if prober_preference is set to 'pool'"
1300 )
1301 if self.want.prober_preference != 'pool' and self.have.prober_preference == 'pool':
1302 if self.want.prober_fallback != 'pool' and self.want.prober_pool != '':
1303 raise F5ModuleError(
1304 "To change prober_preference from {0} to {1}, set prober_pool to an empty string".format(
1305 self.have.prober_preference,
1306 self.want.prober_preference
1307 )
1308 )
1309 if self.want.prober_preference == self.want.prober_fallback:
1310 raise F5ModuleError(
1311 "Prober_preference and prober_fallback must not be equal."
1312 )
1313 if self.want.prober_preference == self.have.prober_fallback:
1314 raise F5ModuleError(
1315 "Cannot set prober_preference to {0} if prober_fallback on device is set to {1}.".format(
1316 self.want.prober_preference,
1317 self.have.prober_fallback
1318 )
1319 )
1320 if self.want.prober_preference != self.have.prober_preference:
1321 return self.want.prober_preference
1322
1323 @property
1324 def prober_fallback(self):
1325 if self.want.prober_fallback is None:
1326 return None
1327 if self.want.prober_fallback == self.have.prober_fallback:
1328 return None
1329 if self.want.prober_fallback == 'pool' and self.want.prober_pool is None:
1330 raise F5ModuleError(
1331 "A prober_pool needs to be set if prober_fallback is set to 'pool'"
1332 )
1333 if self.want.prober_fallback != 'pool' and self.have.prober_fallback == 'pool':
1334 if self.want.prober_preference != 'pool' and self.want.prober_pool != '':
1335 raise F5ModuleError(
1336 "To change prober_fallback from {0} to {1}, set prober_pool to an empty string".format(
1337 self.have.prober_fallback,
1338 self.want.prober_fallback
1339 )
1340 )
1341 if self.want.prober_preference == self.want.prober_fallback:
1342 raise F5ModuleError(
1343 "Prober_preference and prober_fallback must not be equal."
1344 )
1345 if self.want.prober_fallback == self.have.prober_preference:
1346 raise F5ModuleError(
1347 "Cannot set prober_fallback to {0} if prober_preference on device is set to {1}.".format(
1348 self.want.prober_fallback,
1349 self.have.prober_preference
1350 )
1351 )
1352 if self.want.prober_fallback != self.have.prober_fallback:
1353 return self.want.prober_fallback
1354
1355
1356 class ModuleManager(object):
1357 def __init__(self, *args, **kwargs):
1358 self.module = kwargs.get('module', None)
1359 self.client = F5RestClient(**self.module.params)
1360 self.kwargs = kwargs
1361
1362 def exec_module(self):
1363 if not module_provisioned(self.client, 'gtm'):
1364 raise F5ModuleError(
1365 "GTM must be provisioned to use this module."
1366 )
1367 if self.version_is_less_than('13.0.0'):
1368 manager = self.get_manager('v1')
1369 else:
1370 manager = self.get_manager('v2')
1371 return manager.exec_module()
1372
1373 def get_manager(self, type):
1374 if type == 'v1':
1375 return V1Manager(**self.kwargs)
1376 elif type == 'v2':
1377 return V2Manager(**self.kwargs)
1378
1379 def version_is_less_than(self, version):
1380 tmos = tmos_version(self.client)
1381 if Version(tmos) < Version(version):
1382 return True
1383 else:
1384 return False
1385
1386
1387 class BaseManager(object):
1388 def __init__(self, *args, **kwargs):
1389 self.module = kwargs.get('module', None)
1390 self.client = F5RestClient(**self.module.params)
1391 self.want = ModuleParameters(params=self.module.params)
1392 self.want.update(dict(client=self.client))
1393 self.have = ApiParameters()
1394 self.changes = UsableChanges()
1395
1396 def _set_changed_options(self):
1397 changed = {}
1398 for key in Parameters.returnables:
1399 if getattr(self.want, key) is not None:
1400 changed[key] = getattr(self.want, key)
1401 if changed:
1402 self.changes = UsableChanges(params=changed)
1403
1404 def _update_changed_options(self):
1405 diff = Difference(self.want, self.have)
1406 diff.client = self.client
1407 updatables = Parameters.updatables
1408 changed = dict()
1409 for k in updatables:
1410 change = diff.compare(k)
1411 if change is None:
1412 continue
1413 else:
1414 if isinstance(change, dict):
1415 changed.update(change)
1416 else:
1417 changed[k] = change
1418 if changed:
1419 self.changes = UsableChanges(params=changed)
1420 return True
1421 return False
1422
1423 def exec_module(self):
1424 start = datetime.now().isoformat()
1425 version = tmos_version(self.client)
1426 changed = False
1427 result = dict()
1428 state = self.want.state
1429
1430 if state in ['present', 'enabled', 'disabled']:
1431 changed = self.present()
1432 elif state == "absent":
1433 changed = self.absent()
1434 reportable = ReportableChanges(params=self.changes.to_return())
1435 changes = reportable.to_return()
1436 result.update(**changes)
1437 result.update(dict(changed=changed))
1438 self._announce_deprecations(result)
1439 send_teem(start, self.client, self.module, version)
1440 return result
1441
1442 def _announce_deprecations(self, result):
1443 warnings = result.pop('__warnings', [])
1444 for warning in warnings:
1445 self.module.deprecate(
1446 msg=warning['msg'],
1447 version=warning['version']
1448 )
1449
1450 def _check_link_discovery_requirements(self):
1451 if (self.want.link_discovery in ['enabled', 'enabled-no-delete'] and
1452 self.want.virtual_server_discovery == 'disabled'):
1453 raise F5ModuleError(
1454 "Virtual server discovery must be enabled if link discovery is enabled"
1455 )
1456
1457 def present(self):
1458 if self.exists():
1459 return self.update()
1460 else:
1461 return self.create()
1462
1463 def create(self):
1464 if self.want.state == 'disabled':
1465 self.want.update({'disabled': True})
1466 elif self.want.state in ['present', 'enabled']:
1467 self.want.update({'enabled': True})
1468
1469 self.adjust_server_type_by_version()
1470 self.should_update()
1471
1472 if self.want.devices is None:
1473 raise F5ModuleError(
1474 "You must provide an initial device."
1475 )
1476 self._assign_creation_defaults()
1477 self.handle_prober_settings()
1478 self._set_changed_options()
1479 if self.module.check_mode:
1480 return True
1481 self.create_on_device()
1482 if self.exists():
1483 return True
1484 else:
1485 raise F5ModuleError("Failed to create the server")
1486
1487 def create_on_device(self):
1488 params = self.changes.api_params()
1489 params['name'] = self.want.name
1490 params['partition'] = self.want.partition
1491 uri = "https://{0}:{1}/mgmt/tm/gtm/server/".format(
1492 self.client.provider['server'],
1493 self.client.provider['server_port']
1494 )
1495 resp = self.client.api.post(uri, json=params)
1496 try:
1497 response = resp.json()
1498 except ValueError as ex:
1499 raise F5ModuleError(str(ex))
1500
1501 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1502 return True
1503 raise F5ModuleError(resp.content)
1504
1505 def read_current_from_device(self):
1506 uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format(
1507 self.client.provider['server'],
1508 self.client.provider['server_port'],
1509 transform_name(self.want.partition, self.want.name)
1510 )
1511 resp = self.client.api.get(uri)
1512 try:
1513 response = resp.json()
1514 except ValueError as ex:
1515 raise F5ModuleError(str(ex))
1516
1517 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1518 return ApiParameters(params=response)
1519 raise F5ModuleError(resp.content)
1520
1521 def should_update(self):
1522 result = self._update_changed_options()
1523 if result:
1524 return True
1525 return False
1526
1527 def update_on_device(self):
1528 params = self.changes.api_params()
1529 uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format(
1530 self.client.provider['server'],
1531 self.client.provider['server_port'],
1532 transform_name(self.want.partition, self.want.name)
1533 )
1534 resp = self.client.api.patch(uri, json=params)
1535 try:
1536 response = resp.json()
1537 except ValueError as ex:
1538 raise F5ModuleError(str(ex))
1539
1540 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1541 return True
1542 raise F5ModuleError(resp.content)
1543
1544 def absent(self):
1545 changed = False
1546 if self.exists():
1547 changed = self.remove()
1548 return changed
1549
1550 def remove(self):
1551 if self.module.check_mode:
1552 return True
1553 self.remove_from_device()
1554 if self.exists():
1555 raise F5ModuleError("Failed to delete the server")
1556 return True
1557
1558 def remove_from_device(self):
1559 uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format(
1560 self.client.provider['server'],
1561 self.client.provider['server_port'],
1562 transform_name(self.want.partition, self.want.name)
1563 )
1564 response = self.client.api.delete(uri)
1565 if response.status == 200:
1566 return True
1567 raise F5ModuleError(response.content)
1568
1569 def exists(self):
1570 uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format(
1571 self.client.provider['server'],
1572 self.client.provider['server_port'],
1573 transform_name(self.want.partition, self.want.name)
1574 )
1575 resp = self.client.api.get(uri)
1576 try:
1577 response = resp.json()
1578 except ValueError as ex:
1579 raise F5ModuleError(str(ex))
1580
1581 if resp.status == 404 or 'code' in response and response['code'] == 404:
1582 return False
1583 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1584 return True
1585
1586 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1587
1588 if resp.status in errors or 'code' in response and response['code'] in errors:
1589 if 'message' in response:
1590 raise F5ModuleError(response['message'])
1591 else:
1592 raise F5ModuleError(resp.content)
1593
1594 def check_datacenter(self):
1595 # check if datacenter exists
1596 if self.want.datacenter is not None:
1597 uri = "https://{0}:{1}/mgmt/tm/gtm/datacenter/".format(
1598 self.client.provider['server'],
1599 self.client.provider['server_port']
1600 )
1601 resp = self.client.api.get(uri)
1602 try:
1603 response = resp.json()
1604 datacenter = [dc for dc in response['items'] if dc['fullPath'] == self.want.datacenter]
1605 if len(datacenter) == 0:
1606 raise F5ModuleError(
1607 f'{self.want.datacenter} does not exists'
1608 )
1609 except ValueError as ex:
1610 raise F5ModuleError(str(ex))
1611
1612
1613 class V1Manager(BaseManager):
1614 def _assign_creation_defaults(self):
1615 if self.want.server_type is None:
1616 if len(self.want.devices) == 0:
1617 raise F5ModuleError(
1618 "You must provide at least one device."
1619 )
1620 elif len(self.want.devices) == 1:
1621 self.want.update({'server_type': 'single-bigip'})
1622 else:
1623 self.want.update({'server_type': 'redundant-bigip'})
1624 if self.want.link_discovery is None:
1625 self.want.update({'link_discovery': 'disabled'})
1626 if self.want.virtual_server_discovery is None:
1627 self.want.update({'virtual_server_discovery': 'disabled'})
1628 self._check_link_discovery_requirements()
1629
1630 def adjust_server_type_by_version(self):
1631 if len(self.want.devices) == 1 and self.want.server_type == 'bigip':
1632 self.want.update({'server_type': 'single-bigip'})
1633 if len(self.want.devices) > 1 and self.want.server_type == 'bigip':
1634 self.want.update({'server_type': 'redundant-bigip'})
1635
1636 def update(self):
1637 self.have = self.read_current_from_device()
1638 self.handle_prober_settings()
1639 if not self.should_update():
1640 return False
1641 if self.module.check_mode:
1642 return True
1643 self.update_on_device()
1644 return True
1645
1646 def handle_prober_settings(self):
1647 if self.want.prober_preference is not None:
1648 self.want._values.pop('prober_preference')
1649 if self.want.prober_fallback is not None:
1650 self.want._values.pop('prober_fallback')
1651 self.check_datacenter()
1652
1653
1654 class V2Manager(BaseManager):
1655 def update(self):
1656 self.check_datacenter()
1657 self.have = self.read_current_from_device()
1658 if not self.should_update():
1659 return False
1660 if self.module.check_mode:
1661 return True
1662 self.update_on_device()
1663 return True
1664
1665 def _assign_creation_defaults(self):
1666 if self.want.server_type is None:
1667 self.want.update({'server_type': 'bigip'})
1668 if self.want.link_discovery is None:
1669 self.want.update({'link_discovery': 'disabled'})
1670 if self.want.virtual_server_discovery is None:
1671 self.want.update({'virtual_server_discovery': 'disabled'})
1672 self._check_link_discovery_requirements()
1673
1674 def adjust_server_type_by_version(self):
1675 pass
1676
1677 def handle_prober_settings(self):
1678 if self.want.prober_preference == 'pool' and self.want.prober_pool is None:
1679 raise F5ModuleError(
1680 "A prober_pool needs to be set if prober_preference is set to 'pool'"
1681 )
1682 if self.want.prober_preference is not None and self.want.prober_fallback is not None:
1683 if self.want.prober_preference == self.want.prober_fallback:
1684 raise F5ModuleError(
1685 "The parameters for prober_preference and prober_fallback must not be the same."
1686 )
1687 if self.want.prober_fallback == 'pool' and self.want.prober_pool is None:
1688 raise F5ModuleError(
1689 "A prober_pool needs to be set if prober_fallback is set to 'pool'"
1690 )
1691
1692
1693 class ArgumentSpec(object):
1694 def __init__(self):
1695 self.states = ['absent', 'present', 'enabled', 'disabled']
1696 self.server_types = [
1697 'alteon-ace-director',
1698 'cisco-css',
1699 'cisco-server-load-balancer',
1700 'generic-host',
1701 'radware-wsd',
1702 'windows-nt-4.0',
1703 'bigip',
1704 'cisco-local-director-v2',
1705 'extreme',
1706 'generic-load-balancer',
1707 'sun-solaris',
1708 'cacheflow',
1709 'cisco-local-director-v3',
1710 'foundry-server-iron',
1711 'netapp',
1712 'windows-2000-server'
1713 ]
1714 self.supports_check_mode = True
1715 argument_spec = dict(
1716 state=dict(
1717 default='present',
1718 choices=self.states,
1719 ),
1720 name=dict(required=True),
1721 server_type=dict(
1722 choices=self.server_types,
1723 aliases=['product']
1724 ),
1725 datacenter=dict(),
1726 link_discovery=dict(
1727 choices=['enabled', 'disabled', 'enabled-no-delete']
1728 ),
1729 virtual_server_discovery=dict(
1730 choices=['enabled', 'disabled', 'enabled-no-delete']
1731 ),
1732 devices=dict(
1733 type='raw',
1734 ),
1735 partition=dict(
1736 default='Common',
1737 fallback=(env_fallback, ['F5_PARTITION'])
1738 ),
1739 iquery_options=dict(
1740 type='dict',
1741 options=dict(
1742 allow_path=dict(type='bool'),
1743 allow_service_check=dict(type='bool'),
1744 allow_snmp=dict(type='bool')
1745 )
1746 ),
1747 availability_requirements=dict(
1748 type='dict',
1749 options=dict(
1750 type=dict(
1751 choices=['all', 'at_least', 'require'],
1752 required=True
1753 ),
1754 at_least=dict(type='int'),
1755 number_of_probes=dict(type='int'),
1756 number_of_probers=dict(type='int')
1757 ),
1758 mutually_exclusive=[
1759 ['at_least', 'number_of_probes'],
1760 ['at_least', 'number_of_probers'],
1761 ],
1762 required_if=[
1763 ['type', 'at_least', ['at_least']],
1764 ['type', 'require', ['number_of_probes', 'number_of_probers']]
1765 ]
1766 ),
1767 limits=dict(
1768 type='dict',
1769 options=dict(
1770 bits_enabled=dict(type='bool'),
1771 packets_enabled=dict(type='bool'),
1772 connections_enabled=dict(type='bool'),
1773 cpu_enabled=dict(type='bool'),
1774 memory_enabled=dict(type='bool'),
1775 bits_limit=dict(type='int'),
1776 packets_limit=dict(type='int'),
1777 connections_limit=dict(type='int'),
1778 cpu_limit=dict(type='int'),
1779 memory_limit=dict(type='int'),
1780 )
1781 ),
1782 monitors=dict(
1783 type='list',
1784 elements='str',
1785 ),
1786 prober_preference=dict(
1787 choices=['inside-datacenter', 'outside-datacenter', 'inherit', 'pool']
1788 ),
1789 prober_fallback=dict(
1790 choices=['inside-datacenter', 'outside-datacenter',
1791 'inherit', 'pool', 'any', 'none']
1792 ),
1793 prober_pool=dict()
1794
1795 )
1796 self.argument_spec = {}
1797 self.argument_spec.update(f5_argument_spec)
1798 self.argument_spec.update(argument_spec)
1799
1800
1801 def main():
1802 spec = ArgumentSpec()
1803
1804 module = AnsibleModule(
1805 argument_spec=spec.argument_spec,
1806 supports_check_mode=spec.supports_check_mode,
1807 )
1808
1809 if not HAS_PACKAGING:
1810 module.fail_json(
1811 msg=missing_required_lib('packaging'),
1812 exception=PACKAGING_IMPORT_ERROR
1813 )
1814
1815 try:
1816 mm = ModuleManager(module=module)
1817 results = mm.exec_module()
1818 module.exit_json(**results)
1819 except F5ModuleError as ex:
1820 module.fail_json(msg=str(ex))
1821
1822
1823 if __name__ == '__main__':
1824 main()