Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_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
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: bigip_pool
14 short_description: Manages F5 BIG-IP LTM pools
15 description:
16 - Manages F5 BIG-IP LTM pools via iControl REST API.
17 version_added: "1.0.0"
18 options:
19 description:
20 description:
21 - Specifies descriptive text that identifies the pool.
22 type: str
23 name:
24 description:
25 - Pool name
26 type: str
27 aliases:
28 - pool
29 lb_method:
30 description:
31 - Load balancing method. When creating a new pool, if this value is not
32 specified, the default of C(round-robin) is used.
33 type: str
34 choices:
35 - dynamic-ratio-member
36 - dynamic-ratio-node
37 - fastest-app-response
38 - fastest-node
39 - least-connections-member
40 - least-connections-node
41 - least-sessions
42 - observed-member
43 - observed-node
44 - predictive-member
45 - predictive-node
46 - ratio-least-connections-member
47 - ratio-least-connections-node
48 - ratio-member
49 - ratio-node
50 - ratio-session
51 - round-robin
52 - weighted-least-connections-member
53 - weighted-least-connections-node
54 monitor_type:
55 description:
56 - Monitor rule type when C(monitors) is specified.
57 - When creating a new pool, if this value is not specified, the default
58 of C(and_list) is used.
59 - When C(single), ensures all specified monitors are checked, but
60 additionally includes checks to make sure you only specified a single
61 monitor.
62 - When C(and_list), ensures B(all) monitors are checked.
63 - When C(m_of_n), ensures C(quorum) of C(monitors) are checked. C(m_of_n)
64 B(requires) a C(quorum) of 1 or greater be set either in the playbook,
65 or already exist on the device.
66 - Both C(single) and C(and_list) are functionally identical, as BIG-IP
67 considers all monitors as "a list".
68 type: str
69 aliases:
70 - availability_requirements_type
71 choices:
72 - and_list
73 - m_of_n
74 - single
75 quorum:
76 description:
77 - Monitor quorum value when C(monitor_type) is C(m_of_n).
78 - Quorum must be a value of 1 or greater when C(monitor_type) is C(m_of_n).
79 type: int
80 aliases:
81 - availability_requirements_at_least
82 monitors:
83 description:
84 - Monitor template name list. If the partition is not provided as part of
85 the monitor name, the C(partition) option is used instead.
86 type: list
87 elements: str
88 slow_ramp_time:
89 description:
90 - Sets the ramp-up time (in seconds) to gradually ramp up the load on
91 newly added or freshly detected up pool members.
92 type: int
93 reselect_tries:
94 description:
95 - Sets the number of times the system tries to contact a pool member
96 after a passive failure.
97 type: int
98 service_down_action:
99 description:
100 - Sets the action to take when node goes down in pool.
101 type: str
102 choices:
103 - none
104 - reset
105 - drop
106 - reselect
107 partition:
108 description:
109 - Device partition on which to manage resources.
110 type: str
111 default: Common
112 state:
113 description:
114 - When C(present), guarantees the pool exists with the provided
115 attributes.
116 - When C(absent), removes the pool from the system.
117 type: str
118 choices:
119 - absent
120 - present
121 default: present
122 metadata:
123 description:
124 - Arbitrary key/value pairs you can attach to a pool. This is useful in
125 situations where you might want to annotate a pool to be managed by Ansible.
126 - Key names are stored as strings; this includes names that are numbers.
127 - Values for all of the keys are stored as strings; this includes values
128 that are numbers.
129 - Data will be persisted, not ephemeral.
130 type: raw
131 priority_group_activation:
132 description:
133 - Specifies whether the system load balances traffic according to the priority
134 number assigned to the pool member.
135 - When creating a new pool, if this parameter is not specified, the default of
136 C(0) is used.
137 - To disable this setting, provide the value C(0).
138 - Once you enable this setting, you can specify pool member priority when you
139 create a new pool or on a pool member's properties screen.
140 - The system treats same-priority pool members as a group.
141 - To enable priority group activation, provide a number from C(0) to C(65535)
142 that represents the minimum number of members that must be available in one
143 priority group before the system directs traffic to members in a lower
144 priority group.
145 - When a sufficient number of members become available in the higher priority
146 group, the system again directs traffic to the higher priority group.
147 type: int
148 aliases:
149 - minimum_active_members
150 min_up_members:
151 description:
152 - Specifies the minimum number of pool members that must be up,
153 - otherwise, the system takes the action specified in the C(min-up-members-action) option.
154 - Use this option for gateway pools in a redundant system where a unit number is applied to the pool.
155 - This indicates the pool is configured only on the specified unit.
156 - When creating a new pool, if this parameter is not specified, the default is C(0).
157 type: int
158 min_up_members_action:
159 description:
160 - Specifies the action to take if C(min_up_members_checking) is C(enabled) and the number of active pool members
161 falls below the number specified in the C(min_up_members) option.
162 - When creating a new pool, if this parameter is not specified, the default is C(failover).
163 type: str
164 choices:
165 - failover
166 - reboot
167 - restart-all
168 min_up_members_checking:
169 description:
170 - Enables or disables the C(min_up_members) feature.
171 - If you enable this feature, you must also specify a value for both the C(min_up_members) and
172 C(min_up_members_action) options.
173 - When creating a new pool, if this parameter is not specified, the default is C(disabled).
174 type: str
175 choices:
176 - enabled
177 - disabled
178 aggregate:
179 description:
180 - List of pool definitions to be created, modified, or removed.
181 - When using C(aggregates), if one of the aggregate definitions is invalid, the aggregate run will fail,
182 indicating the error it last encountered.
183 - The module will B(NOT) rollback any changes it has made prior to encountering the error.
184 - The module also will not indicate which changes were made prior to failure. Therefore we strongly advise
185 you run the module in C(check) mode to ensure basic validation prior to executing this module.
186 type: list
187 elements: dict
188 suboptions:
189 description:
190 description:
191 - Specifies descriptive text that identifies the pool.
192 type: str
193 name:
194 description:
195 - Pool name
196 type: str
197 aliases:
198 - pool
199 lb_method:
200 description:
201 - Load balancing method. When creating a new pool, if this value is not
202 specified, the default of C(round-robin) is used.
203 type: str
204 choices:
205 - dynamic-ratio-member
206 - dynamic-ratio-node
207 - fastest-app-response
208 - fastest-node
209 - least-connections-member
210 - least-connections-node
211 - least-sessions
212 - observed-member
213 - observed-node
214 - predictive-member
215 - predictive-node
216 - ratio-least-connections-member
217 - ratio-least-connections-node
218 - ratio-member
219 - ratio-node
220 - ratio-session
221 - round-robin
222 - weighted-least-connections-member
223 - weighted-least-connections-node
224 monitor_type:
225 description:
226 - Monitor rule type when C(monitors) is specified.
227 - When creating a new pool, if this value is not specified, the default
228 of C(and_list) is used.
229 - When C(single), ensures all specified monitors are checked, but
230 additionally includes checks to make sure you only specified a single
231 monitor.
232 - When C(and_list), ensures B(all) monitors are checked.
233 - When C(m_of_n), ensures C(quorum) of C(monitors) are checked. C(m_of_n)
234 B(requires) a C(quorum) of 1 or greater be set either in the playbook,
235 or already exist on the device.
236 - Both C(single) and C(and_list) are functionally identical, as BIG-IP
237 considers all monitors as "a list".
238 type: str
239 aliases:
240 - availability_requirements_type
241 choices:
242 - and_list
243 - m_of_n
244 - single
245 quorum:
246 description:
247 - Monitor quorum value when C(monitor_type) is C(m_of_n).
248 - Quorum must be a value of 1 or greater when C(monitor_type) is C(m_of_n).
249 type: int
250 aliases:
251 - availability_requirements_at_least
252 monitors:
253 description:
254 - Monitor template name list. If the partition is not provided as part of
255 the monitor name, the C(partition) option is used instead.
256 type: list
257 elements: str
258 slow_ramp_time:
259 description:
260 - Sets the ramp-up time (in seconds) to gradually ramp up the load on
261 newly added or freshly detected up pool members.
262 type: int
263 reselect_tries:
264 description:
265 - Sets the number of times the system tries to contact a pool member
266 after a passive failure.
267 type: int
268 service_down_action:
269 description:
270 - Sets the action to take when node goes down in pool.
271 type: str
272 choices:
273 - none
274 - reset
275 - drop
276 - reselect
277 partition:
278 description:
279 - Device partition on which to manage resources.
280 type: str
281 default: Common
282 state:
283 description:
284 - When C(present), guarantees the pool exists with the provided
285 attributes.
286 - When C(absent), removes the pool from the system.
287 type: str
288 choices:
289 - absent
290 - present
291 default: present
292 metadata:
293 description:
294 - Arbitrary key/value pairs you can attach to a pool. This is useful in
295 situations where you might want to annotate a pool to be managed by Ansible.
296 - Key names are stored as strings; this includes names that are numbers.
297 - Values for all of the keys are stored as strings; this includes values
298 that are numbers.
299 - Data will be persisted, not ephemeral.
300 type: raw
301 priority_group_activation:
302 description:
303 - Specifies whether the system load balances traffic according to the priority
304 number assigned to the pool member.
305 - When creating a new pool, if this parameter is not specified, the default of
306 C(0) is used.
307 - To disable this setting, provide the value C(0).
308 - Once you enable this setting, you can specify pool member priority when you
309 create a new pool or on a pool member's properties screen.
310 - The system treats same-priority pool members as a group.
311 - To enable priority group activation, provide a number from C(0) to C(65535)
312 that represents the minimum number of members that must be available in one
313 priority group before the system directs traffic to members in a lower
314 priority group.
315 - When a sufficient number of members become available in the higher priority
316 group, the system again directs traffic to the higher priority group.
317 type: int
318 aliases:
319 - minimum_active_members
320 min_up_members:
321 description:
322 - Specifies the minimum number of pool members that must be up,
323 - otherwise, the system takes the action specified in the C(min-up-members-action) option.
324 - Use this option for gateway pools in a redundant system where a unit number is applied to the pool.
325 - This indicates the pool is configured only on the specified unit.
326 - When creating a new pool, if this parameter is not specified, the default is C(0).
327 type: int
328 min_up_members_action:
329 description:
330 - Specifies the action to take if C(min_up_members_checking) is C(enabled) and the number of active pool members
331 falls below the number specified in the C(min_up_members) option.
332 - When creating a new pool, if this parameter is not specified, the default is C(failover).
333 type: str
334 choices:
335 - failover
336 - reboot
337 - restart-all
338 min_up_members_checking:
339 description:
340 - Enables or disables the C(min_up_members) feature.
341 - If you enable this feature, you must also specify a value for both the C(min_up_members) and
342 C(min_up_members_action) options.
343 - When creating a new pool, if this parameter is not specified, the default is C(disabled).
344 type: str
345 choices:
346 - enabled
347 - disabled
348 aliases:
349 - pools
350 replace_all_with:
351 description:
352 - Removes pools not defined in the C(aggregate) parameter.
353 - This operation is all or none, meaning it will stop if there are some pools
354 that cannot be removed.
355 type: bool
356 default: false
357 aliases:
358 - purge
359 extends_documentation_fragment: f5networks.f5_modules.f5
360 author:
361 - Tim Rupp (@caphrim007)
362 - Wojciech Wypior (@wojtek0806)
363 '''
364
365 EXAMPLES = r'''
366 - name: Create pool
367 bigip_pool:
368 state: present
369 name: my-pool
370 partition: Common
371 lb_method: least-connections-member
372 slow_ramp_time: 120
373 provider:
374 server: lb.mydomain.com
375 user: admin
376 password: secret
377 delegate_to: localhost
378
379 - name: Modify load balancer method
380 bigip_pool:
381 state: present
382 name: my-pool
383 partition: Common
384 lb_method: round-robin
385 provider:
386 server: lb.mydomain.com
387 user: admin
388 password: secret
389 delegate_to: localhost
390
391 - name: Set a single monitor (with enforcement)
392 bigip_pool:
393 state: present
394 name: my-pool
395 partition: Common
396 monitor_type: single
397 monitors:
398 - http
399 provider:
400 server: lb.mydomain.com
401 user: admin
402 password: secret
403 delegate_to: localhost
404
405 - name: Set a single monitor (without enforcement)
406 bigip_pool:
407 state: present
408 name: my-pool
409 partition: Common
410 monitors:
411 - http
412 provider:
413 server: lb.mydomain.com
414 user: admin
415 password: secret
416 delegate_to: localhost
417
418 - name: Set multiple monitors (all must succeed)
419 bigip_pool:
420 state: present
421 name: my-pool
422 partition: Common
423 monitor_type: and_list
424 monitors:
425 - http
426 - tcp
427 provider:
428 server: lb.mydomain.com
429 user: admin
430 password: secret
431 delegate_to: localhost
432
433 - name: Set multiple monitors (at least 1 must succeed)
434 bigip_pool:
435 state: present
436 name: my-pool
437 partition: Common
438 monitor_type: m_of_n
439 quorum: 1
440 monitors:
441 - http
442 - tcp
443 provider:
444 server: lb.mydomain.com
445 user: admin
446 password: secret
447 delegate_to: localhost
448
449 - name: Set multiple monitors (at least 2 must succeed)
450 bigip_pool:
451 state: present
452 name: my-pool
453 partition: Common
454 availability_requirements_type: m_of_n
455 availability_requirements_at_least: 2
456 monitors:
457 - http
458 - tcp
459 provider:
460 server: lb.mydomain.com
461 user: admin
462 password: secret
463 delegate_to: localhost
464
465 - name: Delete pool
466 bigip_pool:
467 state: absent
468 name: my-pool
469 partition: Common
470 provider:
471 server: lb.mydomain.com
472 user: admin
473 password: secret
474 delegate_to: localhost
475
476 - name: Add metadata to pool
477 bigip_pool:
478 state: present
479 name: my-pool
480 partition: Common
481 metadata:
482 ansible: 2.4
483 updated_at: 2017-12-20T17:50:46Z
484 provider:
485 server: lb.mydomain.com
486 user: admin
487 password: secret
488 delegate_to: localhost
489
490 - name: Add pools Aggregate
491 bigip_pool:
492 aggregate:
493 - name: my-pool
494 partition: Common
495 lb_method: least-connections-member
496 slow_ramp_time: 120
497 - name: my-pool2
498 partition: Common
499 lb_method: least-sessions
500 slow_ramp_time: 120
501 - name: my-pool3
502 partition: Common
503 lb_method: round-robin
504 slow_ramp_time: 120
505 provider:
506 server: lb.mydomain.com
507 user: admin
508 password: secret
509 delegate_to: localhost
510
511 - name: Add pools Aggregate, purge others
512 bigip_pool:
513 aggregate:
514 - name: my-pool
515 partition: Common
516 lb_method: least-connections-member
517 slow_ramp_time: 120
518 - name: my-pool2
519 partition: Common
520 lb_method: least-sessions
521 slow_ramp_time: 120
522 - name: my-pool3
523 partition: Common
524 lb_method: round-robin
525 slow_ramp_time: 120
526 replace_all_with: true
527 provider:
528 server: lb.mydomain.com
529 user: admin
530 password: secret
531 delegate_to: localhost
532 '''
533
534 RETURN = r'''
535 monitor_type:
536 description:
537 - Changed value for the monitor_type of the pool.
538 returned: changed
539 type: str
540 sample: m_of_n
541 quorum:
542 description: The quorum that was set on the pool.
543 returned: changed
544 type: int
545 sample: 2
546 monitors:
547 description: Monitors set on the pool.
548 returned: changed
549 type: list
550 sample: ['/Common/http', '/Common/gateway_icmp']
551 service_down_action:
552 description: Service down action that is set on the pool.
553 returned: changed
554 type: str
555 sample: reset
556 description:
557 description: Description set on the pool.
558 returned: changed
559 type: str
560 sample: Pool of web servers
561 lb_method:
562 description: The load balancing method set for the pool.
563 returned: changed
564 type: str
565 sample: round-robin
566 slow_ramp_time:
567 description: The new value set for the slow ramp-up time.
568 returned: changed
569 type: int
570 sample: 500
571 reselect_tries:
572 description: The new value set for the number of tries to contact member.
573 returned: changed
574 type: int
575 sample: 10
576 metadata:
577 description: The new value of the pool.
578 returned: changed
579 type: dict
580 sample: {'key1': 'foo', 'key2': 'bar'}
581 priority_group_activation:
582 description: The new minimum number of members to activate the priority group.
583 returned: changed
584 type: int
585 sample: 10
586 replace_all_with:
587 description: Purges all non-aggregate pools from device
588 returned: changed
589 type: bool
590 sample: true
591 '''
592
593 import re
594 from copy import deepcopy
595 from datetime import datetime
596
597 from ansible.module_utils.urls import urlparse
598 from ansible.module_utils.basic import (
599 AnsibleModule, env_fallback
600 )
601 from ansible.module_utils.six import iteritems
602
603 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import remove_default_spec
604
605 from ..module_utils.bigip import F5RestClient
606 from ..module_utils.common import (
607 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
608 )
609 from ..module_utils.compare import cmp_str_with_none
610 from ..module_utils.icontrol import (
611 TransactionContextManager, tmos_version
612 )
613 from ..module_utils.teem import send_teem
614
615
616 class Parameters(AnsibleF5Parameters):
617 api_map = {
618 'loadBalancingMode': 'lb_method',
619 'slowRampTime': 'slow_ramp_time',
620 'reselectTries': 'reselect_tries',
621 'serviceDownAction': 'service_down_action',
622 'monitor': 'monitors',
623 'minActiveMembers': 'priority_group_activation',
624 'minUpMembers': 'min_up_members',
625 'minUpMembersAction': 'min_up_members_action',
626 'minUpMembersChecking': 'min_up_members_checking',
627 }
628 api_attributes = [
629 'description',
630 'name',
631 'loadBalancingMode',
632 'monitor',
633 'slowRampTime',
634 'reselectTries',
635 'serviceDownAction',
636 'metadata',
637 'minActiveMembers',
638 'minUpMembers',
639 'minUpMembersAction',
640 'minUpMembersChecking',
641 ]
642
643 returnables = [
644 'monitor_type',
645 'quorum',
646 'monitors',
647 'service_down_action',
648 'description',
649 'lb_method',
650 'slow_ramp_time',
651 'reselect_tries',
652 'monitor',
653 'name',
654 'partition',
655 'metadata',
656 'priority_group_activation',
657 'min_up_members',
658 'min_up_members_action',
659 'min_up_members_checking',
660 ]
661
662 updatables = [
663 'monitor_type',
664 'quorum',
665 'monitors',
666 'service_down_action',
667 'description',
668 'lb_method',
669 'slow_ramp_time',
670 'reselect_tries',
671 'metadata',
672 'priority_group_activation',
673 'min_up_members',
674 'min_up_members_action',
675 'min_up_members_checking',
676 ]
677
678 @property
679 def lb_method(self):
680 lb_method = self._values['lb_method']
681 if lb_method is None:
682 return None
683
684 spec = ArgumentSpec()
685 if lb_method not in spec.lb_choice:
686 raise F5ModuleError('Provided lb_method is unknown')
687 return lb_method
688
689 def _verify_quorum_type(self, quorum):
690 try:
691 if quorum is None:
692 return None
693 return int(quorum)
694 except ValueError:
695 raise F5ModuleError(
696 "The specified 'quorum' must be an integer."
697 )
698
699 @property
700 def monitors(self):
701 if self._values['monitors'] is None:
702 return None
703 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
704 if self.monitor_type == 'm_of_n':
705 monitors = ' '.join(monitors)
706 result = 'min %s of { %s }' % (self.quorum, monitors)
707 else:
708 result = ' and '.join(monitors).strip()
709 return result
710
711 @property
712 def priority_group_activation(self):
713 if self._values['priority_group_activation'] is None:
714 return None
715 return int(self._values['priority_group_activation'])
716
717 @property
718 def min_up_members(self):
719 if self._values['min_up_members'] is None:
720 return None
721 return int(self._values['min_up_members'])
722
723 @property
724 def min_up_members_action(self):
725 if self._values['min_up_members_action'] is None:
726 return None
727 return self._values['min_up_members_action']
728
729 @property
730 def min_up_members_checking(self):
731 if self._values['min_up_members_checking'] is None:
732 return None
733 return self._values['min_up_members_checking']
734
735
736 class ApiParameters(Parameters):
737 @property
738 def description(self):
739 if self._values['description'] in [None, 'none']:
740 return None
741 return self._values['description']
742
743 @property
744 def quorum(self):
745 if self._values['monitors'] is None:
746 return None
747 pattern = r'min\s+(?P<quorum>\d+)\s+of'
748 matches = re.search(pattern, self._values['monitors'])
749 if matches:
750 quorum = matches.group('quorum')
751 else:
752 quorum = None
753 result = self._verify_quorum_type(quorum)
754 return result
755
756 @property
757 def monitor_type(self):
758 if self._values['monitors'] is None:
759 return None
760 pattern = r'min\s+\d+\s+of'
761 matches = re.search(pattern, self._values['monitors'])
762 if matches:
763 return 'm_of_n'
764 else:
765 return 'and_list'
766
767 @property
768 def monitors_list(self):
769 if self._values['monitors'] is None:
770 return []
771 try:
772 result = re.findall(r'/[\w-]+/[^\s}]+', self._values['monitors'])
773 return result
774 except Exception:
775 return self._values['monitors']
776
777 @property
778 def metadata(self):
779 if self._values['metadata'] is None:
780 return None
781 result = []
782 for md in self._values['metadata']:
783 tmp = dict(name=str(md['name']))
784 if 'value' in md:
785 tmp['value'] = str(md['value'])
786 else:
787 tmp['value'] = ''
788 result.append(tmp)
789 return result
790
791
792 class ModuleParameters(Parameters):
793 @property
794 def description(self):
795 if self._values['description'] is None:
796 return None
797 elif self._values['description'] in ['none', '']:
798 return ''
799 return self._values['description']
800
801 @property
802 def monitors_list(self):
803 if self._values['monitors'] is None:
804 return []
805 return self._values['monitors']
806
807 @property
808 def quorum(self):
809 if self._values['quorum'] is None:
810 return None
811 result = self._verify_quorum_type(self._values['quorum'])
812 return result
813
814 @property
815 def monitor_type(self):
816 if self._values['monitor_type'] is None:
817 return None
818 return self._values['monitor_type']
819
820 @property
821 def metadata(self):
822 if self._values['metadata'] is None:
823 return None
824 if self._values['metadata'] == '':
825 return []
826 result = []
827 try:
828 for k, v in iteritems(self._values['metadata']):
829 tmp = dict(name=str(k))
830 if v:
831 tmp['value'] = str(v)
832 else:
833 tmp['value'] = ''
834 result.append(tmp)
835 except AttributeError:
836 raise F5ModuleError(
837 "The 'metadata' parameter must be a dictionary of key/value pairs."
838 )
839 return result
840
841
842 class Changes(Parameters):
843 def to_return(self):
844 result = {}
845 for returnable in self.returnables:
846 try:
847 result[returnable] = getattr(self, returnable)
848 except Exception:
849 pass
850 result = self._filter_params(result)
851 return result
852
853 @property
854 def monitors(self):
855 if self._values['monitors'] is None:
856 return None
857 return self._values['monitors']
858
859
860 class UsableChanges(Changes):
861 @property
862 def monitors(self):
863 monitor_string = self._values['monitors']
864 if monitor_string is None:
865 return None
866
867 if '{' in monitor_string and '}' in monitor_string:
868 tmp = monitor_string.strip('}').split('{')
869 monitor = ''.join(tmp).rstrip()
870 return monitor
871
872 return monitor_string
873
874
875 class ReportableChanges(Changes):
876 @property
877 def monitors(self):
878 result = sorted(re.findall(r'/[\w-]+/[^\s}]+', self._values['monitors']))
879 return result
880
881 @property
882 def monitor_type(self):
883 pattern = r'min\s+\d+\s+of'
884 matches = re.search(pattern, self._values['monitors'])
885 if matches:
886 return 'm_of_n'
887 else:
888 return 'and_list'
889
890 @property
891 def metadata(self):
892 result = dict()
893 for x in self._values['metadata']:
894 result[x['name']] = x['value']
895 return result
896
897
898 class Difference(object):
899 def __init__(self, want, have=None):
900 self.want = want
901 self.have = have
902
903 def compare(self, param):
904 try:
905 result = getattr(self, param)
906 return result
907 except AttributeError:
908 return self.__default(param)
909
910 def __default(self, param):
911 attr1 = getattr(self.want, param)
912 try:
913 attr2 = getattr(self.have, param)
914 if attr1 != attr2:
915 return attr1
916 except AttributeError:
917 return attr1
918
919 def to_tuple(self, items):
920 result = []
921 for x in items:
922 tmp = [(str(k), str(v)) for k, v in iteritems(x)]
923 result += tmp
924 return result
925
926 def _diff_complex_items(self, want, have):
927 if want == [] and have is None:
928 return None
929 if want is None:
930 return None
931 w = self.to_tuple(want)
932 h = self.to_tuple(have)
933 if set(w).issubset(set(h)):
934 return None
935 else:
936 return want
937
938 @property
939 def description(self):
940 return cmp_str_with_none(self.want.description, self.have.description)
941
942 def _monitors_and_quorum(self):
943 if self.want.monitor_type is None:
944 self.want.update(dict(monitor_type=self.have.monitor_type))
945 if self.want.monitor_type == 'm_of_n':
946 if self.want.quorum is None:
947 self.want.update(dict(quorum=self.have.quorum))
948 if self.want.quorum is None or self.want.quorum < 1:
949 raise F5ModuleError(
950 "Quorum value must be specified with monitor_type 'm_of_n'."
951 )
952 if self.want.monitors != self.have.monitors:
953 if self.want.monitors is None or not self.want.monitors_list:
954 return None
955 return dict(
956 monitors=self.want.monitors
957 )
958 elif self.want.monitor_type == 'and_list':
959 if self.want.quorum is not None and self.want.quorum > 0:
960 raise F5ModuleError(
961 "Quorum values have no effect when used with 'and_list'."
962 )
963 if self.want.monitors != self.have.monitors:
964 if self.want.monitors is None or not self.want.monitors_list:
965 return None
966 return dict(
967 monitors=self.want.monitors
968 )
969 elif self.want.monitor_type == 'single':
970 if len(self.want.monitors_list) > 1:
971 raise F5ModuleError(
972 "When using a 'monitor_type' of 'single', only one monitor may be provided."
973 )
974 elif len(self.have.monitors_list) > 1 and len(self.want.monitors_list) == 0:
975 # Handle instances where there already exists many monitors, and the
976 # user runs the module again specifying that the monitor_type should be
977 # changed to 'single'
978 raise F5ModuleError(
979 "A single monitor must be specified if more than one monitor currently exists on your pool."
980 )
981 # Update to 'and_list' here because the above checks are all that need
982 # to be done before we change the value back to what is expected by
983 # BIG-IP.
984 #
985 # Remember that 'single' is nothing more than a fancy way of saying
986 # "and_list plus some extra checks"
987 self.want.update(dict(monitor_type='and_list'))
988 if self.want.monitors != self.have.monitors:
989 if self.want.monitors is None or not self.want.monitors_list:
990 return None
991 return dict(
992 monitors=self.want.monitors
993 )
994
995 @property
996 def monitor_type(self):
997 return self._monitors_and_quorum()
998
999 @property
1000 def quorum(self):
1001 return self._monitors_and_quorum()
1002
1003 @property
1004 def monitors(self):
1005 if self.want.monitors is None:
1006 return None
1007 if not self.want.monitors_list and self.have.monitors is None:
1008 # Idempotency check - removing monitors from a device where no monitors exists
1009 return None
1010 # when monitors_list is [], remove all the monitors
1011 if not self.want.monitors_list:
1012 # monitors is '' in the case of monitor_type and_list and min <quorum> of { } in case monitor_type m_of_n
1013 return {'monitors': ''}
1014 if self.want.monitor_type is None:
1015 self.want.update(dict(monitor_type=self.have.monitor_type))
1016 if not self.want.monitors and self.want.monitor_type is not None:
1017 raise F5ModuleError(
1018 "The 'monitors' parameter cannot be empty when 'monitor_type' parameter is specified"
1019 )
1020 if self.want.monitors != self.have.monitors:
1021 return self.want.monitors
1022
1023 @property
1024 def metadata(self):
1025 if self.want.metadata is None:
1026 return None
1027 elif len(self.want.metadata) == 0 and self.have.metadata is None:
1028 return None
1029 elif len(self.want.metadata) == 0:
1030 return []
1031 elif self.have.metadata is None:
1032 return self.want.metadata
1033 result = self._diff_complex_items(self.want.metadata, self.have.metadata)
1034 return result
1035
1036
1037 class ModuleManager(object):
1038 def __init__(self, *args, **kwargs):
1039 self.module = kwargs.get('module', None)
1040 self.client = F5RestClient(**self.module.params)
1041 self.want = None
1042 self.have = None
1043 self.changes = None
1044 self.replace_all_with = None
1045 self.purge_links = list()
1046
1047 def exec_module(self):
1048 start = datetime.now().isoformat()
1049 version = tmos_version(self.client)
1050 wants = None
1051 if self.module.params['replace_all_with']:
1052 self.replace_all_with = True
1053
1054 if self.module.params['aggregate']:
1055 wants = self.merge_defaults_for_aggregate(self.module.params)
1056
1057 result = dict()
1058 changed = False
1059
1060 if self.replace_all_with and self.purge_links:
1061 self.purge()
1062 changed = True
1063
1064 if self.module.params['aggregate']:
1065 result['aggregate'] = list()
1066 for want in wants:
1067 output = self.execute(want)
1068 if output['changed']:
1069 changed = output['changed']
1070 result['aggregate'].append(output)
1071 else:
1072 output = self.execute(self.module.params)
1073 if output['changed']:
1074 changed = output['changed']
1075 result.update(output)
1076 if changed:
1077 result['changed'] = True
1078 send_teem(start, self.client, self.module, version)
1079 return result
1080
1081 def merge_defaults_for_aggregate(self, params):
1082 defaults = deepcopy(params)
1083 aggregate = defaults.pop('aggregate')
1084
1085 for i, j in enumerate(aggregate):
1086 for k, v in iteritems(defaults):
1087 if k != 'replace_all_with':
1088 if j.get(k, None) is None and v is not None:
1089 aggregate[i][k] = v
1090
1091 if self.replace_all_with:
1092 self.compare_aggregate_names(aggregate)
1093
1094 return aggregate
1095
1096 def compare_aggregate_names(self, items):
1097 on_device = self._read_purge_collection()
1098 if not on_device:
1099 return False
1100 aggregates = [item['name'] for item in items]
1101 collection = [item['name'] for item in on_device]
1102
1103 diff = set(collection) - set(aggregates)
1104
1105 if diff:
1106 to_purge = [item['selfLink'] for item in on_device if item['name'] in diff]
1107 self.purge_links.extend(to_purge)
1108
1109 def execute(self, params=None):
1110 self.want = ModuleParameters(params=params)
1111 self.have = ApiParameters()
1112 self.changes = UsableChanges()
1113
1114 changed = False
1115 result = dict()
1116 state = params['state']
1117
1118 if state == "present":
1119 changed = self.present()
1120 elif state == "absent":
1121 changed = self.absent()
1122
1123 reportable = ReportableChanges(params=self.changes.to_return())
1124 changes = reportable.to_return()
1125 result.update(**changes)
1126 result.update(dict(changed=changed))
1127 self._announce_deprecations(result)
1128 return result
1129
1130 def _announce_deprecations(self, result):
1131 warnings = result.pop('__warnings', [])
1132 for warning in warnings:
1133 self.module.deprecate(
1134 msg=warning['msg'],
1135 version=warning['version']
1136 )
1137
1138 def _set_changed_options(self):
1139 changed = {}
1140 for key in Parameters.returnables:
1141 if getattr(self.want, key) is not None:
1142 changed[key] = getattr(self.want, key)
1143 if changed:
1144 self.changes = UsableChanges(params=changed)
1145
1146 def _update_changed_options(self):
1147 diff = Difference(self.want, self.have)
1148 updatables = Parameters.updatables
1149 changed = dict()
1150 for k in updatables:
1151 change = diff.compare(k)
1152 if change is None:
1153 continue
1154 else:
1155 if isinstance(change, dict):
1156 changed.update(change)
1157 else:
1158 changed[k] = change
1159 if changed:
1160 self.changes = UsableChanges(params=changed)
1161 return True
1162 return False
1163
1164 def present(self):
1165 if self.exists():
1166 return self.update()
1167 else:
1168 return self.create()
1169
1170 def absent(self):
1171 if self.exists():
1172 return self.remove()
1173 return False
1174
1175 def should_update(self):
1176 result = self._update_changed_options()
1177 if result:
1178 return True
1179 return False
1180
1181 def update(self):
1182 self.have = self.read_current_from_device()
1183 if not self.should_update():
1184 return False
1185 if self.module.check_mode:
1186 return True
1187 self.update_on_device()
1188 return True
1189
1190 def remove(self):
1191 if self.module.check_mode:
1192 return True
1193 self.remove_from_device()
1194 if self.exists():
1195 raise F5ModuleError("Failed to delete the Pool")
1196 return True
1197
1198 def purge(self):
1199 if self.module.check_mode:
1200 return True
1201 self.purge_from_device()
1202 return True
1203
1204 def create(self):
1205 if self.want.monitor_type is not None:
1206 if not self.want.monitors_list:
1207 raise F5ModuleError(
1208 "The 'monitors' parameter cannot be empty when 'monitor_type' parameter is specified"
1209 )
1210 else:
1211 if self.want.monitor_type is None:
1212 self.want.update(dict(monitor_type='and_list'))
1213
1214 if self.want.monitor_type == 'm_of_n' and (self.want.quorum is None or self.want.quorum < 1):
1215 raise F5ModuleError(
1216 "Quorum value must be specified with monitor_type 'm_of_n'."
1217 )
1218 elif self.want.monitor_type == 'and_list' and self.want.quorum is not None and self.want.quorum > 0:
1219 raise F5ModuleError(
1220 "Quorum values have no effect when used with 'and_list'."
1221 )
1222 elif self.want.monitor_type == 'single' and len(self.want.monitors_list) > 1:
1223 raise F5ModuleError(
1224 "When using a 'monitor_type' of 'single', only one monitor may be provided"
1225 )
1226 if self.want.priority_group_activation is None:
1227 self.want.update({'priority_group_activation': 0})
1228
1229 if self.want.min_up_members is None:
1230 self.want.update({'min_up_members': 0})
1231
1232 if self.want.min_up_members_action is None:
1233 self.want.update({'min_up_members_action': 'failover'})
1234
1235 if self.want.min_up_members_checking is None:
1236 self.want.update({'min_up_members_checking': 'disabled'})
1237
1238 self._set_changed_options()
1239 if self.module.check_mode:
1240 return True
1241 self.create_on_device()
1242 return True
1243
1244 def _read_purge_collection(self):
1245 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/".format(
1246 self.client.provider['server'],
1247 self.client.provider['server_port'],
1248 )
1249
1250 query = "?$select=name,selfLink"
1251 resp = self.client.api.get(uri + query)
1252
1253 try:
1254 response = resp.json()
1255 except ValueError as ex:
1256 raise F5ModuleError(str(ex))
1257
1258 if 'code' in response and response['code'] == 400:
1259 if 'message' in response:
1260 raise F5ModuleError(response['message'])
1261 else:
1262 raise F5ModuleError(resp.content)
1263 if 'items' in response:
1264 return response['items']
1265 return []
1266
1267 def create_on_device(self):
1268 params = self.changes.api_params()
1269 params['name'] = self.want.name
1270 params['partition'] = self.want.partition
1271 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/".format(
1272 self.client.provider['server'],
1273 self.client.provider['server_port']
1274 )
1275 resp = self.client.api.post(uri, json=params)
1276 try:
1277 response = resp.json()
1278 except ValueError as ex:
1279 raise F5ModuleError(str(ex))
1280
1281 if 'code' in response and response['code'] in [400, 403]:
1282 if 'message' in response:
1283 raise F5ModuleError(response['message'])
1284 else:
1285 raise F5ModuleError(resp.content)
1286
1287 def update_on_device(self):
1288 params = self.changes.api_params()
1289 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}".format(
1290 self.client.provider['server'],
1291 self.client.provider['server_port'],
1292 transform_name(self.want.partition, self.want.name)
1293 )
1294 resp = self.client.api.patch(uri, json=params)
1295 try:
1296 response = resp.json()
1297 except ValueError as ex:
1298 raise F5ModuleError(str(ex))
1299
1300 if 'code' in response and response['code'] == 400:
1301 if 'message' in response:
1302 raise F5ModuleError(response['message'])
1303 else:
1304 raise F5ModuleError(resp.content)
1305
1306 def exists(self):
1307 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}".format(
1308 self.client.provider['server'],
1309 self.client.provider['server_port'],
1310 transform_name(self.want.partition, self.want.name)
1311 )
1312 resp = self.client.api.get(uri)
1313 try:
1314 response = resp.json()
1315 except ValueError as ex:
1316 raise F5ModuleError(str(ex))
1317
1318 if resp.status == 404 or 'code' in response and response['code'] == 404:
1319 return False
1320 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1321 return True
1322
1323 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1324
1325 if resp.status in errors or 'code' in response and response['code'] in errors:
1326 if 'message' in response:
1327 raise F5ModuleError(response['message'])
1328 else:
1329 raise F5ModuleError(resp.content)
1330
1331 def remove_from_device(self):
1332 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}".format(
1333 self.client.provider['server'],
1334 self.client.provider['server_port'],
1335 transform_name(self.want.partition, self.want.name)
1336 )
1337 response = self.client.api.delete(uri)
1338 if response.status == 200:
1339 return True
1340 raise F5ModuleError(response.content)
1341
1342 def read_current_from_device(self):
1343 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}".format(
1344 self.client.provider['server'],
1345 self.client.provider['server_port'],
1346 transform_name(self.want.partition, self.want.name)
1347 )
1348 query = '?expandSubcollections=true'
1349 resp = self.client.api.get(uri + query)
1350 try:
1351 response = resp.json()
1352 except ValueError as ex:
1353 raise F5ModuleError(str(ex))
1354
1355 if 'code' in response and response['code'] == 400:
1356 if 'message' in response:
1357 raise F5ModuleError(response['message'])
1358 else:
1359 raise F5ModuleError(resp.content)
1360 return ApiParameters(params=response)
1361
1362 def _prepare_links(self, collection):
1363 purge_links = list()
1364 purge_paths = [urlparse(link).path for link in collection]
1365
1366 for path in purge_paths:
1367 link = "https://{0}:{1}{2}".format(
1368 self.client.provider['server'],
1369 self.client.provider['server_port'],
1370 path
1371 )
1372 purge_links.append(link)
1373 return purge_links
1374
1375 def purge_from_device(self):
1376 links = self._prepare_links(self.purge_links)
1377
1378 with TransactionContextManager(self.client) as transact:
1379 for link in links:
1380 resp = transact.api.delete(link)
1381
1382 try:
1383 response = resp.json()
1384 except ValueError as ex:
1385 raise F5ModuleError(str(ex))
1386
1387 if 'code' in response and response['code'] == 400:
1388 if 'message' in response:
1389 raise F5ModuleError(response['message'])
1390 else:
1391 raise F5ModuleError(resp.content)
1392 return True
1393
1394
1395 class ArgumentSpec(object):
1396 def __init__(self):
1397 self.lb_choice = [
1398 'dynamic-ratio-member',
1399 'dynamic-ratio-node',
1400 'fastest-app-response',
1401 'fastest-node',
1402 'least-connections-member',
1403 'least-connections-node',
1404 'least-sessions',
1405 'observed-member',
1406 'observed-node',
1407 'predictive-member',
1408 'predictive-node',
1409 'ratio-least-connections-member',
1410 'ratio-least-connections-node',
1411 'ratio-member',
1412 'ratio-node',
1413 'ratio-session',
1414 'round-robin',
1415 'weighted-least-connections-member',
1416 'weighted-least-connections-node'
1417 ]
1418 self.supports_check_mode = True
1419 element_spec = dict(
1420 name=dict(
1421 aliases=['pool']
1422 ),
1423 lb_method=dict(
1424 choices=self.lb_choice
1425 ),
1426 monitor_type=dict(
1427 choices=[
1428 'and_list', 'm_of_n', 'single'
1429 ],
1430 aliases=['availability_requirements_type']
1431 ),
1432 quorum=dict(
1433 type='int',
1434 aliases=['availability_requirements_at_least']
1435 ),
1436 monitors=dict(
1437 type='list',
1438 elements='str',
1439 ),
1440 slow_ramp_time=dict(
1441 type='int'
1442 ),
1443 reselect_tries=dict(
1444 type='int'
1445 ),
1446 service_down_action=dict(
1447 choices=[
1448 'none', 'reset',
1449 'drop', 'reselect'
1450 ]
1451 ),
1452 description=dict(),
1453 metadata=dict(type='raw'),
1454 priority_group_activation=dict(
1455 type='int',
1456 aliases=['minimum_active_members']
1457 ),
1458 min_up_members=dict(
1459 type='int'
1460 ),
1461 min_up_members_action=dict(
1462 choices=['failover', 'reboot', 'restart-all']
1463 ),
1464 min_up_members_checking=dict(
1465 choices=['enabled', 'disabled']
1466 ),
1467 state=dict(
1468 default='present',
1469 choices=['present', 'absent']
1470 ),
1471 partition=dict(
1472 default='Common',
1473 fallback=(env_fallback, ['F5_PARTITION'])
1474 )
1475 )
1476
1477 aggregate_spec = deepcopy(element_spec)
1478
1479 remove_default_spec(aggregate_spec)
1480 aggregate_spec["state"].update(default="present")
1481 aggregate_spec["partition"].update(default="Common")
1482
1483 argument_spec = dict(
1484 aggregate=dict(
1485 type='list',
1486 elements='dict',
1487 options=aggregate_spec,
1488 aliases=['pools']
1489 ),
1490 partition=dict(
1491 default='Common',
1492 fallback=(env_fallback, ['F5_PARTITION'])
1493 ),
1494 replace_all_with=dict(
1495 default='no',
1496 type='bool',
1497 aliases=['purge']
1498 )
1499 )
1500
1501 self.mutually_exclusive = [
1502 ['name', 'aggregate']
1503 ]
1504 self.required_one_of = [
1505 ['name', 'aggregate']
1506 ]
1507
1508 self.argument_spec = {}
1509 self.argument_spec.update(element_spec)
1510 self.argument_spec.update(f5_argument_spec)
1511 self.argument_spec.update(argument_spec)
1512
1513
1514 def main():
1515 spec = ArgumentSpec()
1516
1517 module = AnsibleModule(
1518 argument_spec=spec.argument_spec,
1519 supports_check_mode=spec.supports_check_mode,
1520 mutually_exclusive=spec.mutually_exclusive,
1521 required_one_of=spec.required_one_of
1522 )
1523
1524 try:
1525 mm = ModuleManager(module=module)
1526 results = mm.exec_module()
1527 module.exit_json(**results)
1528 except F5ModuleError as ex:
1529 module.fail_json(msg=str(ex))
1530
1531
1532 if __name__ == '__main__':
1533 main()