Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_gtm_pool.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_pool
13 short_description: Manages F5 BIG-IP GTM pools
14 description:
15 - Manages F5 BIG-IP GTM (now BIG-IP DNS) pools.
16 version_added: "1.0.0"
17 options:
18 state:
19 description:
20 - Pool state. When C(present), ensures the pool is created and enabled.
21 When C(absent), ensures the pool is removed from the system. When
22 C(enabled) or C(disabled), ensures the pool is enabled or disabled
23 (respectively) on the remote device.
24 type: str
25 choices:
26 - present
27 - absent
28 - enabled
29 - disabled
30 default: present
31 preferred_lb_method:
32 description:
33 - The load balancing mode the system tries first.
34 type: str
35 choices:
36 - round-robin
37 - return-to-dns
38 - ratio
39 - topology
40 - static-persistence
41 - global-availability
42 - virtual-server-capacity
43 - least-connections
44 - lowest-round-trip-time
45 - fewest-hops
46 - packet-rate
47 - cpu
48 - completion-rate
49 - quality-of-service
50 - kilobytes-per-second
51 - drop-packet
52 - fallback-ip
53 - virtual-server-score
54 alternate_lb_method:
55 description:
56 - The load balancing mode the system tries if the
57 C(preferred_lb_method) is unsuccessful in picking a pool.
58 type: str
59 choices:
60 - round-robin
61 - return-to-dns
62 - none
63 - ratio
64 - topology
65 - static-persistence
66 - global-availability
67 - virtual-server-capacity
68 - packet-rate
69 - drop-packet
70 - fallback-ip
71 - virtual-server-score
72 fallback_lb_method:
73 description:
74 - The load balancing mode the system tries if both the
75 C(preferred_lb_method) and C(alternate_lb_method)s are unsuccessful
76 in picking a pool.
77 type: str
78 choices:
79 - round-robin
80 - return-to-dns
81 - ratio
82 - topology
83 - static-persistence
84 - global-availability
85 - virtual-server-capacity
86 - least-connections
87 - lowest-round-trip-time
88 - fewest-hops
89 - packet-rate
90 - cpu
91 - completion-rate
92 - quality-of-service
93 - kilobytes-per-second
94 - drop-packet
95 - fallback-ip
96 - virtual-server-score
97 - none
98 fallback_ip:
99 description:
100 - Specifies the IPv4 or IPv6 address of the server to which the system
101 directs requests when it cannot use one of its pools to do so.
102 Note that the system uses the fallback IP only if you select the
103 C(fallback_ip) load balancing method.
104 type: str
105 type:
106 description:
107 - The type of GTM pool you want to create.
108 type: str
109 required: True
110 choices:
111 - a
112 - aaaa
113 - cname
114 - mx
115 - naptr
116 - srv
117 name:
118 description:
119 - Name of the GTM pool.
120 type: str
121 required: True
122 partition:
123 description:
124 - Device partition to manage resources on.
125 type: str
126 default: Common
127 members:
128 description:
129 - Members to assign to the pool.
130 - The order of the members in this list is the order they will be listed in the pool.
131 suboptions:
132 server:
133 description:
134 - Name of the server which the pool member is a part of.
135 type: str
136 required: True
137 virtual_server:
138 description:
139 - Name of the virtual server, associated with the server, the pool member is a part of.
140 type: str
141 required: True
142 type: list
143 elements: dict
144 monitors:
145 description:
146 - Specifies the health monitors the system currently uses to monitor this resource.
147 - When C(availability_requirements.type) is C(require), you may only have a single monitor in the
148 C(monitors) list.
149 type: list
150 elements: str
151 availability_requirements:
152 description:
153 - If you activate more than one health monitor, specifies the number of health
154 monitors that must receive successful responses in order for the link to be
155 considered available.
156 suboptions:
157 type:
158 description:
159 - Monitor rule type when C(monitors) is specified.
160 - When creating a new pool, if this value is not specified, the default of 'all' will be used.
161 type: str
162 required: True
163 choices:
164 - all
165 - at_least
166 - require
167 at_least:
168 description:
169 - Specifies the minimum number of active health monitors that must be successful
170 before the link is considered up.
171 - This parameter is only relevant when a C(type) of C(at_least) is used.
172 - This parameter will be ignored if a type of either C(all) or C(require) is used.
173 type: int
174 number_of_probes:
175 description:
176 - Specifies the minimum number of probes that must succeed for this server to be declared up.
177 - When creating a new virtual server, if this parameter is specified, the C(number_of_probers)
178 parameter must also be specified.
179 - The value of this parameter should always be B(lower) than, or B(equal to),
180 the value of C(number_of_probers).
181 - This parameter is only relevant when a C(type) of C(require) is used.
182 - This parameter will be ignored if a type of either C(all) or C(at_least) is used.
183 type: int
184 number_of_probers:
185 description:
186 - Specifies the number of probers that should be used when running probes.
187 - When creating a new virtual server, if this parameter is specified, the C(number_of_probes)
188 parameter must also be specified.
189 - The value of this parameter should always be B(higher) than, or B(equal to),
190 the value of C(number_of_probers).
191 - This parameter is only relevant when a C(type) of C(require) is used.
192 - This parameter will be ignored if a type of either C(all) or C(at_least) is used.
193 type: int
194 type: dict
195 max_answers_returned:
196 description:
197 - Specifies the maximum number of available virtual servers the system lists in a response.
198 - The maximum is 500.
199 type: int
200 ttl:
201 description:
202 - Specifies the number of seconds the IP address, once found, is valid.
203 type: int
204 extends_documentation_fragment: f5networks.f5_modules.f5
205 author:
206 - Tim Rupp (@caphrim007)
207 - Wojciech Wypior (@wojtek0806)
208 '''
209
210 EXAMPLES = r'''
211 - name: Create a GTM pool
212 bigip_gtm_pool:
213 name: my_pool
214 type: a
215 provider:
216 user: admin
217 password: secret
218 server: lb.mydomain.com
219 delegate_to: localhost
220
221 - name: Disable pool
222 bigip_gtm_pool:
223 state: disabled
224 name: my_pool
225 type: a
226 provider:
227 user: admin
228 password: secret
229 server: lb.mydomain.com
230 delegate_to: localhost
231 '''
232
233 RETURN = r'''
234 preferred_lb_method:
235 description: New preferred load balancing method for the pool.
236 returned: changed
237 type: str
238 sample: topology
239 alternate_lb_method:
240 description: New alternate load balancing method for the pool.
241 returned: changed
242 type: str
243 sample: drop-packet
244 fallback_lb_method:
245 description: New fallback load balancing method for the pool.
246 returned: changed
247 type: str
248 sample: fewest-hops
249 fallback_ip:
250 description: New fallback IP used when load balacing using the C(fallback_ip) method.
251 returned: changed
252 type: str
253 sample: 10.10.10.10
254 monitors:
255 description: The new list of monitors for the resource.
256 returned: changed
257 type: list
258 sample: ['/Common/monitor1', '/Common/monitor2']
259 members:
260 description: List of members in the pool.
261 returned: changed
262 type: complex
263 contains:
264 server:
265 description: The name of the server portion of the member.
266 returned: changed
267 type: str
268 virtual_server:
269 description: The name of the virtual server portion of the member.
270 returned: changed
271 type: str
272 max_answers_returned:
273 description: The new Maximum Answers Returned value.
274 returned: changed
275 type: int
276 sample: 25
277 '''
278
279 import copy
280 import re
281 from datetime import datetime
282
283 from ansible.module_utils.basic import (
284 AnsibleModule, env_fallback
285 )
286
287 from ..module_utils.bigip import F5RestClient
288 from ..module_utils.common import (
289 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
290 )
291 from ..module_utils.icontrol import (
292 module_provisioned, tmos_version
293 )
294 from ..module_utils.ipaddress import is_valid_ip
295 from ..module_utils.teem import send_teem
296
297
298 class Parameters(AnsibleF5Parameters):
299 api_map = {
300 'loadBalancingMode': 'preferred_lb_method',
301 'alternateMode': 'alternate_lb_method',
302 'fallbackMode': 'fallback_lb_method',
303 'verifyMemberAvailability': 'verify_member_availability',
304 'fallbackIpv4': 'fallback_ip',
305 'fallbackIpv6': 'fallback_ip',
306 'fallbackIp': 'fallback_ip',
307 'membersReference': 'members',
308 'monitor': 'monitors',
309 'maxAnswersReturned': 'max_answers_returned',
310 }
311
312 updatables = [
313 'alternate_lb_method',
314 'fallback_ip',
315 'fallback_lb_method',
316 'members',
317 'monitors',
318 'preferred_lb_method',
319 'state',
320 'max_answers_returned',
321 'ttl',
322 ]
323
324 returnables = [
325 'alternate_lb_method',
326 'fallback_ip',
327 'fallback_lb_method',
328 'members',
329 'monitors',
330 'preferred_lb_method',
331 'enabled',
332 'disabled',
333 'availability_requirements',
334 'max_answers_returned',
335 'ttl',
336 ]
337
338 api_attributes = [
339 'alternateMode',
340 'disabled',
341 'enabled',
342 'fallbackIp',
343 'fallbackIpv4',
344 'fallbackIpv6',
345 'fallbackMode',
346 'loadBalancingMode',
347 'members',
348 'verifyMemberAvailability',
349 'monitor',
350 'maxAnswersReturned',
351 'ttl',
352 ]
353
354 @property
355 def type(self):
356 if self._values['type'] is None:
357 return None
358 return str(self._values['type'])
359
360 @property
361 def verify_member_availability(self):
362 if self._values['verify_member_availability'] is None:
363 return None
364 elif self._values['verify_member_availability']:
365 return 'enabled'
366 else:
367 return 'disabled'
368
369 @property
370 def fallback_ip(self):
371 if self._values['fallback_ip'] is None:
372 return None
373 if self._values['fallback_ip'] == 'any':
374 return 'any'
375 if self._values['fallback_ip'] == 'any6':
376 return 'any6'
377 if is_valid_ip(self._values['fallback_ip']):
378 return self._values['fallback_ip']
379 else:
380 raise F5ModuleError(
381 'The provided fallback address is not a valid IPv4 address'
382 )
383
384 @property
385 def state(self):
386 if self._values['state'] == 'enabled':
387 return 'present'
388 return self._values['state']
389
390 @property
391 def enabled(self):
392 if self._values['enabled'] is None:
393 return None
394 return True
395
396 @property
397 def disabled(self):
398 if self._values['disabled'] is None:
399 return None
400 return True
401
402
403 class ApiParameters(Parameters):
404 @property
405 def members(self):
406 result = []
407 if self._values['members'] is None or 'items' not in self._values['members']:
408 return []
409 for item in self._values['members']['items']:
410 result.append(dict(item=item['fullPath'], order=item['memberOrder']))
411 result = [x['item'] for x in sorted(result, key=lambda k: k['order'])]
412 return result
413
414 @property
415 def availability_requirement_type(self):
416 if self._values['monitors'] is None:
417 return None
418 if 'min ' in self._values['monitors']:
419 return 'at_least'
420 elif 'require ' in self._values['monitors']:
421 return 'require'
422 else:
423 return 'all'
424
425 @property
426 def monitors_list(self):
427 if self._values['monitors'] is None:
428 return []
429 try:
430 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
431 result.sort()
432 return result
433 except Exception:
434 return self._values['monitors']
435
436 @property
437 def monitors(self):
438 if self._values['monitors'] is None:
439 return None
440 if self._values['monitors'] == 'default':
441 return 'default'
442 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
443 if self.availability_requirement_type == 'at_least':
444 monitors = ' '.join(monitors)
445 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
446 elif self.availability_requirement_type == 'require':
447 monitors = ' '.join(monitors)
448 result = 'require {0} from {1} {{ {2} }}'.format(self.number_of_probes, self.number_of_probers, monitors)
449 else:
450 result = ' and '.join(monitors).strip()
451 return result
452
453 @property
454 def number_of_probes(self):
455 """Returns the probes value from the monitor string.
456
457 The monitor string for a Require monitor looks like this.
458
459 require 1 from 2 { /Common/tcp }
460
461 This method parses out the first of the numeric values. This values represents
462 the "probes" value that can be updated in the module.
463
464 Returns:
465 int: The probes value if found. None otherwise.
466 """
467 if self._values['monitors'] is None:
468 return None
469 pattern = r'require\s+(?P<probes>\d+)\s+from'
470 matches = re.search(pattern, self._values['monitors'])
471 if matches is None:
472 return None
473 return matches.group('probes')
474
475 @property
476 def number_of_probers(self):
477 """Returns the probers value from the monitor string.
478
479 The monitor string for a Require monitor looks like this.
480
481 require 1 from 2 { /Common/tcp }
482
483 This method parses out the first of the numeric values. This values represents
484 the "probers" value that can be updated in the module.
485
486 Returns:
487 int: The probers value if found. None otherwise.
488 """
489 if self._values['monitors'] is None:
490 return None
491 pattern = r'require\s+\d+\s+from\s+(?P<probers>\d+)\s+'
492 matches = re.search(pattern, self._values['monitors'])
493 if matches is None:
494 return None
495 return matches.group('probers')
496
497 @property
498 def at_least(self):
499 """Returns the 'at least' value from the monitor string.
500
501 The monitor string for a Require monitor looks like this.
502
503 min 1 of { /Common/gateway_icmp }
504
505 This method parses out the first of the numeric values. This values represents
506 the "at_least" value that can be updated in the module.
507
508 Returns:
509 int: The at_least value if found. None otherwise.
510 """
511 if self._values['monitors'] is None:
512 return None
513 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
514 matches = re.search(pattern, self._values['monitors'])
515 if matches is None:
516 return None
517 return matches.group('least')
518
519
520 class ModuleParameters(Parameters):
521 def _get_availability_value(self, type):
522 if self._values['availability_requirements'] is None:
523 return None
524 if self._values['availability_requirements'][type] is None:
525 return None
526 return int(self._values['availability_requirements'][type])
527
528 @property
529 def members(self):
530 if self._values['members'] is None:
531 return None
532 if not self._values['members']:
533 return []
534 result = []
535 for member in self._values['members']:
536 if 'server' not in member:
537 raise F5ModuleError(
538 "One of the provided members is missing a 'server' sub-option."
539 )
540 if 'virtual_server' not in member:
541 raise F5ModuleError(
542 "One of the provided members is missing a 'virtual_server' sub-option."
543 )
544 name = '{0}:{1}'.format(member['server'], member['virtual_server'])
545 name = fq_name(self.partition, name)
546 if name in result:
547 continue
548 result.append(name)
549 result = list(result)
550 return result
551
552 @property
553 def monitors_list(self):
554 if self._values['monitors'] is None:
555 return []
556 try:
557 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
558 result.sort()
559 return result
560 except Exception:
561 return self._values['monitors']
562
563 @property
564 def monitors(self):
565 if self._values['monitors'] is None:
566 return None
567 if len(self._values['monitors']) == 1 and self._values['monitors'][0] == '':
568 return 'default'
569 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
570 if self.availability_requirement_type == 'at_least':
571 if self.at_least > len(self.monitors_list):
572 raise F5ModuleError(
573 "The 'at_least' value must not exceed the number of 'monitors'."
574 )
575 monitors = ' '.join(monitors)
576 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
577 elif self.availability_requirement_type == 'require':
578 monitors = ' '.join(monitors)
579 if self.number_of_probes > self.number_of_probers:
580 raise F5ModuleError(
581 "The 'number_of_probes' must not exceed the 'number_of_probers'."
582 )
583 result = 'require {0} from {1} {{ {2} }}'.format(self.number_of_probes, self.number_of_probers, monitors)
584 else:
585 result = ' and '.join(monitors).strip()
586
587 return result
588
589 @property
590 def availability_requirement_type(self):
591 if self._values['availability_requirements'] is None:
592 return None
593 return self._values['availability_requirements']['type']
594
595 @property
596 def number_of_probes(self):
597 return self._get_availability_value('number_of_probes')
598
599 @property
600 def number_of_probers(self):
601 return self._get_availability_value('number_of_probers')
602
603 @property
604 def at_least(self):
605 return self._get_availability_value('at_least')
606
607
608 class Changes(Parameters):
609 def to_return(self):
610 result = {}
611 try:
612 for returnable in self.returnables:
613 result[returnable] = getattr(self, returnable)
614 result = self._filter_params(result)
615 except Exception:
616 raise
617 return result
618
619
620 class UsableChanges(Changes):
621 @property
622 def monitors(self):
623 monitor_string = self._values['monitors']
624 if monitor_string is None:
625 return None
626 if '{' in monitor_string and '}' in monitor_string:
627 tmp = monitor_string.strip('}').split('{')
628 monitor = ''.join(tmp).rstrip()
629 return monitor
630 return monitor_string
631
632 @property
633 def members(self):
634 results = []
635 if self._values['members'] is None:
636 return None
637 for idx, member in enumerate(self._values['members']):
638 result = dict(
639 name=member,
640 memberOrder=idx
641 )
642 results.append(result)
643 return results
644
645
646 class ReportableChanges(Changes):
647 @property
648 def members(self):
649 results = []
650 if self._values['members'] is None:
651 return None
652 if not self._values['members']:
653 return []
654 for member in self._values['members']:
655 parts = member.split(':')
656 results.append(dict(
657 server=fq_name(self.partition, parts[0]),
658 virtual_server=fq_name(self.partition, parts[1])
659 ))
660 return results
661
662 @property
663 def monitors(self):
664 if self._values['monitors'] is None:
665 return []
666 try:
667 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
668 result.sort()
669 return result
670 except Exception:
671 return self._values['monitors']
672
673 @property
674 def availability_requirement_type(self):
675 if self._values['monitors'] is None:
676 return None
677 if 'min ' in self._values['monitors']:
678 return 'at_least'
679 elif 'require ' in self._values['monitors']:
680 return 'require'
681 else:
682 return 'all'
683
684 @property
685 def number_of_probes(self):
686 """Returns the probes value from the monitor string.
687 The monitor string for a Require monitor looks like this.
688 require 1 from 2 { /Common/tcp }
689 This method parses out the first of the numeric values. This values represents
690 the "probes" value that can be updated in the module.
691 Returns:
692 int: The probes value if found. None otherwise.
693 """
694 if self._values['monitors'] is None:
695 return None
696 pattern = r'require\s+(?P<probes>\d+)\s+from'
697 matches = re.search(pattern, self._values['monitors'])
698 if matches is None:
699 return None
700 return int(matches.group('probes'))
701
702 @property
703 def number_of_probers(self):
704 """Returns the probers value from the monitor string.
705 The monitor string for a Require monitor looks like this.
706 require 1 from 2 { /Common/tcp }
707 This method parses out the first of the numeric values. This values represents
708 the "probers" value that can be updated in the module.
709 Returns:
710 int: The probers value if found. None otherwise.
711 """
712 if self._values['monitors'] is None:
713 return None
714 pattern = r'require\s+\d+\s+from\s+(?P<probers>\d+)\s+'
715 matches = re.search(pattern, self._values['monitors'])
716 if matches is None:
717 return None
718 return int(matches.group('probers'))
719
720 @property
721 def at_least(self):
722 """Returns the 'at least' value from the monitor string.
723 The monitor string for a Require monitor looks like this.
724 min 1 of { /Common/gateway_icmp }
725 This method parses out the first of the numeric values. This values represents
726 the "at_least" value that can be updated in the module.
727 Returns:
728 int: The at_least value if found. None otherwise.
729 """
730 if self._values['monitors'] is None:
731 return None
732 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
733 matches = re.search(pattern, self._values['monitors'])
734 if matches is None:
735 return None
736 return int(matches.group('least'))
737
738 @property
739 def availability_requirements(self):
740 if self._values['monitors'] is None:
741 return None
742 result = dict()
743 result['type'] = self.availability_requirement_type
744 result['at_least'] = self.at_least
745 result['number_of_probers'] = self.number_of_probers
746 result['number_of_probes'] = self.number_of_probes
747 return result
748
749
750 class Difference(object):
751 def __init__(self, want, have=None):
752 self.want = want
753 self.have = have
754
755 def compare(self, param):
756 try:
757 result = getattr(self, param)
758 return result
759 except AttributeError:
760 return self.__default(param)
761
762 def __default(self, param):
763 attr1 = getattr(self.want, param)
764 try:
765 attr2 = getattr(self.have, param)
766 if attr1 != attr2:
767 return attr1
768 except AttributeError:
769 return attr1
770
771 @property
772 def state(self):
773 if self.want.state == 'disabled' and self.have.enabled:
774 return dict(
775 disabled=True
776 )
777 elif self.want.state in ['present', 'enabled'] and self.have.disabled:
778 return dict(
779 enabled=True
780 )
781
782 @property
783 def monitors(self):
784 if self.want.monitors is None:
785 return None
786 if self.want.monitors == 'default' and self.have.monitors == 'default':
787 return None
788 if self.want.monitors == 'default' and self.have.monitors is None:
789 return None
790 if self.want.monitors == 'default' and len(self.have.monitors) > 0:
791 return 'default'
792 if self.have.monitors is None:
793 return self.want.monitors
794 if self.have.monitors != self.want.monitors:
795 return self.want.monitors
796
797
798 class ModuleManager(object):
799 def __init__(self, *args, **kwargs):
800 self.module = kwargs.get('module', None)
801 self.client = F5RestClient(**self.module.params)
802 self.have = ApiParameters()
803 self.want = ModuleParameters(params=self.module.params)
804 self.changes = UsableChanges()
805
806 def _set_changed_options(self):
807 changed = {}
808 for key in Parameters.returnables:
809 if getattr(self.want, key) is not None:
810 changed[key] = getattr(self.want, key)
811 if changed:
812 self.changes = UsableChanges(params=changed)
813
814 def _update_changed_options(self):
815 diff = Difference(self.want, self.have)
816 updatables = Parameters.updatables
817 changed = dict()
818 for k in updatables:
819 change = diff.compare(k)
820 if change is None:
821 continue
822 else:
823 if isinstance(change, dict):
824 changed.update(change)
825 else:
826 changed[k] = change
827 if changed:
828 self.changes = UsableChanges(params=changed)
829 return True
830 return False
831
832 def exec_module(self):
833 if not module_provisioned(self.client, 'gtm'):
834 raise F5ModuleError(
835 "GTM must be provisioned to use this module."
836 )
837 start = datetime.now().isoformat()
838 version = tmos_version(self.client)
839 changed = False
840 result = dict()
841 state = self.want.state
842
843 if state in ["present", "disabled"]:
844 changed = self.present()
845 elif state == "absent":
846 changed = self.absent()
847
848 reportable = ReportableChanges(params=self.changes.to_return())
849 changes = reportable.to_return()
850 result.update(**changes)
851 result.update(dict(changed=changed))
852 self._announce_deprecations(result)
853 send_teem(start, self.client, self.module, version)
854 return result
855
856 def _announce_deprecations(self, result):
857 warnings = result.pop('__warnings', [])
858 for warning in warnings:
859 self.module.deprecate(
860 msg=warning['msg'],
861 version=warning['version']
862 )
863
864 def present(self):
865 if self.exists():
866 return self.update()
867 else:
868 return self.create()
869
870 def absent(self):
871 if self.exists():
872 return self.remove()
873 return False
874
875 def should_update(self):
876 result = self._update_changed_options()
877 if result:
878 return True
879 return False
880
881 def update(self):
882 self.have = self.read_current_from_device()
883 if not self.should_update():
884 return False
885 if self.module.check_mode:
886 return True
887 self.update_on_device()
888 return True
889
890 def create(self):
891 if self.want.state == 'disabled':
892 self.want.update({'disabled': True})
893 elif self.want.state in ['present', 'enabled']:
894 self.want.update({'enabled': True})
895
896 self._set_changed_options()
897
898 if self.want.availability_requirement_type == 'require' and len(self.want.monitors_list) > 1:
899 raise F5ModuleError(
900 "Only one monitor may be specified when using an availability_requirement type of 'require'"
901 )
902
903 if self.module.check_mode:
904 return True
905 self.create_on_device()
906 if self.exists():
907 return True
908 else:
909 raise F5ModuleError("Failed to create the GTM pool")
910
911 def remove(self):
912 if self.module.check_mode:
913 return True
914 self.remove_from_device()
915 if self.exists():
916 raise F5ModuleError("Failed to delete the GTM pool")
917 return True
918
919 def exists(self):
920 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}".format(
921 self.client.provider['server'],
922 self.client.provider['server_port'],
923 self.want.type,
924 transform_name(self.want.partition, self.want.name)
925 )
926 resp = self.client.api.get(uri)
927 try:
928 response = resp.json()
929 except ValueError as ex:
930 raise F5ModuleError(str(ex))
931
932 if resp.status == 404 or 'code' in response and response['code'] == 404:
933 return False
934 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
935 return True
936
937 errors = [401, 403, 409, 500, 501, 502, 503, 504]
938
939 if resp.status in errors or 'code' in response and response['code'] in errors:
940 if 'message' in response:
941 raise F5ModuleError(response['message'])
942 else:
943 raise F5ModuleError(resp.content)
944
945 def update_on_device(self):
946 params = self.changes.api_params()
947 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}".format(
948 self.client.provider['server'],
949 self.client.provider['server_port'],
950 self.want.type,
951 transform_name(self.want.partition, self.want.name)
952 )
953 resp = self.client.api.patch(uri, json=params)
954 try:
955 response = resp.json()
956 except ValueError as ex:
957 raise F5ModuleError(str(ex))
958
959 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
960 return True
961 raise F5ModuleError(resp.content)
962
963 def read_current_from_device(self):
964 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}".format(
965 self.client.provider['server'],
966 self.client.provider['server_port'],
967 self.want.type,
968 transform_name(self.want.partition, self.want.name)
969 )
970
971 query = '?expandSubcollections=true'
972 resp = self.client.api.get(uri + query)
973
974 try:
975 response = resp.json()
976 except ValueError as ex:
977 raise F5ModuleError(str(ex))
978
979 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
980 return ApiParameters(params=response)
981 raise F5ModuleError(resp.content)
982
983 def create_on_device(self):
984 params = self.changes.api_params()
985 params['name'] = self.want.name
986 params['partition'] = self.want.partition
987 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}".format(
988 self.client.provider['server'],
989 self.client.provider['server_port'],
990 self.want.type
991 )
992 resp = self.client.api.post(uri, json=params)
993 try:
994 response = resp.json()
995 except ValueError as ex:
996 raise F5ModuleError(str(ex))
997
998 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
999 return True
1000 raise F5ModuleError(resp.content)
1001
1002 def remove_from_device(self):
1003 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}".format(
1004 self.client.provider['server'],
1005 self.client.provider['server_port'],
1006 self.want.type,
1007 transform_name(self.want.partition, self.want.name)
1008 )
1009 response = self.client.api.delete(uri)
1010 if response.status == 200:
1011 return True
1012 raise F5ModuleError(response.content)
1013
1014
1015 class ArgumentSpec(object):
1016 def __init__(self):
1017 self.states = ['absent', 'present', 'enabled', 'disabled']
1018 self.preferred_lb_methods = [
1019 'round-robin', 'return-to-dns', 'ratio', 'topology',
1020 'static-persistence', 'global-availability',
1021 'virtual-server-capacity', 'least-connections',
1022 'lowest-round-trip-time', 'fewest-hops', 'packet-rate', 'cpu',
1023 'completion-rate', 'quality-of-service', 'kilobytes-per-second',
1024 'drop-packet', 'fallback-ip', 'virtual-server-score'
1025 ]
1026 self.alternate_lb_methods = [
1027 'round-robin', 'return-to-dns', 'none', 'ratio', 'topology',
1028 'static-persistence', 'global-availability',
1029 'virtual-server-capacity', 'packet-rate', 'drop-packet',
1030 'fallback-ip', 'virtual-server-score'
1031 ]
1032 self.fallback_lb_methods = copy.copy(self.preferred_lb_methods)
1033 self.fallback_lb_methods.append('none')
1034 self.types = [
1035 'a', 'aaaa', 'cname', 'mx', 'naptr', 'srv'
1036 ]
1037 self.supports_check_mode = True
1038 argument_spec = dict(
1039 name=dict(required=True),
1040 state=dict(
1041 default='present',
1042 choices=self.states,
1043 ),
1044 preferred_lb_method=dict(
1045 choices=self.preferred_lb_methods,
1046 ),
1047 fallback_lb_method=dict(
1048 choices=self.fallback_lb_methods,
1049 ),
1050 alternate_lb_method=dict(
1051 choices=self.alternate_lb_methods,
1052 ),
1053 fallback_ip=dict(),
1054 type=dict(
1055 required=True,
1056 choices=self.types
1057 ),
1058 partition=dict(
1059 default='Common',
1060 fallback=(env_fallback, ['F5_PARTITION'])
1061 ),
1062 members=dict(
1063 type='list',
1064 elements='dict',
1065 options=dict(
1066 server=dict(required=True),
1067 virtual_server=dict(required=True)
1068 )
1069 ),
1070 availability_requirements=dict(
1071 type='dict',
1072 options=dict(
1073 type=dict(
1074 choices=['all', 'at_least', 'require'],
1075 required=True
1076 ),
1077 at_least=dict(type='int'),
1078 number_of_probes=dict(type='int'),
1079 number_of_probers=dict(type='int')
1080 ),
1081 mutually_exclusive=[
1082 ['at_least', 'number_of_probes'],
1083 ['at_least', 'number_of_probers'],
1084 ],
1085 required_if=[
1086 ['type', 'at_least', ['at_least']],
1087 ['type', 'require', ['number_of_probes', 'number_of_probers']]
1088 ]
1089 ),
1090 monitors=dict(
1091 type='list',
1092 elements='str',
1093 ),
1094 max_answers_returned=dict(type='int'),
1095 ttl=dict(type='int')
1096 )
1097 self.argument_spec = {}
1098 self.argument_spec.update(f5_argument_spec)
1099 self.argument_spec.update(argument_spec)
1100 self.required_if = [
1101 ['preferred_lb_method', 'fallback-ip', ['fallback_ip']],
1102 ['fallback_lb_method', 'fallback-ip', ['fallback_ip']],
1103 ['alternate_lb_method', 'fallback-ip', ['fallback_ip']]
1104 ]
1105
1106
1107 def main():
1108 spec = ArgumentSpec()
1109
1110 module = AnsibleModule(
1111 argument_spec=spec.argument_spec,
1112 supports_check_mode=spec.supports_check_mode,
1113 required_if=spec.required_if
1114 )
1115
1116 try:
1117 mm = ModuleManager(module=module)
1118 results = mm.exec_module()
1119 module.exit_json(**results)
1120 except F5ModuleError as ex:
1121 module.fail_json(msg=str(ex))
1122
1123
1124 if __name__ == '__main__':
1125 main()