Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_gtm_pool_member
13 short_description: Manage GTM pool member settings
14 description:
15 - Manages a variety of settings on GTM (now BIG-IP DNS) pool members. The settings that can be
16 adjusted with this module are much more broad that what can be done in the
17 C(bigip_gtm_pool) module. The pool module is intended to allow you to adjust
18 the member order in the pool, not the various settings of the members. The
19 C(bigip_gtm_pool_member) module should be used to adjust all of the other
20 settings.
21 version_added: "1.0.0"
22 options:
23 aggregate:
24 description:
25 - List of GTM pool member definitions to be created, modified, or removed.
26 - When using C(aggregates), if one of the aggregate definitions is invalid, the aggregate run will fail,
27 indicating the error it last encountered.
28 - The module will C(NOT) rollback any changes it has made prior to encountering the error.
29 - The module also will not indicate what changes were made prior to failure, therefore we strongly advise
30 you run the module in check mode to make basic validation, prior to module execution.
31 type: list
32 elements: dict
33 suboptions:
34 virtual_server:
35 description:
36 - Specifies the name of the GTM virtual server which is assigned to the specified
37 C(server).
38 type: str
39 server_name:
40 description:
41 - Specifies the GTM server which contains the C(virtual_server).
42 type: str
43 member_order:
44 description:
45 - Specifies the order in which the member will appear in the pool.
46 - The system uses this number with load balancing methods that involve prioritizing
47 pool members, such as the Ratio load balancing method.
48 type: int
49 monitor:
50 description:
51 - Specifies the monitor assigned to this pool member.
52 - Pool members only support a single monitor.
53 - If the C(port) of the C(gtm_virtual_server) is C(*), the accepted values of this
54 parameter will be affected.
55 - If this parameter is not specified when creating a new pool member, the default
56 of C(default) will be used.
57 - To remove the monitor from the pool member, use the value C(none).
58 type: str
59 ratio:
60 description:
61 - Specifies the weight of the pool member for load balancing purposes.
62 type: int
63 description:
64 description:
65 - The description of the pool member.
66 type: str
67 limits:
68 description:
69 - Specifies resource thresholds or limit requirements at the pool member level.
70 - When you enable one or more limit settings, the system then uses that data to take
71 members in and out of service.
72 - You can define limits for any or all of the limit settings. However, when a
73 member does not meet the resource threshold limit requirement, the system marks
74 the member as unavailable and directs load balancing traffic to another resource.
75 type: dict
76 suboptions:
77 bits_enabled:
78 description:
79 - Whether or not the bits limit is enabled.
80 type: bool
81 packets_enabled:
82 description:
83 - Whether or not the packets limit is enabled.
84 type: bool
85 connections_enabled:
86 description:
87 - Whether or not the current connections limit is enabled.
88 type: bool
89 bits_limit:
90 description:
91 - Specifies the maximum allowable data throughput rate
92 for the member, in bits per second.
93 type: int
94 packets_limit:
95 description:
96 - Specifies the maximum allowable data transfer rate for the member,
97 in packets per second.
98 type: int
99 connections_limit:
100 description:
101 - Specifies the maximum number of concurrent connections, combined, for all of
102 the members.
103 type: int
104 state:
105 description:
106 - Pool member state. When C(present), ensures the pool member is
107 created and enabled. When C(absent), ensures the pool member is
108 removed from the system. When C(enabled) or C(disabled), ensures
109 the pool member is enabled or disabled (respectively) on the remote
110 device.
111 type: str
112 choices:
113 - present
114 - absent
115 - enabled
116 - disabled
117 default: present
118 partition:
119 description:
120 - Device partition to manage resources on.
121 type: str
122 default: Common
123 aliases:
124 - members
125 virtual_server:
126 description:
127 - Specifies the name of the GTM virtual server which is assigned to the specified
128 C(server).
129 type: str
130 server_name:
131 description:
132 - Specifies the GTM server which contains the C(virtual_server).
133 type: str
134 member_order:
135 description:
136 - Specifies the order in which the member will appear in the pool.
137 - The system uses this number with load balancing methods that involve prioritizing
138 pool members, such as the Ratio load balancing method.
139 type: int
140 monitor:
141 description:
142 - Specifies the monitor assigned to this pool member.
143 - Pool members only support a single monitor.
144 - If the C(port) of the C(gtm_virtual_server) is C(*), the accepted values of this
145 parameter will be affected.
146 - If this parameter is not specified when creating a new pool member, the default
147 of C(default) will be used.
148 - To remove the monitor from the pool member, use the value C(none).
149 type: str
150 ratio:
151 description:
152 - Specifies the weight of the pool member for load balancing purposes.
153 type: int
154 description:
155 description:
156 - The description of the pool member.
157 type: str
158 limits:
159 description:
160 - Specifies resource thresholds or limit requirements at the pool member level.
161 - When you enable one or more limit settings, the system then uses that data to take
162 members in and out of service.
163 - You can define limits for any or all of the limit settings. However, when a
164 member does not meet the resource threshold limit requirement, the system marks
165 the member as unavailable and directs load balancing traffic to another resource.
166 type: dict
167 suboptions:
168 bits_enabled:
169 description:
170 - Whether or not the bits limit is enabled.
171 type: bool
172 packets_enabled:
173 description:
174 - Whether or not the packets limit is enabled.
175 type: bool
176 connections_enabled:
177 description:
178 - Whether or not the current connections limit is enabled.
179 type: bool
180 bits_limit:
181 description:
182 - Specifies the maximum allowable data throughput rate
183 for the member, in bits per second.
184 type: int
185 packets_limit:
186 description:
187 - Specifies the maximum allowable data transfer rate for the member,
188 in packets per second.
189 type: int
190 connections_limit:
191 description:
192 - Specifies the maximum number of concurrent connections, combined, for all of
193 the members.
194 type: int
195 pool:
196 description:
197 - Name of the GTM pool.
198 - For pools created on different partitions, you must specify partition of the pool in the full path format,
199 for example, C(/FooBar/pool_name).
200 type: str
201 required: True
202 type:
203 description:
204 - The type of GTM pool that the member is in.
205 type: str
206 required: True
207 choices:
208 - a
209 - aaaa
210 - cname
211 - mx
212 - naptr
213 - srv
214 replace_all_with:
215 description:
216 - Removes members not defined in the C(aggregate) parameter.
217 - This operation is all or none, meaning it will stop if there are some pool members
218 that cannot be removed.
219 type: bool
220 default: false
221 aliases:
222 - purge
223 partition:
224 description:
225 - Device partition to manage resources on.
226 type: str
227 default: Common
228 state:
229 description:
230 - Pool member state. When C(present), ensures the pool member is
231 created and enabled. When C(absent), ensures the pool member is
232 removed from the system. When C(enabled) or C(disabled), ensures
233 the pool member is enabled or disabled (respectively) on the remote
234 device.
235 type: str
236 choices:
237 - present
238 - absent
239 - enabled
240 - disabled
241 default: present
242 extends_documentation_fragment: f5networks.f5_modules.f5
243 author:
244 - Tim Rupp (@caphrim007)
245 - Wojciech Wypior (@wojtek0806)
246 '''
247
248 EXAMPLES = r'''
249 - name: Create a GTM pool member
250 bigip_gtm_pool_member:
251 pool: pool1
252 server_name: server1
253 virtual_server: vs1
254 type: a
255 provider:
256 password: secret
257 server: lb.mydomain.com
258 user: admin
259 delegate_to: localhost
260
261 - name: Create a GTM pool member different partition
262 bigip_gtm_pool_member:
263 server_name: /Common/foo_name
264 virtual_server: GTMVSName
265 type: a
266 pool: /FooBar/foo-pool
267 partition: Common
268 provider:
269 password: secret
270 server: lb.mydomain.com
271 user: admin
272 delegate_to: localhost
273
274 - name: Add GTM pool members aggregate
275 bigip_gtm_pool_member:
276 pool: pool1
277 type: a
278 aggregate:
279 - server_name: server1
280 virtual_server: vs1
281 partition: Common
282 description: web server1
283 member_order: 0
284 - server_name: server2
285 virtual_server: vs2
286 partition: Common
287 description: web server2
288 member_order: 1
289 - server_name: server3
290 virtual_server: vs3
291 partition: Common
292 description: web server3
293 member_order: 2
294 provider:
295 server: lb.mydomain.com
296 user: admin
297 password: secret
298 delegate_to: localhost
299
300 - name: Add GTM pool members aggregate, remove non aggregates
301 bigip_gtm_pool_member:
302 pool: pool1
303 type: a
304 aggregate:
305 - server_name: server1
306 virtual_server: vs1
307 partition: Common
308 description: web server1
309 member_order: 0
310 - server_name: server2
311 virtual_server: vs2
312 partition: Common
313 description: web server2
314 member_order: 1
315 - server_name: server3
316 virtual_server: vs3
317 partition: Common
318 description: web server3
319 member_order: 2
320 replace_all_with: true
321 provider:
322 server: lb.mydomain.com
323 user: admin
324 password: secret
325 delegate_to: localhost
326 '''
327
328 RETURN = r'''
329 bits_enabled:
330 description: Whether the bits limit is enabled.
331 returned: changed
332 type: bool
333 sample: true
334 bits_limit:
335 description: The new bits_enabled limit.
336 returned: changed
337 type: int
338 sample: 100
339 connections_enabled:
340 description: Whether the connections limit is enabled.
341 returned: changed
342 type: bool
343 sample: true
344 connections_limit:
345 description: The new connections_limit limit.
346 returned: changed
347 type: int
348 sample: 100
349 disabled:
350 description: Whether the pool member is disabled or not.
351 returned: changed
352 type: bool
353 sample: true
354 enabled:
355 description: Whether the pool member is enabled or not.
356 returned: changed
357 type: bool
358 sample: true
359 member_order:
360 description: The new order in which the member appears in the pool.
361 returned: changed
362 type: int
363 sample: 2
364 monitor:
365 description: The new monitor assigned to the pool member.
366 returned: changed
367 type: str
368 sample: /Common/monitor1
369 packets_enabled:
370 description: Whether the packets limit is enabled.
371 returned: changed
372 type: bool
373 sample: true
374 packets_limit:
375 description: The new packets_limit limit.
376 returned: changed
377 type: int
378 sample: 100
379 ratio:
380 description: The new weight of the member for load balancing.
381 returned: changed
382 type: int
383 sample: 10
384 description:
385 description: The new description of the member.
386 returned: changed
387 type: str
388 sample: My description
389 replace_all_with:
390 description: Purges all non-aggregate pool members from device
391 returned: changed
392 type: bool
393 sample: true
394 '''
395
396 from copy import deepcopy
397 from datetime import datetime
398
399 from ansible.module_utils.urls import urlparse
400 from ansible.module_utils.basic import (
401 AnsibleModule, env_fallback
402 )
403 from ansible.module_utils.six import iteritems
404
405 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import remove_default_spec
406
407 from ..module_utils.bigip import F5RestClient
408 from ..module_utils.common import (
409 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
410 )
411 from ..module_utils.icontrol import (
412 module_provisioned, TransactionContextManager, tmos_version
413 )
414 from ..module_utils.teem import send_teem
415
416
417 class Parameters(AnsibleF5Parameters):
418 api_map = {
419 'limitMaxBps': 'bits_limit',
420 'limitMaxBpsStatus': 'bits_enabled',
421 'limitMaxConnections': 'connections_limit',
422 'limitMaxConnectionsStatus': 'connections_enabled',
423 'limitMaxPps': 'packets_limit',
424 'limitMaxPpsStatus': 'packets_enabled',
425 'memberOrder': 'member_order',
426 }
427
428 api_attributes = [
429 'disabled',
430 'enabled',
431 'limitMaxBps',
432 'limitMaxBpsStatus',
433 'limitMaxConnections',
434 'limitMaxConnectionsStatus',
435 'limitMaxPps',
436 'limitMaxPpsStatus',
437 'memberOrder',
438 'monitor',
439 'ratio',
440 'description',
441 ]
442
443 returnables = [
444 'bits_enabled',
445 'bits_limit',
446 'connections_enabled',
447 'connections_limit',
448 'disabled',
449 'enabled',
450 'member_order',
451 'monitor',
452 'packets_enabled',
453 'packets_limit',
454 'ratio',
455 'description',
456 ]
457
458 updatables = [
459 'bits_enabled',
460 'bits_limit',
461 'connections_enabled',
462 'connections_limit',
463 'enabled',
464 'member_order',
465 'monitor',
466 'packets_limit',
467 'packets_enabled',
468 'ratio',
469 'description',
470 ]
471
472 @property
473 def ratio(self):
474 if self._values['ratio'] is None:
475 return None
476 return int(self._values['ratio'])
477
478
479 class ApiParameters(Parameters):
480 def name(self):
481 # We need to do this because BIGIP allows / in names of GTM VS, allowing and users create such names incorrectly
482 # Despite the fact that GTM server and GTM Virtual Server cannot be created outside the Common partition
483 if self._values['subPath'] is None:
484 return self._values['name']
485 result = self._values['subPath'] + self._values['name']
486 return result
487
488 @property
489 def enabled(self):
490 if 'enabled' in self._values:
491 return True
492 else:
493 return False
494
495 @property
496 def disabled(self):
497 if 'disabled' in self._values:
498 return True
499 return False
500
501 @property
502 def monitor(self):
503 if self._values['monitor'] is None:
504 return None
505 # The value of this parameter in the API includes an extra space
506 return self._values['monitor'].strip()
507
508
509 class ModuleParameters(Parameters):
510 def _get_limit_value(self, type):
511 if self._values['limits'] is None:
512 return None
513 if self._values['limits'][type] is None:
514 return None
515 return int(self._values['limits'][type])
516
517 def _get_limit_status(self, type):
518 if self._values['limits'] is None:
519 return None
520 if self._values['limits'][type] is None:
521 return None
522 if self._values['limits'][type]:
523 return 'enabled'
524 return 'disabled'
525
526 @property
527 def name(self):
528 result = '{0}:{1}'.format(self.server_name, self.virtual_server)
529 return result
530
531 @property
532 def type(self):
533 if self._values['type'] is None:
534 return None
535 return str(self._values['type'])
536
537 @property
538 def enabled(self):
539 if self._values['state'] == 'enabled':
540 return True
541 elif self._values['state'] == 'disabled':
542 return False
543 else:
544 return None
545
546 @property
547 def disabled(self):
548 if self._values['state'] == 'enabled':
549 return False
550 elif self._values['state'] == 'disabled':
551 return True
552 else:
553 return None
554
555 @property
556 def bits_limit(self):
557 return self._get_limit_value('bits_limit')
558
559 @property
560 def packets_limit(self):
561 return self._get_limit_value('packets_limit')
562
563 @property
564 def connections_limit(self):
565 return self._get_limit_value('connections_limit')
566
567 @property
568 def bits_enabled(self):
569 return self._get_limit_status('bits_enabled')
570
571 @property
572 def packets_enabled(self):
573 return self._get_limit_status('packets_enabled')
574
575 @property
576 def connections_enabled(self):
577 return self._get_limit_status('connections_enabled')
578
579 @property
580 def monitor(self):
581 if self._values['monitor'] is None:
582 return None
583 elif self._values['monitor'] in ['default', '']:
584 return 'default'
585 return fq_name(self.partition, self._values['monitor'])
586
587
588 class Changes(Parameters):
589 def to_return(self):
590 result = {}
591 try:
592 for returnable in self.returnables:
593 result[returnable] = getattr(self, returnable)
594 result = self._filter_params(result)
595 except Exception:
596 raise
597 return result
598
599
600 class UsableChanges(Changes):
601 pass
602
603
604 class ReportableChanges(Changes):
605 @property
606 def disabled(self):
607 return flatten_boolean(self._values['disabled'])
608
609 @property
610 def enabled(self):
611 return flatten_boolean(self._values['enabled'])
612
613
614 class Difference(object):
615 def __init__(self, want, have=None):
616 self.want = want
617 self.have = have
618
619 def compare(self, param):
620 try:
621 result = getattr(self, param)
622 return result
623 except AttributeError:
624 return self.__default(param)
625
626 def __default(self, param):
627 attr1 = getattr(self.want, param)
628 try:
629 attr2 = getattr(self.have, param)
630 if attr1 != attr2:
631 return attr1
632 except AttributeError:
633 return attr1
634
635 @property
636 def description(self):
637 if self.want.description == '' and self.have.description is None:
638 return None
639 if self.want.description != self.have.description:
640 return self.want.description
641
642 @property
643 def enabled(self):
644 if self.want.state == 'enabled' and self.have.disabled:
645 result = dict(
646 enabled=True,
647 disabled=False
648 )
649 return result
650 elif self.want.state == 'disabled' and self.have.enabled:
651 result = dict(
652 enabled=False,
653 disabled=True
654 )
655 return result
656
657
658 class ModuleManager(object):
659 def __init__(self, *args, **kwargs):
660 self.module = kwargs.get('module', None)
661 self.client = F5RestClient(**self.module.params)
662 self.want = None
663 self.have = None
664 self.changes = None
665 self.replace_all_with = None
666 self.purge_links = list()
667
668 def _set_changed_options(self):
669 changed = {}
670 for key in Parameters.returnables:
671 if getattr(self.want, key) is not None:
672 changed[key] = getattr(self.want, key)
673 if changed:
674 self.changes = UsableChanges(params=changed)
675
676 def _update_changed_options(self):
677 diff = Difference(self.want, self.have)
678 updatables = Parameters.updatables
679 changed = dict()
680 for k in updatables:
681 change = diff.compare(k)
682 if change is None:
683 continue
684 else:
685 if isinstance(change, dict):
686 changed.update(change)
687 else:
688 changed[k] = change
689 if changed:
690 self.changes = UsableChanges(params=changed)
691 return True
692 return False
693
694 def exec_module(self):
695 start = datetime.now().isoformat()
696 version = tmos_version(self.client)
697 if not module_provisioned(self.client, 'gtm'):
698 raise F5ModuleError(
699 "GTM must be provisioned to use this module."
700 )
701 wants = None
702 if self.module.params['replace_all_with']:
703 self.replace_all_with = True
704
705 if self.module.params['aggregate']:
706 wants = self.merge_defaults_for_aggregate(self.module.params)
707
708 result = dict()
709 changed = False
710
711 if self.replace_all_with and self.purge_links:
712 self.purge()
713 changed = True
714
715 if self.module.params['aggregate']:
716 result['aggregate'] = list()
717 for want in wants:
718 output = self.execute(want)
719 if output['changed']:
720 changed = output['changed']
721 result['aggregate'].append(output)
722 else:
723 output = self.execute(self.module.params)
724 if output['changed']:
725 changed = output['changed']
726 result.update(output)
727 if changed:
728 result['changed'] = True
729 send_teem(start, self.client, self.module, version)
730 return result
731
732 def merge_defaults_for_aggregate(self, params):
733 defaults = deepcopy(params)
734 aggregate = defaults.pop('aggregate')
735
736 for i, j in enumerate(aggregate):
737 for k, v in iteritems(defaults):
738 if k != 'replace_all_with':
739 if j.get(k, None) is None and v is not None:
740 aggregate[i][k] = v
741
742 if self.replace_all_with:
743 self.compare_aggregate_names(aggregate)
744
745 return aggregate
746
747 def _combine_names(self, item):
748 server_name = transform_name(item['partition'], item['server_name'])
749 virtual_server = transform_name(name=item['virtual_server'])
750 result = '{0}:{1}'.format(server_name, virtual_server)
751 return result
752
753 def _transform_api_names(self, item):
754 if 'subPath' in item and item['subPath'] is None:
755 return item['name']
756 result = transform_name(item['fullPath'])
757 return result
758
759 def compare_aggregate_names(self, items):
760 on_device = self._read_purge_collection()
761
762 if not on_device:
763 return False
764
765 aggregates = [self._combine_names(item) for item in items]
766 collection = [self._transform_api_names(item) for item in on_device]
767
768 diff = set(collection) - set(aggregates)
769
770 if diff:
771 to_purge = [item['selfLink'] for item in on_device if self._transform_api_names(item) in diff]
772 self.purge_links.extend(to_purge)
773
774 def execute(self, params=None):
775 self.want = ModuleParameters(params=params)
776 self.have = ApiParameters()
777 self.changes = UsableChanges()
778
779 changed = False
780 result = dict()
781 state = params['state']
782
783 if state in ['present', 'enabled', 'disabled']:
784 changed = self.present()
785 elif state == "absent":
786 changed = self.absent()
787
788 reportable = ReportableChanges(params=self.changes.to_return())
789 changes = reportable.to_return()
790 result.update(**changes)
791 result.update(dict(changed=changed))
792 self._announce_deprecations(result)
793 return result
794
795 def _announce_deprecations(self, result):
796 warnings = result.pop('__warnings', [])
797 for warning in warnings:
798 self.client.module.deprecate(
799 msg=warning['msg'],
800 version=warning['version']
801 )
802
803 def present(self):
804 if self.exists():
805 return self.update()
806 else:
807 return self.create()
808
809 def absent(self):
810 if self.exists():
811 return self.remove()
812 return False
813
814 def purge(self):
815 if self.module.check_mode:
816 return True
817 self.purge_from_device()
818 return True
819
820 def update(self):
821 self.have = self.read_current_from_device()
822 if not self.should_update():
823 return False
824 if self.module.check_mode:
825 return True
826 self.update_on_device()
827 return True
828
829 def should_update(self):
830 result = self._update_changed_options()
831 if result:
832 return True
833 return False
834
835 def remove(self):
836 if self.module.check_mode:
837 return True
838 self.remove_from_device()
839 if self.exists():
840 raise F5ModuleError("Failed to delete the resource.")
841 return True
842
843 def create(self):
844 if self.want.state == 'disabled':
845 self.want.update({'disabled': True})
846 elif self.want.state in ['present', 'enabled']:
847 self.want.update({'enabled': True})
848 self._set_changed_options()
849 if self.module.check_mode:
850 return True
851 self.create_on_device()
852 return True
853
854 def exists(self):
855 if not self.pool_exist():
856 raise F5ModuleError('The specified GTM pool does not exist')
857
858 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}/members/{4}".format(
859 self.client.provider['server'],
860 self.client.provider['server_port'],
861 self.want.type,
862 transform_name(name=fq_name(self.want.partition, self.want.pool)),
863 transform_name(self.want.partition, self.want.name),
864 )
865 resp = self.client.api.get(uri)
866 try:
867 response = resp.json()
868 except ValueError as ex:
869 raise F5ModuleError(str(ex))
870
871 if resp.status == 404 or 'code' in response and response['code'] == 404:
872 return False
873 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
874 return True
875
876 errors = [401, 403, 409, 500, 501, 502, 503, 504]
877
878 if resp.status in errors or 'code' in response and response['code'] in errors:
879 if 'message' in response:
880 raise F5ModuleError(response['message'])
881 else:
882 raise F5ModuleError(resp.content)
883
884 def pool_exist(self):
885 if self.replace_all_with:
886 type = self.module.params['type']
887 pool_name = transform_name(name=fq_name(self.module.params['partition'], self.module.params['pool']))
888 else:
889 pool_name = transform_name(name=fq_name(self.want.partition, self.want.pool))
890 type = self.want.type
891
892 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}".format(
893 self.client.provider['server'],
894 self.client.provider['server_port'],
895 type,
896 pool_name
897
898 )
899 resp = self.client.api.get(uri)
900 try:
901 response = resp.json()
902 except ValueError as ex:
903 raise F5ModuleError(str(ex))
904
905 if resp.status == 404 or 'code' in response and response['code'] == 404:
906 return False
907 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
908 return True
909
910 errors = [401, 403, 409, 500, 501, 502, 503, 504]
911
912 if resp.status in errors or 'code' in response and response['code'] in errors:
913 if 'message' in response:
914 raise F5ModuleError(response['message'])
915 else:
916 raise F5ModuleError(resp.content)
917
918 def _read_purge_collection(self):
919 type = self.module.params['type']
920 pool_name = transform_name(name=fq_name(self.module.params['partition'], self.module.params['pool']))
921
922 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}/members".format(
923 self.client.provider['server'],
924 self.client.provider['server_port'],
925 type,
926 pool_name
927 )
928
929 query = '?$select=name,selfLink,fullPath,subPath'
930 resp = self.client.api.get(uri + query)
931
932 try:
933 response = resp.json()
934 except ValueError as ex:
935 raise F5ModuleError(str(ex))
936
937 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
938 if 'items' in response:
939 return response['items']
940 return []
941 raise F5ModuleError(resp.content)
942
943 def create_on_device(self):
944 params = self.changes.api_params()
945 params['name'] = self.want.name
946 params['partition'] = self.want.partition
947 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}/members/".format(
948 self.client.provider['server'],
949 self.client.provider['server_port'],
950 self.want.type,
951 transform_name(name=fq_name(self.want.partition, self.want.pool)),
952 )
953 resp = self.client.api.post(uri, json=params)
954 try:
955 response = resp.json()
956 except ValueError as ex:
957 raise F5ModuleError(str(ex))
958
959 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
960 return True
961 raise F5ModuleError(resp.content)
962
963 def update_on_device(self):
964 params = self.changes.api_params()
965 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}/members/{4}".format(
966 self.client.provider['server'],
967 self.client.provider['server_port'],
968 self.want.type,
969 transform_name(name=fq_name(self.want.partition, self.want.pool)),
970 transform_name(self.want.partition, self.want.name),
971 )
972 resp = self.client.api.patch(uri, json=params)
973 try:
974 response = resp.json()
975 except ValueError as ex:
976 raise F5ModuleError(str(ex))
977
978 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
979 return True
980 raise F5ModuleError(resp.content)
981
982 def remove_from_device(self):
983 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}/members/{4}".format(
984 self.client.provider['server'],
985 self.client.provider['server_port'],
986 self.want.type,
987 transform_name(name=fq_name(self.want.partition, self.want.pool)),
988 transform_name(self.want.partition, self.want.name),
989 )
990 response = self.client.api.delete(uri)
991 if response.status == 200:
992 return True
993 raise F5ModuleError(response.content)
994
995 def read_current_from_device(self):
996 uri = "https://{0}:{1}/mgmt/tm/gtm/pool/{2}/{3}/members/{4}".format(
997 self.client.provider['server'],
998 self.client.provider['server_port'],
999 self.want.type,
1000 transform_name(name=fq_name(self.want.partition, self.want.pool)),
1001 transform_name(self.want.partition, self.want.name),
1002 )
1003 resp = self.client.api.get(uri)
1004 try:
1005 response = resp.json()
1006 except ValueError as ex:
1007 raise F5ModuleError(str(ex))
1008
1009 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1010 return ApiParameters(params=response)
1011 raise F5ModuleError(resp.content)
1012
1013 def _prepare_links(self, collection):
1014 # this is to ensure no duplicates are in the provided collection
1015 no_dupes = list(set(collection))
1016 links = list()
1017 purge_paths = [urlparse(link).path for link in no_dupes]
1018
1019 for path in purge_paths:
1020 link = "https://{0}:{1}{2}".format(
1021 self.client.provider['server'],
1022 self.client.provider['server_port'],
1023 path
1024 )
1025 links.append(link)
1026 return links
1027
1028 def purge_from_device(self):
1029 links = self._prepare_links(self.purge_links)
1030
1031 with TransactionContextManager(self.client) as transact:
1032 for link in links:
1033 resp = transact.api.delete(link)
1034
1035 try:
1036 response = resp.json()
1037 except ValueError as ex:
1038 raise F5ModuleError(str(ex))
1039
1040 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
1041 raise F5ModuleError(resp.content)
1042
1043 return True
1044
1045
1046 class ArgumentSpec(object):
1047 def __init__(self):
1048 self.supports_check_mode = True
1049 self.types = [
1050 'a', 'aaaa', 'cname', 'mx', 'naptr', 'srv'
1051 ]
1052 element_spec = dict(
1053 server_name=dict(),
1054 virtual_server=dict(),
1055 member_order=dict(type='int'),
1056 monitor=dict(),
1057 ratio=dict(type='int'),
1058 description=dict(),
1059 limits=dict(
1060 type='dict',
1061 options=dict(
1062 bits_enabled=dict(type='bool'),
1063 packets_enabled=dict(type='bool'),
1064 connections_enabled=dict(type='bool'),
1065 bits_limit=dict(type='int'),
1066 packets_limit=dict(type='int'),
1067 connections_limit=dict(type='int')
1068 )
1069 ),
1070 state=dict(
1071 default='present',
1072 choices=['present', 'absent', 'disabled', 'enabled']
1073 ),
1074 partition=dict(
1075 default='Common',
1076 fallback=(env_fallback, ['F5_PARTITION'])
1077 ),
1078
1079 )
1080
1081 aggregate_spec = deepcopy(element_spec)
1082
1083 # remove default in aggregate spec, to handle common arguments
1084 remove_default_spec(aggregate_spec)
1085 aggregate_spec["state"].update(default="present")
1086 aggregate_spec["partition"].update(default="Common")
1087
1088 self.argument_spec = dict(
1089 aggregate=dict(
1090 type='list',
1091 elements='dict',
1092 options=aggregate_spec,
1093 aliases=['members'],
1094 required_one_of=[
1095 ['server_name', 'virtual_server']
1096 ],
1097 required_together=[
1098 ['server_name', 'virtual_server']
1099 ]
1100
1101 ),
1102 pool=dict(required=True),
1103 type=dict(
1104 choices=self.types,
1105 required=True
1106 ),
1107 replace_all_with=dict(
1108 type='bool',
1109 aliases=['purge'],
1110 default='no'
1111 ),
1112 partition=dict(
1113 default='Common',
1114 fallback=(env_fallback, ['F5_PARTITION'])
1115 )
1116
1117 )
1118 self.argument_spec.update(element_spec)
1119 self.argument_spec.update(f5_argument_spec)
1120 self.required_together = [
1121 ['server_name', 'virtual_server']
1122 ]
1123 self.mutually_exclusive = [
1124 ['server_name', 'aggregate'],
1125 ['virtual_server', 'aggregate']
1126 ]
1127 self.required_one_of = [
1128 ['server_name', 'virtual_server', 'aggregate']
1129 ]
1130
1131
1132 def main():
1133 spec = ArgumentSpec()
1134
1135 module = AnsibleModule(
1136 argument_spec=spec.argument_spec,
1137 supports_check_mode=spec.supports_check_mode,
1138 mutually_exclusive=spec.mutually_exclusive,
1139 required_one_of=spec.required_one_of,
1140 required_together=spec.required_together,
1141 )
1142
1143 try:
1144 mm = ModuleManager(module=module)
1145 results = mm.exec_module()
1146 module.exit_json(**results)
1147 except F5ModuleError as ex:
1148 module.fail_json(msg=str(ex))
1149
1150
1151 if __name__ == '__main__':
1152 main()