Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # Copyright: (c) 2013, Matt Hite <[email protected]>
6 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: bigip_pool_member
14 short_description: Manages F5 BIG-IP LTM pool members
15 description:
16 - Manages F5 BIG-IP LTM pool members via the REST API.
17 version_added: "1.0.0"
18 options:
19 aggregate:
20 description:
21 - List of pool member definitions to be created, modified, or removed.
22 - When using C(aggregates), if one of the aggregate definitions is invalid, the aggregate run will fail,
23 indicating the error it last encountered.
24 - The module will B(NOT) rollback any changes it has made prior to encountering the error.
25 - The module also will not indicate what changes were made prior to failure. Therefore we strong advise
26 you run the module in C(check) mode to ensure basic validation prior to executing this module.
27 type: list
28 elements: dict
29 suboptions:
30 name:
31 description:
32 - Name of the node to create or re-use when creating a new pool member.
33 - While this parameter is optional, we recommend specifying this parameter
34 at all times to mitigate any unexpected behavior.
35 - If not specified, a node name is created automatically from either the specified C(address) or C(fqdn).
36 - The C(enabled) state is an alias of C(present).
37 type: str
38 address:
39 description:
40 - IP address of the pool member. This can be either IPv4 or IPv6. When creating a
41 new pool member, one of either C(address) or C(fqdn) must be provided. This
42 parameter cannot be updated after it is set.
43 type: str
44 aliases:
45 - ip
46 - host
47 fqdn:
48 description:
49 - FQDN name of the pool member. This can be any name that is a valid RFC 1123 DNS
50 name. Therefore, the only usable characters are "A" to "Z",
51 "a" to "z", "0" to "9", the hyphen ("-") and the period (".").
52 - FQDN names must include at least one period; delineating the host from
53 the domain. For example, C(host.domain).
54 - FQDN names must end with a letter or a number.
55 - When creating a new pool member, one of either C(address) or C(fqdn) must be
56 provided. This parameter cannot be updated after it is set.
57 type: str
58 aliases:
59 - hostname
60 port:
61 description:
62 - Pool member port.
63 - This value cannot be changed after it has been set.
64 - Parameter must be provided when using aggregates.
65 type: int
66 connection_limit:
67 description:
68 - Pool member connection limit. Setting this to C(0) disables the limit.
69 type: int
70 description:
71 description:
72 - Pool member description.
73 type: str
74 rate_limit:
75 description:
76 - Pool member rate limit (connections-per-second). Setting this to C(0)
77 disables the limit.
78 type: int
79 ratio:
80 description:
81 - Pool member ratio weight. Valid values range from 1 through 100.
82 New pool members -- unless overridden with this value -- default
83 to 1.
84 type: int
85 preserve_node:
86 description:
87 - When state is C(absent), the system attempts to remove the node the pool
88 member references.
89 - The node will not be removed if it is still referenced by other pool
90 members. If this happens, the module will not raise an error.
91 - Setting this to C(true) disables this behavior.
92 type: bool
93 priority_group:
94 description:
95 - Specifies a number representing the priority group for the pool member.
96 - When adding a new member, the default is C(0), meaning the member has no priority.
97 - To specify a priority, you must activate priority group usage when you
98 create a new pool or when adding or removing pool members. When activated,
99 the system load balances traffic according to the priority group number
100 assigned to the pool member.
101 - The higher the number, the higher the priority. So a member with a priority
102 of 3 has higher priority than a member with a priority of 1.
103 type: int
104 fqdn_auto_populate:
105 description:
106 - Specifies whether the system automatically creates ephemeral nodes using
107 the IP addresses returned by the resolution of a DNS query for a node
108 defined by an FQDN.
109 - When C(true), the system generates an ephemeral node for each IP address
110 returned in response to a DNS query for the FQDN of the node. Additionally,
111 when a DNS response indicates the IP address of an ephemeral node no longer
112 exists, the system deletes the ephemeral node.
113 - When C(false), the system resolves a DNS query for the FQDN of the node
114 with the single IP address associated with the FQDN.
115 - When creating a new pool member, the default for this parameter is C(true).
116 - Once set this parameter cannot be changed afterwards.
117 - This parameter is ignored when C(reuse_nodes) is C(true).
118 type: bool
119 reuse_nodes:
120 description:
121 - Reuses node definitions if requested.
122 type: bool
123 default: true
124 monitors:
125 description:
126 - Specifies the health monitors the system currently uses to monitor
127 this resource.
128 type: list
129 elements: str
130 availability_requirements:
131 description:
132 - If you activate more than one health monitor, specifies the number of health
133 monitors that must receive successful responses in order for the link to be
134 considered available.
135 - Specifying an empty string will remove the monitors and revert to inheriting from the pool (default).
136 - Specifying C(none) will remove any health monitoring from the member completely.
137 type: dict
138 suboptions:
139 type:
140 description:
141 - Monitor rule type when C(monitors) is specified.
142 - When creating a new pool, if this value is not specified, the default of
143 C(all) will be used.
144 type: str
145 required: True
146 choices:
147 - all
148 - at_least
149 at_least:
150 description:
151 - Specifies the minimum number of active health monitors that must be successful
152 before the link is considered up.
153 - This parameter is only relevant when a C(type) of C(at_least) is used.
154 - This parameter will be ignored if a type of C(all) is used.
155 type: int
156 ip_encapsulation:
157 description:
158 - Specifies the IP encapsulation using either IPIP (IP encapsulation within IP,
159 RFC 2003) or GRE (Generic Router Encapsulation, RFC 2784) on outbound packets
160 (from BIG-IP system to server-pool member).
161 - When C(none), disables IP encapsulation.
162 - When C(inherit), inherits the IP encapsulation setting from the member's pool.
163 - When any other value, the options are None, Inherit from Pool, and Member Specific.
164 type: str
165 state:
166 description:
167 - Pool member state.
168 type: str
169 choices:
170 - present
171 - absent
172 - enabled
173 - disabled
174 - forced_offline
175 default: present
176 partition:
177 description:
178 - Partition to manage resources on.
179 type: str
180 default: Common
181 aliases:
182 - members
183 pool:
184 description:
185 - Pool name. This pool must exist.
186 type: str
187 required: True
188 name:
189 description:
190 - Name of the node to create or re-use when creating a new pool member.
191 - While this parameter is optional, we recommend specifying this parameter
192 at all times to mitigate any unexpected behavior.
193 - If not specified, a node name is created automatically from either the specified C(address) or C(fqdn).
194 - The C(enabled) state is an alias of C(present).
195 type: str
196 address:
197 description:
198 - IP address of the pool member. This can be either IPv4 or IPv6. When creating a
199 new pool member, one of either C(address) or C(fqdn) must be provided. This
200 parameter cannot be updated after it is set.
201 type: str
202 aliases:
203 - ip
204 - host
205 fqdn:
206 description:
207 - FQDN name of the pool member. This can be any name that is a valid RFC 1123 DNS
208 name. Therefore, the only usable characters are "A" to "Z",
209 "a" to "z", "0" to "9", the hyphen ("-") and the period (".").
210 - FQDN names must include at least one period; delineating the host from
211 the domain. For example, C(host.domain).
212 - FQDN names must end with a letter or a number.
213 - When creating a new pool member, one of either C(address) or C(fqdn) must be
214 provided. This parameter cannot be updated after it is set.
215 type: str
216 aliases:
217 - hostname
218 port:
219 description:
220 - Pool member port.
221 - This value cannot be changed after it has been set.
222 - Parameter must be provided when using aggregates.
223 type: int
224 connection_limit:
225 description:
226 - Pool member connection limit. Setting this to C(0) disables the limit.
227 type: int
228 description:
229 description:
230 - Pool member description.
231 type: str
232 rate_limit:
233 description:
234 - Pool member rate limit (connections-per-second). Setting this to C(0)
235 disables the limit.
236 type: int
237 ratio:
238 description:
239 - Pool member ratio weight. Valid values range from 1 through 100.
240 New pool members -- unless overridden with this value -- default
241 to 1.
242 type: int
243 preserve_node:
244 description:
245 - When state is C(absent), the system attempts to remove the node the pool
246 member references.
247 - The node will not be removed if it is still referenced by other pool
248 members. If this happens, the module will not raise an error.
249 - Setting this to C(true) disables this behavior.
250 type: bool
251 priority_group:
252 description:
253 - Specifies a number representing the priority group for the pool member.
254 - When adding a new member, the default is C(0), meaning the member has no priority.
255 - To specify a priority, you must activate priority group usage when you
256 create a new pool or when adding or removing pool members. When activated,
257 the system load balances traffic according to the priority group number
258 assigned to the pool member.
259 - The higher the number, the higher the priority. So a member with a priority
260 of 3 has higher priority than a member with a priority of 1.
261 type: int
262 fqdn_auto_populate:
263 description:
264 - Specifies whether the system automatically creates ephemeral nodes using
265 the IP addresses returned by the resolution of a DNS query for a node
266 defined by an FQDN.
267 - When C(true), the system generates an ephemeral node for each IP address
268 returned in response to a DNS query for the FQDN of the node. Additionally,
269 when a DNS response indicates the IP address of an ephemeral node no longer
270 exists, the system deletes the ephemeral node.
271 - When C(false), the system resolves a DNS query for the FQDN of the node
272 with the single IP address associated with the FQDN.
273 - When creating a new pool member, the default for this parameter is C(true).
274 - Once set this parameter cannot be changed afterwards.
275 - This parameter is ignored when C(reuse_nodes) is C(true).
276 type: bool
277 reuse_nodes:
278 description:
279 - Reuses node definitions if requested.
280 type: bool
281 default: true
282 monitors:
283 description:
284 - Specifies the health monitors the system currently uses to monitor
285 this resource.
286 type: list
287 elements: str
288 availability_requirements:
289 description:
290 - If you activate more than one health monitor, specifies the number of health
291 monitors that must receive successful responses in order for the link to be
292 considered available.
293 - Specifying an empty string will remove the monitors and revert to inheriting from the pool (default).
294 - Specifying C(none) will remove any health monitoring from the member completely.
295 type: dict
296 suboptions:
297 type:
298 description:
299 - Monitor rule type when C(monitors) is specified.
300 - When creating a new pool, if this value is not specified, the default of
301 C(all) will be used.
302 type: str
303 required: True
304 choices:
305 - all
306 - at_least
307 at_least:
308 description:
309 - Specifies the minimum number of active health monitors that must be successful
310 before the link is considered up.
311 - This parameter is only relevant when a C(type) of C(at_least) is used.
312 - This parameter will be ignored if a type of C(all) is used.
313 type: int
314 ip_encapsulation:
315 description:
316 - Specifies the IP encapsulation using either IPIP (IP encapsulation within IP,
317 RFC 2003) or GRE (Generic Router Encapsulation, RFC 2784) on outbound packets
318 (from BIG-IP system to server-pool member).
319 - When C(none), disables IP encapsulation.
320 - When C(inherit), inherits the IP encapsulation setting from the member's pool.
321 - When any other value, the options are None, Inherit from Pool, and Member Specific.
322 type: str
323 state:
324 description:
325 - Pool member state.
326 type: str
327 choices:
328 - present
329 - absent
330 - enabled
331 - disabled
332 - forced_offline
333 default: present
334 partition:
335 description:
336 - Partition to manage resources on.
337 type: str
338 default: Common
339 replace_all_with:
340 description:
341 - Removes members not defined in the C(aggregate) parameter.
342 - This operation is all or none, meaning it will stop if there are some pool members
343 that cannot be removed.
344 type: bool
345 default: false
346 aliases:
347 - purge
348 extends_documentation_fragment: f5networks.f5_modules.f5
349 author:
350 - Tim Rupp (@caphrim007)
351 - Wojciech Wypior (@wojtek0806)
352 '''
353
354 EXAMPLES = r'''
355 - name: Add pool member
356 bigip_pool_member:
357 pool: my-pool
358 partition: Common
359 name: my-member
360 host: "{{ ansible_default_ipv4['address'] }}"
361 port: 80
362 description: web server
363 connection_limit: 100
364 rate_limit: 50
365 ratio: 2
366 provider:
367 server: lb.mydomain.com
368 user: admin
369 password: secret
370 delegate_to: localhost
371
372 - name: Modify pool member ratio and description
373 bigip_pool_member:
374 pool: my-pool
375 partition: Common
376 name: my-member
377 host: "{{ ansible_default_ipv4['address'] }}"
378 port: 80
379 ratio: 1
380 description: nginx server
381 provider:
382 server: lb.mydomain.com
383 user: admin
384 password: secret
385 delegate_to: localhost
386
387 - name: Remove pool member from pool
388 bigip_pool_member:
389 state: absent
390 pool: my-pool
391 partition: Common
392 name: my-member
393 host: "{{ ansible_default_ipv4['address'] }}"
394 port: 80
395 provider:
396 server: lb.mydomain.com
397 user: admin
398 password: secret
399 delegate_to: localhost
400
401 - name: Force pool member offline
402 bigip_pool_member:
403 state: forced_offline
404 pool: my-pool
405 partition: Common
406 name: my-member
407 host: "{{ ansible_default_ipv4['address'] }}"
408 port: 80
409 provider:
410 server: lb.mydomain.com
411 user: admin
412 password: secret
413 delegate_to: localhost
414
415 - name: Create members with priority groups
416 bigip_pool_member:
417 pool: my-pool
418 partition: Common
419 host: "{{ item.address }}"
420 name: "{{ item.name }}"
421 priority_group: "{{ item.priority_group }}"
422 port: 80
423 provider:
424 server: lb.mydomain.com
425 user: admin
426 password: secret
427 delegate_to: localhost
428 loop:
429 - address: 1.1.1.1
430 name: web1
431 priority_group: 4
432 - address: 2.2.2.2
433 name: web2
434 priority_group: 3
435 - address: 3.3.3.3
436 name: web3
437 priority_group: 2
438 - address: 4.4.4.4
439 name: web4
440 priority_group: 1
441
442 - name: Add pool members aggregate
443 bigip_pool_member:
444 pool: my-pool
445 aggregate:
446 - host: 192.168.1.1
447 partition: Common
448 port: 80
449 description: web server
450 connection_limit: 100
451 rate_limit: 50
452 ratio: 2
453 - host: 192.168.1.2
454 partition: Common
455 port: 80
456 description: web server
457 connection_limit: 100
458 rate_limit: 50
459 ratio: 2
460 - host: 192.168.1.3
461 partition: Common
462 port: 80
463 description: web server
464 connection_limit: 100
465 rate_limit: 50
466 ratio: 2
467 provider:
468 server: lb.mydomain.com
469 user: admin
470 password: secret
471 delegate_to: localhost
472
473 - name: Add pool members aggregate, remove non aggregates
474 bigip_pool_member:
475 pool: my-pool
476 aggregate:
477 - host: 192.168.1.1
478 partition: Common
479 port: 80
480 description: web server
481 connection_limit: 100
482 rate_limit: 50
483 ratio: 2
484 - host: 192.168.1.2
485 partition: Common
486 port: 80
487 description: web server
488 connection_limit: 100
489 rate_limit: 50
490 ratio: 2
491 - host: 192.168.1.3
492 partition: Common
493 port: 80
494 description: web server
495 connection_limit: 100
496 rate_limit: 50
497 ratio: 2
498 replace_all_with: true
499 provider:
500 server: lb.mydomain.com
501 user: admin
502 password: secret
503 delegate_to: localhost
504 '''
505
506 RETURN = r'''
507 rate_limit:
508 description: The new rate limit, in connections per second, of the pool member.
509 returned: changed
510 type: int
511 sample: 100
512 connection_limit:
513 description: The new connection limit of the pool member.
514 returned: changed
515 type: int
516 sample: 1000
517 description:
518 description: The new description of pool member.
519 returned: changed
520 type: str
521 sample: My pool member
522 ratio:
523 description: The new pool member ratio weight.
524 returned: changed
525 type: int
526 sample: 50
527 priority_group:
528 description: The new priority group.
529 returned: changed
530 type: int
531 sample: 3
532 fqdn_auto_populate:
533 description: Whether FQDN auto population was set on the member or not.
534 returned: changed
535 type: bool
536 sample: true
537 fqdn:
538 description: The FQDN of the pool member.
539 returned: changed
540 type: str
541 sample: foo.bar.com
542 address:
543 description: The address of the pool member.
544 returned: changed
545 type: str
546 sample: 1.2.3.4
547 monitors:
548 description: The new list of monitors for the resource.
549 returned: changed
550 type: list
551 sample: ['/Common/monitor1', '/Common/monitor2']
552 replace_all_with:
553 description: Purges all non-aggregate pool members from device.
554 returned: changed
555 type: bool
556 sample: true
557 '''
558
559 import os
560 import re
561
562 from copy import deepcopy
563 from datetime import datetime
564
565 from ansible.module_utils.urls import urlparse
566 from ansible.module_utils.basic import (
567 AnsibleModule, env_fallback
568 )
569 from ansible.module_utils.six import iteritems
570
571 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import remove_default_spec
572
573 from ..module_utils.bigip import F5RestClient
574 from ..module_utils.common import (
575 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name, flatten_boolean, is_valid_hostname
576 )
577 from ..module_utils.ipaddress import is_valid_ip, validate_ip_v6_address
578 from ..module_utils.compare import cmp_str_with_none
579 from ..module_utils.icontrol import (
580 TransactionContextManager, tmos_version
581 )
582 from ..module_utils.teem import send_teem
583
584
585 class Parameters(AnsibleF5Parameters):
586 api_map = {
587 'rateLimit': 'rate_limit',
588 'connectionLimit': 'connection_limit',
589 'priorityGroup': 'priority_group',
590 'monitor': 'monitors',
591 'inheritProfile': 'inherit_profile',
592 'profiles': 'ip_encapsulation',
593 }
594
595 api_attributes = [
596 'rateLimit',
597 'connectionLimit',
598 'description',
599 'ratio',
600 'priorityGroup',
601 'address',
602 'fqdn',
603 'session',
604 'state',
605 'monitor',
606
607 # These two settings are for IP Encapsulation
608 'inheritProfile',
609 'profiles',
610 ]
611
612 returnables = [
613 'rate_limit',
614 'connection_limit',
615 'description',
616 'ratio',
617 'priority_group',
618 'fqdn_auto_populate',
619 'session',
620 'fqdn',
621 'address',
622 'monitors',
623
624 # IP Encapsulation related
625 'inherit_profile',
626 'ip_encapsulation',
627 ]
628
629 updatables = [
630 'rate_limit',
631 'connection_limit',
632 'description',
633 'ratio',
634 'priority_group',
635 'fqdn_auto_populate',
636 'state',
637 'monitors',
638 'inherit_profile',
639 'ip_encapsulation',
640 ]
641
642
643 class ModuleParameters(Parameters):
644 @property
645 def full_name(self):
646 delimiter = ':'
647 try:
648 if validate_ip_v6_address(self.full_name_dict['name']):
649 delimiter = '.'
650 except TypeError:
651 pass
652 return '{0}{1}{2}'.format(self.full_name_dict['name'], delimiter, self.port)
653
654 @property
655 def full_name_dict(self):
656 if self._values['name'] is None:
657 if self._values['address'] and not self._values['fqdn']:
658 name = self._values['address']
659 else:
660 name = self._values['fqdn']
661 else:
662 name = self._values['name']
663 return dict(
664 name=name,
665 port=self.port
666 )
667
668 @property
669 def node_name(self):
670 return self.full_name_dict['name']
671
672 @property
673 def fqdn_name(self):
674 return self._values['fqdn']
675
676 @property
677 def fqdn(self):
678 result = {}
679 if self.fqdn_auto_populate:
680 result['autopopulate'] = 'enabled'
681 else:
682 result['autopopulate'] = 'disabled'
683 if self._values['fqdn'] is None:
684 return result
685 if not is_valid_hostname(self._values['fqdn']):
686 raise F5ModuleError(
687 "The specified 'fqdn' value of: {0} is not a valid hostname.".format(self._values['fqdn'])
688 )
689 result['tmName'] = self._values['fqdn']
690 return result
691
692 @property
693 def pool(self):
694 return fq_name(self.want.partition, self._values['pool'])
695
696 @property
697 def port(self):
698 if self._values['port'] is None:
699 raise F5ModuleError(
700 "Port value must be specified."
701 )
702 if 0 > int(self._values['port']) or int(self._values['port']) > 65535:
703 raise F5ModuleError(
704 "Valid ports must be in range 0 - 65535"
705 )
706 return int(self._values['port'])
707
708 @property
709 def address(self):
710 if self._values['address'] is None:
711 return None
712 elif self._values['address'] == 'any6':
713 return 'any6'
714 address = self._values['address'].split('%')[0]
715 if is_valid_ip(address):
716 return self._values['address']
717 raise F5ModuleError(
718 "The specified 'address' value of: {0} is not a valid IP address.".format(address)
719 )
720
721 @property
722 def state(self):
723 if self._values['state'] == 'enabled':
724 return 'present'
725 return self._values['state']
726
727 @property
728 def monitors_list(self):
729 if self._values['monitors'] is None:
730 return []
731 try:
732 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
733 result.sort()
734 return result
735 except Exception:
736 return self._values['monitors']
737
738 @property
739 def monitors(self):
740 if self._values['monitors'] is None:
741 return None
742 if len(self._values['monitors']) == 1 and self._values['monitors'][0] == '':
743 return 'default'
744 if len(self._values['monitors']) == 1 and self._values['monitors'][0] == 'none':
745 return '/Common/none'
746 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
747 if self.availability_requirement_type == 'at_least':
748 if self.at_least > len(self.monitors_list):
749 raise F5ModuleError(
750 "The 'at_least' value must not exceed the number of 'monitors'."
751 )
752 monitors = ' '.join(monitors)
753 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
754 else:
755 result = ' and '.join(monitors).strip()
756 return result
757
758 @property
759 def availability_requirement_type(self):
760 if self._values['availability_requirements'] is None:
761 return None
762 return self._values['availability_requirements']['type']
763
764 @property
765 def at_least(self):
766 return self._get_availability_value('at_least')
767
768 @property
769 def ip_encapsulation(self):
770 if self._values['ip_encapsulation'] is None:
771 return None
772 if self._values['ip_encapsulation'] == 'inherit':
773 return 'inherit'
774 if self._values['ip_encapsulation'] in ['', 'none']:
775 return ''
776 return fq_name(self.partition, self._values['ip_encapsulation'])
777
778 def _get_availability_value(self, type):
779 if self._values['availability_requirements'] is None:
780 return None
781 if self._values['availability_requirements'][type] is None:
782 return None
783 return int(self._values['availability_requirements'][type])
784
785
786 class ApiParameters(Parameters):
787 @property
788 def ip_encapsulation(self):
789 """Returns a simple name for the tunnel.
790
791 The API stores the data like so
792
793 "profiles": [
794 {
795 "name": "gre",
796 "partition": "Common",
797 "nameReference": {
798 "link": "https://localhost/mgmt/tm/net/tunnels/gre/~Common~gre?ver=13.1.0.7"
799 }
800 }
801 ]
802
803 This method returns that data as a simple profile name. For instance,
804
805 /Common/gre
806
807 This allows us to do comparisons of it in the Difference class and then,
808 as needed, translate it back to the more complex form in the UsableChanges
809 class.
810
811 Returns:
812 string: The simple form representation of the tunnel
813 """
814 if self._values['ip_encapsulation'] is None and self.inherit_profile == 'yes':
815 return 'inherit'
816 if self._values['ip_encapsulation'] is None and self.inherit_profile == 'no':
817 return ''
818 if self._values['ip_encapsulation'] is None:
819 return None
820
821 # There can be only one
822 tunnel = self._values['ip_encapsulation'][0]
823
824 return fq_name(tunnel['partition'], tunnel['name'])
825
826 @property
827 def inherit_profile(self):
828 return flatten_boolean(self._values['inherit_profile'])
829
830 @property
831 def allow(self):
832 if self._values['allow'] is None:
833 return ''
834 if self._values['allow'][0] == 'All':
835 return 'all'
836 allow = self._values['allow']
837 result = list(set([str(x) for x in allow]))
838 result = sorted(result)
839 return result
840
841 @property
842 def rate_limit(self):
843 if self._values['rate_limit'] is None:
844 return None
845 if self._values['rate_limit'] == 'disabled':
846 return 0
847 return int(self._values['rate_limit'])
848
849 @property
850 def state(self):
851 if (self._values['state'] in ['user-up', 'unchecked', 'fqdn-up-no-addr', 'fqdn-up', 'fqdn-down']
852 and self._values['session'] in ['user-enabled', 'monitor-enabled']):
853 return 'present'
854 elif self._values['state'] in ['down', 'up', 'checking'] and self._values['session'] == 'monitor-enabled':
855 # monitor-enabled + checking:
856 # Monitor is checking to see state of pool member. For instance,
857 # whether it is up or down
858 #
859 # monitor-enabled + down:
860 # Monitor returned and determined that pool member is down.
861 #
862 # monitor-enabled + up
863 # Monitor returned and determined that pool member is up.
864 return 'present'
865 elif self._values['state'] in ['user-down'] and self._values['session'] in ['user-disabled']:
866 return 'forced_offline'
867 else:
868 return 'disabled'
869
870 @property
871 def availability_requirement_type(self):
872 if self._values['monitors'] is None:
873 return None
874 if 'min ' in self._values['monitors']:
875 return 'at_least'
876 else:
877 return 'all'
878
879 @property
880 def monitors_list(self):
881 if self._values['monitors'] is None:
882 return []
883 try:
884 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
885 result.sort()
886 return result
887 except Exception:
888 return self._values['monitors']
889
890 @property
891 def monitors(self):
892 if self._values['monitors'] is None:
893 return None
894 if self._values['monitors'] == 'default':
895 return 'default'
896 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
897 if self.availability_requirement_type == 'at_least':
898 monitors = ' '.join(monitors)
899 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
900 else:
901 result = ' and '.join(monitors).strip()
902
903 return result
904
905 @property
906 def at_least(self):
907 """Returns the 'at least' value from the monitor string.
908 The monitor string for a Require monitor looks like this.
909 min 1 of { /Common/gateway_icmp }
910 This method parses out the first of the numeric values. This values represents
911 the "at_least" value that can be updated in the module.
912 Returns:
913 int: The at_least value if found. None otherwise.
914 """
915 if self._values['monitors'] is None:
916 return None
917 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
918 matches = re.search(pattern, self._values['monitors'])
919 if matches is None:
920 return None
921 return matches.group('least')
922
923 @property
924 def fqdn_auto_populate(self):
925 if self._values['fqdn'] is None:
926 return None
927 if 'autopopulate' in self._values['fqdn']:
928 if self._values['fqdn']['autopopulate'] == 'enabled':
929 return True
930 return False
931
932 @property
933 def fqdn(self):
934 if self._values['fqdn'] is None:
935 return None
936 if 'tmName' in self._values['fqdn']:
937 return self._values['fqdn']['tmName']
938
939
940 class NodeApiParameters(Parameters):
941 pass
942
943
944 class Changes(Parameters):
945 def to_return(self):
946 result = {}
947 try:
948 for returnable in self.returnables:
949 result[returnable] = getattr(self, returnable)
950 result = self._filter_params(result)
951 except Exception:
952 pass
953 return result
954
955
956 class UsableChanges(Changes):
957 @property
958 def monitors(self):
959 monitor_string = self._values['monitors']
960 if monitor_string is None:
961 return None
962 if '{' in monitor_string and '}' in monitor_string:
963 tmp = monitor_string.strip('}').split('{')
964 monitor = ''.join(tmp).rstrip()
965 return monitor
966 return monitor_string
967
968
969 class ReportableChanges(Changes):
970 @property
971 def ssl_cipher_suite(self):
972 default = ':'.join(sorted(Parameters._ciphers.split(':')))
973 if self._values['ssl_cipher_suite'] == default:
974 return 'default'
975 else:
976 return self._values['ssl_cipher_suite']
977
978 @property
979 def fqdn_auto_populate(self):
980 if self._values['fqdn'] is None:
981 return None
982 if 'autopopulate' in self._values['fqdn']:
983 if self._values['fqdn']['autopopulate'] == 'enabled':
984 return True
985 return False
986
987 @property
988 def fqdn(self):
989 if self._values['fqdn'] is None:
990 return None
991 if 'tmName' in self._values['fqdn']:
992 return self._values['fqdn']['tmName']
993
994 @property
995 def state(self):
996 if (self._values['state'] in ['user-up', 'unchecked', 'fqdn-up-no-addr', 'fqdn-up'] and
997 self._values['session'] in ['user-enabled']):
998 return 'present'
999 elif self._values['state'] in ['down', 'up', 'checking'] and self._values['session'] == 'monitor-enabled':
1000 return 'present'
1001 elif self._values['state'] in ['user-down'] and self._values['session'] in ['user-disabled']:
1002 return 'forced_offline'
1003 else:
1004 return 'disabled'
1005
1006 @property
1007 def monitors(self):
1008 if self._values['monitors'] is None:
1009 return []
1010 try:
1011 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
1012 result.sort()
1013 return result
1014 except Exception:
1015 return self._values['monitors']
1016
1017 @property
1018 def availability_requirement_type(self):
1019 if self._values['monitors'] is None:
1020 return None
1021 if 'min ' in self._values['monitors']:
1022 return 'at_least'
1023 else:
1024 return 'all'
1025
1026 @property
1027 def at_least(self):
1028 """Returns the 'at least' value from the monitor string.
1029 The monitor string for a Require monitor looks like this.
1030 min 1 of { /Common/gateway_icmp }
1031 This method parses out the first of the numeric values. This values represents
1032 the "at_least" value that can be updated in the module.
1033 Returns:
1034 int: The at_least value if found. None otherwise.
1035 """
1036 if self._values['monitors'] is None:
1037 return None
1038 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
1039 matches = re.search(pattern, self._values['monitors'])
1040 if matches is None:
1041 return None
1042 return int(matches.group('least'))
1043
1044 @property
1045 def availability_requirements(self):
1046 if self._values['monitors'] is None:
1047 return None
1048 result = dict()
1049 result['type'] = self.availability_requirement_type
1050 result['at_least'] = self.at_least
1051 return result
1052
1053
1054 class Difference(object):
1055 def __init__(self, want, have=None):
1056 self.want = want
1057 self.have = have
1058
1059 def compare(self, param):
1060 try:
1061 result = getattr(self, param)
1062 return result
1063 except AttributeError:
1064 return self.__default(param)
1065
1066 def __default(self, param):
1067 attr1 = getattr(self.want, param)
1068 try:
1069 attr2 = getattr(self.have, param)
1070 if attr1 != attr2:
1071 return attr1
1072 except AttributeError:
1073 return attr1
1074
1075 @property
1076 def state(self):
1077 if self.want.state == self.have.state:
1078 return None
1079 if self.want.state == 'forced_offline':
1080 return {
1081 'state': 'user-down',
1082 'session': 'user-disabled'
1083 }
1084 elif self.want.state == 'disabled':
1085 return {
1086 'state': 'user-up',
1087 'session': 'user-disabled'
1088 }
1089 elif self.want.state in ['present', 'enabled']:
1090 return {
1091 'state': 'user-up',
1092 'session': 'user-enabled'
1093 }
1094
1095 @property
1096 def fqdn_auto_populate(self):
1097 if self.want.fqdn_auto_populate is not None:
1098 if self.want.fqdn_auto_populate != self.have.fqdn_auto_populate:
1099 raise F5ModuleError(
1100 "The fqdn_auto_populate cannot be changed once it has been set."
1101 )
1102
1103 @property
1104 def monitors(self):
1105 if self.want.monitors is None:
1106 return None
1107 if self.want.monitors == 'default' and self.have.monitors == 'default':
1108 return None
1109 if self.want.monitors == 'default' and self.have.monitors is None:
1110 return None
1111 if self.want.monitors == 'default' and len(self.have.monitors) > 0:
1112 return 'default'
1113 # this is necessary as in v12 there is a bug where returned value has a space at the end
1114 if self.want.monitors == '/Common/none' and self.have.monitors in ['/Common/none', '/Common/none ']:
1115 return None
1116 if self.have.monitors is None:
1117 return self.want.monitors
1118 if self.have.monitors != self.want.monitors:
1119 return self.want.monitors
1120
1121 @property
1122 def ip_encapsulation(self):
1123 result = cmp_str_with_none(self.want.ip_encapsulation, self.have.ip_encapsulation)
1124 if result is None:
1125 return None
1126 if result == 'inherit':
1127 return dict(
1128 inherit_profile='enabled',
1129 ip_encapsulation=[]
1130 )
1131 elif result in ['', 'none']:
1132 return dict(
1133 inherit_profile='disabled',
1134 ip_encapsulation=[]
1135 )
1136 else:
1137 return dict(
1138 inherit_profile='disabled',
1139 ip_encapsulation=[
1140 dict(
1141 name=os.path.basename(result).strip('/'),
1142 partition=os.path.dirname(result)
1143 )
1144 ]
1145 )
1146
1147
1148 class ModuleManager(object):
1149 def __init__(self, *args, **kwargs):
1150 self.module = kwargs.get('module', None)
1151 self.client = F5RestClient(**self.module.params)
1152 self.want = None
1153 self.have = None
1154 self.changes = None
1155 self.replace_all_with = False
1156 self.purge_links = list()
1157 self.on_device = None
1158
1159 def _set_changed_options(self):
1160 changed = {}
1161 for key in Parameters.returnables:
1162 if getattr(self.want, key) is not None:
1163 changed[key] = getattr(self.want, key)
1164 if changed:
1165 self.changes = UsableChanges(params=changed)
1166
1167 def _update_changed_options(self):
1168 diff = Difference(self.want, self.have)
1169 updatables = Parameters.updatables
1170 changed = dict()
1171 for k in updatables:
1172 change = diff.compare(k)
1173 if change is None:
1174 continue
1175 else:
1176 if isinstance(change, dict):
1177 changed.update(change)
1178 else:
1179 changed[k] = change
1180 if changed:
1181 self.changes = UsableChanges(params=changed)
1182 return True
1183 return False
1184
1185 def _announce_deprecations(self, result):
1186 warnings = result.pop('__warnings', [])
1187 for warning in warnings:
1188 self.module.deprecate(
1189 msg=warning['msg'],
1190 version=warning['version']
1191 )
1192
1193 def exec_module(self):
1194 start = datetime.now().isoformat()
1195 version = tmos_version(self.client)
1196 wants = None
1197 if self.module.params['replace_all_with']:
1198 self.replace_all_with = True
1199
1200 if self.module.params['aggregate']:
1201 wants = self.merge_defaults_for_aggregate(self.module.params)
1202
1203 result = dict()
1204 changed = False
1205 if self.replace_all_with and self.purge_links:
1206 self.purge()
1207 changed = True
1208
1209 if self.module.params['aggregate']:
1210 result['aggregate'] = list()
1211 for want in wants:
1212 output = self.execute(want)
1213 if output['changed']:
1214 changed = output['changed']
1215 result['aggregate'].append(output)
1216 else:
1217 output = self.execute(self.module.params)
1218 if output['changed']:
1219 changed = output['changed']
1220 result.update(output)
1221 if changed:
1222 result['changed'] = True
1223 send_teem(start, self.client, self.module, version)
1224 return result
1225
1226 def merge_defaults_for_aggregate(self, params):
1227 defaults = deepcopy(params)
1228 aggregate = defaults.pop('aggregate')
1229
1230 for i, j in enumerate(aggregate):
1231 for k, v in iteritems(defaults):
1232 if k != 'replace_all_with':
1233 if j.get(k, None) is None and v is not None:
1234 aggregate[i][k] = v
1235
1236 if self.replace_all_with:
1237 self.compare_aggregate_names(aggregate)
1238
1239 return aggregate
1240
1241 def _filter_ephemerals(self):
1242 on_device = self._read_purge_collection()
1243 if not on_device:
1244 self.on_device = []
1245 return
1246 self.on_device = [member for member in on_device if member['ephemeral'] != "true"]
1247
1248 def compare_fqdns(self, items):
1249 if any('fqdn' in item for item in items):
1250 aggregates = [item['fqdn'] for item in items if 'fqdn' in item and item['fqdn']]
1251 collection = [member['fqdn']['tmName'] for member in self.on_device if 'tmName' in member['fqdn']]
1252
1253 diff = set(collection) - set(aggregates)
1254
1255 if diff:
1256 fqdns = [
1257 member['selfLink'] for member in self.on_device
1258 if 'tmName' in member['fqdn'] and member['fqdn']['tmName'] in diff
1259 ]
1260 self.purge_links.extend(fqdns)
1261 return True
1262 return False
1263 return False
1264
1265 def _join_address_port(self, item):
1266 if 'port' not in item:
1267 raise F5ModuleError(
1268 "Aggregates must be provided with both address and port."
1269 )
1270 delimiter = ':'
1271 # If user provides us a name for the aggregate element, we use its name with port, this is
1272 # how F5 BIG-IP behaves as well.
1273 if 'name' in item and item['name']:
1274 return '{0}{1}{2}'.format(item['name'], delimiter, item['port'])
1275 try:
1276 if validate_ip_v6_address(item['address']):
1277 delimiter = '.'
1278 except TypeError:
1279 pass
1280 return '{0}{1}{2}'.format(item['address'], delimiter, item['port'])
1281
1282 def compare_addresses(self, items):
1283 if any('address' in item for item in items):
1284 aggregates = [self._join_address_port(item) for item in items if 'address' in item and item['address']]
1285 collection = [member['name'] for member in self.on_device]
1286 diff = set(collection) - set(aggregates)
1287 if diff:
1288 addresses = [item['selfLink'] for item in self.on_device if item['name'] in diff]
1289 self.purge_links.extend(addresses)
1290 return True
1291 return False
1292 return False
1293
1294 def compare_aggregate_names(self, items):
1295 self._filter_ephemerals()
1296 if not self.on_device:
1297 return False
1298 fqdns = self.compare_fqdns(items)
1299 addresses = self.compare_addresses(items)
1300
1301 if self.purge_links:
1302 if fqdns:
1303 if not addresses:
1304 self.purge_links.extend([item['selfLink'] for item in self.on_device if 'tmName' not in item['fqdn']])
1305
1306 def execute(self, params=None):
1307 self.want = ModuleParameters(params=params)
1308 self.have = ApiParameters()
1309 self.changes = UsableChanges()
1310
1311 changed = False
1312 result = dict()
1313 state = params['state']
1314 if state in ['present', 'enabled', 'disabled', 'forced_offline']:
1315 changed = self.present()
1316 elif state == "absent":
1317 changed = self.absent()
1318
1319 reportable = ReportableChanges(params=self.changes.to_return())
1320 changes = reportable.to_return()
1321 result.update(**changes)
1322 result.update(dict(changed=changed))
1323 self._announce_deprecations(result)
1324 return result
1325
1326 def present(self):
1327 if self.exists():
1328 return self.update()
1329 else:
1330 return self.create()
1331
1332 def absent(self):
1333 if self.exists():
1334 return self.remove()
1335 elif not self.want.preserve_node and self.node_exists():
1336 return self.remove_node_from_device()
1337 return False
1338
1339 def update(self):
1340 self.have = self.read_current_from_device()
1341 if not self.should_update():
1342 return False
1343 if self.module.check_mode:
1344 return True
1345 self.update_on_device()
1346 return True
1347
1348 def should_update(self):
1349 result = self._update_changed_options()
1350 if result:
1351 return True
1352 return False
1353
1354 def remove(self):
1355 if self.module.check_mode:
1356 return True
1357 self.remove_from_device()
1358 if not self.want.preserve_node:
1359 self.remove_node_from_device()
1360 if self.exists():
1361 raise F5ModuleError("Failed to delete the resource.")
1362 return True
1363
1364 def purge(self):
1365 if self.module.check_mode:
1366 return True
1367 if not self.pool_exist():
1368 raise F5ModuleError('The specified pool does not exist')
1369 self.purge_from_device()
1370 return True
1371
1372 def create(self):
1373 if self.want.reuse_nodes:
1374 self._update_address_with_existing_nodes()
1375
1376 if self.want.name and not any(x for x in [self.want.address, self.want.fqdn_name]):
1377 self._set_host_by_name()
1378
1379 if self.want.ip_encapsulation == '':
1380 self.changes.update({'inherit_profile': 'enabled'})
1381 self.changes.update({'profiles': []})
1382 elif self.want.ip_encapsulation:
1383 # Read the current list of tunnels so that IP encapsulation
1384 # checking can take place.
1385 tunnels_gre = self.read_current_tunnels_from_device('gre')
1386 tunnels_ipip = self.read_current_tunnels_from_device('ipip')
1387 tunnels = tunnels_gre + tunnels_ipip
1388 if self.want.ip_encapsulation not in tunnels:
1389 raise F5ModuleError(
1390 "The specified 'ip_encapsulation' tunnel was not found on the system."
1391 )
1392 self.changes.update({'inherit_profile': 'disabled'})
1393
1394 self._update_api_state_attributes()
1395 self._set_changed_options()
1396 if self.module.check_mode:
1397 return True
1398 self.create_on_device()
1399 return True
1400
1401 def exists(self):
1402 if not self.pool_exist():
1403 raise F5ModuleError('The specified pool does not exist')
1404
1405 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}/members/{3}".format(
1406 self.client.provider['server'],
1407 self.client.provider['server_port'],
1408 transform_name(name=fq_name(self.want.partition, self.want.pool)),
1409 transform_name(self.want.partition, self.want.full_name)
1410 )
1411 resp = self.client.api.get(uri)
1412 try:
1413 response = resp.json()
1414 except ValueError as ex:
1415 raise F5ModuleError(str(ex))
1416 if resp.status == 404 or 'code' in response and response['code'] == 404:
1417 return False
1418 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1419 return True
1420
1421 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1422
1423 if resp.status in errors or 'code' in response and response['code'] in errors:
1424 if 'message' in response:
1425 raise F5ModuleError(response['message'])
1426 else:
1427 raise F5ModuleError(resp.content)
1428
1429 def pool_exist(self):
1430 if self.module.check_mode:
1431 return True
1432 if self.replace_all_with:
1433 pool_name = transform_name(name=fq_name(self.module.params['partition'], self.module.params['pool']))
1434 else:
1435 pool_name = transform_name(name=fq_name(self.want.partition, self.want.pool))
1436
1437 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}".format(
1438 self.client.provider['server'],
1439 self.client.provider['server_port'],
1440 pool_name
1441
1442 )
1443 resp = self.client.api.get(uri)
1444 try:
1445 response = resp.json()
1446 except ValueError as ex:
1447 raise F5ModuleError(str(ex))
1448
1449 if resp.status == 404 or 'code' in response and response['code'] == 404:
1450 return False
1451 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1452 return True
1453
1454 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1455
1456 if resp.status in errors or 'code' in response and response['code'] in errors:
1457 if 'message' in response:
1458 raise F5ModuleError(response['message'])
1459 else:
1460 raise F5ModuleError(resp.content)
1461
1462 def node_exists(self):
1463 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
1464 self.client.provider['server'],
1465 self.client.provider['server_port'],
1466 transform_name(self.want.partition, self.want.node_name)
1467 )
1468 resp = self.client.api.get(uri)
1469 try:
1470 response = resp.json()
1471 except ValueError as ex:
1472 raise F5ModuleError(str(ex))
1473
1474 if resp.status == 404 or 'code' in response and response['code'] == 404:
1475 return False
1476 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1477 return True
1478
1479 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1480
1481 if resp.status in errors or 'code' in response and response['code'] in errors:
1482 if 'message' in response:
1483 raise F5ModuleError(response['message'])
1484 else:
1485 raise F5ModuleError(resp.content)
1486
1487 def _set_host_by_name(self):
1488 if is_valid_ip(self.want.name):
1489 self.want.update({
1490 'fqdn': None,
1491 'address': self.want.name
1492 })
1493 else:
1494 if not is_valid_hostname(self.want.name):
1495 raise F5ModuleError(
1496 "'name' is neither a valid IP address or FQDN name."
1497 )
1498 self.want.update({
1499 'fqdn': self.want.name,
1500 'address': None
1501 })
1502
1503 def _update_api_state_attributes(self):
1504 if self.want.state == 'forced_offline':
1505 self.want.update({
1506 'state': 'user-down',
1507 'session': 'user-disabled',
1508 })
1509 elif self.want.state == 'disabled':
1510 self.want.update({
1511 'state': 'user-up',
1512 'session': 'user-disabled',
1513 })
1514 elif self.want.state in ['present', 'enabled']:
1515 self.want.update({
1516 'state': 'user-up',
1517 'session': 'user-enabled',
1518 })
1519
1520 def _update_address_with_existing_nodes(self):
1521 try:
1522 have = self.read_current_node_from_device(self.want.node_name)
1523 if self.want.fqdn_auto_populate and self.want.reuse_nodes:
1524 self.module.warn(
1525 "'fqdn_auto_populate' is discarded in favor of the re-used node's auto-populate setting."
1526 )
1527 self.want.update({
1528 'fqdn_auto_populate': True if have.fqdn['autopopulate'] == 'enabled' else False
1529 })
1530 if 'tmName' in have.fqdn:
1531 self.want.update({
1532 'fqdn': have.fqdn['tmName'],
1533 'address': 'any6'
1534 })
1535 else:
1536 self.want.update({
1537 'address': have.address
1538 })
1539 except Exception:
1540 return None
1541
1542 def _read_purge_collection(self):
1543 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}/members".format(
1544 self.client.provider['server'],
1545 self.client.provider['server_port'],
1546 transform_name(name=fq_name(self.module.params['partition'], self.module.params['pool']))
1547 )
1548
1549 query = '?$select=name,selfLink,fqdn,address,ephemeral'
1550 resp = self.client.api.get(uri + query)
1551
1552 try:
1553 response = resp.json()
1554 except ValueError as ex:
1555 raise F5ModuleError(str(ex))
1556
1557 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1558 if 'items' in response:
1559 return response['items']
1560 return []
1561 raise F5ModuleError(resp.content)
1562
1563 def create_on_device(self):
1564 params = self.changes.api_params()
1565 params['name'] = self.want.full_name
1566 params['partition'] = self.want.partition
1567 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}/members".format(
1568 self.client.provider['server'],
1569 self.client.provider['server_port'],
1570 transform_name(name=fq_name(self.want.partition, self.want.pool)),
1571
1572 )
1573 resp = self.client.api.post(uri, json=params)
1574 try:
1575 response = resp.json()
1576 except ValueError as ex:
1577 raise F5ModuleError(str(ex))
1578
1579 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1580 return True
1581 raise F5ModuleError(resp.content)
1582
1583 def update_on_device(self):
1584 params = self.changes.api_params()
1585 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}/members/{3}".format(
1586 self.client.provider['server'],
1587 self.client.provider['server_port'],
1588 transform_name(name=fq_name(self.want.partition, self.want.pool)),
1589 transform_name(self.want.partition, self.want.full_name)
1590
1591 )
1592 resp = self.client.api.patch(uri, json=params)
1593 try:
1594 response = resp.json()
1595 except ValueError as ex:
1596 raise F5ModuleError(str(ex))
1597
1598 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1599 return True
1600 raise F5ModuleError(resp.content)
1601
1602 def remove_from_device(self):
1603 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}/members/{3}".format(
1604 self.client.provider['server'],
1605 self.client.provider['server_port'],
1606 transform_name(name=fq_name(self.want.partition, self.want.pool)),
1607 transform_name(self.want.partition, self.want.full_name)
1608
1609 )
1610 response = self.client.api.delete(uri)
1611 if response.status == 200:
1612 return True
1613 raise F5ModuleError(response.content)
1614
1615 def remove_node_from_device(self):
1616 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
1617 self.client.provider['server'],
1618 self.client.provider['server_port'],
1619 transform_name(self.want.partition, self.want.node_name)
1620 )
1621 response = self.client.api.delete(uri)
1622 if response.status == 200:
1623 return True
1624 raise F5ModuleError(response.content)
1625
1626 def read_current_from_device(self):
1627 uri = "https://{0}:{1}/mgmt/tm/ltm/pool/{2}/members/{3}".format(
1628 self.client.provider['server'],
1629 self.client.provider['server_port'],
1630 transform_name(name=fq_name(self.want.partition, self.want.pool)),
1631 transform_name(self.want.partition, self.want.full_name)
1632
1633 )
1634 resp = self.client.api.get(uri)
1635 try:
1636 response = resp.json()
1637 except ValueError as ex:
1638 raise F5ModuleError(str(ex))
1639
1640 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
1641 raise F5ModuleError(resp.content)
1642
1643 # Read the current list of tunnels so that IP encapsulation
1644 # checking can take place.
1645 tunnels_gre = self.read_current_tunnels_from_device('gre')
1646 tunnels_ipip = self.read_current_tunnels_from_device('ipip')
1647 response['tunnels'] = tunnels_gre + tunnels_ipip
1648
1649 return ApiParameters(params=response)
1650
1651 def read_current_node_from_device(self, node):
1652 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
1653 self.client.provider['server'],
1654 self.client.provider['server_port'],
1655 transform_name(self.want.partition, node)
1656 )
1657 resp = self.client.api.get(uri)
1658 try:
1659 response = resp.json()
1660 except ValueError as ex:
1661 raise F5ModuleError(str(ex))
1662
1663 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1664 return NodeApiParameters(params=response)
1665 raise F5ModuleError(resp.content)
1666
1667 def read_current_tunnels_from_device(self, tunnel_type):
1668 uri = "https://{0}:{1}/mgmt/tm/net/tunnels/{2}".format(
1669 self.client.provider['server'],
1670 self.client.provider['server_port'],
1671 tunnel_type
1672 )
1673 resp = self.client.api.get(uri)
1674 try:
1675 response = resp.json()
1676 except ValueError as ex:
1677 raise F5ModuleError(str(ex))
1678
1679 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1680 if 'items' not in response:
1681 return []
1682 return [x['fullPath'] for x in response['items']]
1683 raise F5ModuleError(resp.content)
1684
1685 def _prepare_links(self, collection):
1686 # this is to ensure no duplicates are in the provided collection
1687 no_dupes = list(set(collection))
1688 links = list()
1689 purge_paths = [urlparse(link).path for link in no_dupes]
1690
1691 for path in purge_paths:
1692 link = "https://{0}:{1}{2}".format(
1693 self.client.provider['server'],
1694 self.client.provider['server_port'],
1695 path
1696 )
1697 links.append(link)
1698 return links
1699
1700 def purge_from_device(self):
1701 links = self._prepare_links(self.purge_links)
1702
1703 with TransactionContextManager(self.client) as transact:
1704 for link in links:
1705 resp = transact.api.delete(link)
1706
1707 try:
1708 response = resp.json()
1709 except ValueError as ex:
1710 raise F5ModuleError(str(ex))
1711
1712 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
1713 raise F5ModuleError(resp.content)
1714 return True
1715
1716
1717 class ArgumentSpec(object):
1718 def __init__(self):
1719 self.supports_check_mode = True
1720 element_spec = dict(
1721 address=dict(aliases=['host', 'ip']),
1722 fqdn=dict(
1723 aliases=['hostname']
1724 ),
1725 name=dict(),
1726 port=dict(type='int'),
1727 connection_limit=dict(type='int'),
1728 description=dict(),
1729 rate_limit=dict(type='int'),
1730 ratio=dict(type='int'),
1731 preserve_node=dict(type='bool'),
1732 priority_group=dict(type='int'),
1733 state=dict(
1734 default='present',
1735 choices=['absent', 'present', 'enabled', 'disabled', 'forced_offline']
1736 ),
1737 fqdn_auto_populate=dict(type='bool'),
1738 reuse_nodes=dict(type='bool', default=True),
1739 availability_requirements=dict(
1740 type='dict',
1741 options=dict(
1742 type=dict(
1743 choices=['all', 'at_least'],
1744 required=True
1745 ),
1746 at_least=dict(type='int'),
1747 ),
1748 required_if=[
1749 ['type', 'at_least', ['at_least']],
1750 ]
1751 ),
1752 monitors=dict(
1753 type='list',
1754 elements='str',
1755 ),
1756 ip_encapsulation=dict(),
1757 partition=dict(
1758 default='Common',
1759 fallback=(env_fallback, ['F5_PARTITION'])
1760 ),
1761 )
1762 aggregate_spec = deepcopy(element_spec)
1763
1764 # remove default in aggregate spec, to handle common arguments
1765 remove_default_spec(aggregate_spec)
1766 aggregate_spec["state"].update(default="present")
1767 aggregate_spec["partition"].update(default="Common")
1768 aggregate_spec["reuse_nodes"].update(default=True)
1769
1770 self.argument_spec = dict(
1771 aggregate=dict(
1772 type='list',
1773 elements='dict',
1774 options=aggregate_spec,
1775 aliases=['members'],
1776 mutually_exclusive=[
1777 ['address', 'fqdn']
1778 ],
1779 required_one_of=[
1780 ['address', 'fqdn']
1781 ],
1782 ),
1783 replace_all_with=dict(
1784 type='bool',
1785 aliases=['purge'],
1786 default='no'
1787 ),
1788 pool=dict(required=True),
1789 partition=dict(
1790 default='Common',
1791 fallback=(env_fallback, ['F5_PARTITION'])
1792 ),
1793 )
1794
1795 self.argument_spec.update(element_spec)
1796 self.argument_spec.update(f5_argument_spec)
1797
1798 self.mutually_exclusive = [
1799 ['address', 'aggregate'],
1800 ['fqdn', 'aggregate']
1801 ]
1802 self.required_one_of = [
1803 ['address', 'fqdn', 'aggregate'],
1804 ]
1805
1806
1807 def main():
1808 spec = ArgumentSpec()
1809
1810 module = AnsibleModule(
1811 argument_spec=spec.argument_spec,
1812 supports_check_mode=spec.supports_check_mode,
1813 mutually_exclusive=spec.mutually_exclusive,
1814 required_one_of=spec.required_one_of,
1815 )
1816
1817 try:
1818 mm = ModuleManager(module=module)
1819 results = mm.exec_module()
1820 module.exit_json(**results)
1821 except F5ModuleError as ex:
1822 module.fail_json(msg=str(ex))
1823
1824
1825 if __name__ == '__main__':
1826 main()