Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, 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_device_ha_group
13 short_description: Manage HA group settings on a BIG-IP system
14 description:
15 - Manage HA (High Availability) group settings on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Name of the HA group to create/manage.
21 type: str
22 required: True
23 enable:
24 description:
25 - When set to C(false), the system disables the HA score feature.
26 type: bool
27 default: true
28 description:
29 description:
30 - User created HA group description.
31 type: str
32 active_bonus:
33 description:
34 - Specifies the extra value to be added to the HA score of the active unit.
35 - When system creates HA group this value is set to C(10) by the system.
36 type: int
37 pools:
38 description:
39 - Specifies pools to contribute to the HA score.
40 - The pools must exist on the BIG-IP, otherwise the operation will fail.
41 type: list
42 elements: dict
43 suboptions:
44 pool_name:
45 description:
46 - The pool name which is used to contribute to the HA score.
47 - Referencing the pool can be done in the full path format for example, C(/Common/pool_name).
48 - When the pool is referenced in full path format, the C(partition) parameter is ignored.
49 type: str
50 required: True
51 attribute:
52 description:
53 - The pool attribute that contributes to the HA score.
54 type: str
55 choices:
56 - percent-up-members
57 default: 'percent-up-members'
58 weight:
59 description:
60 - Maximum value the selected pool attribute contributes to the HA score.
61 type: int
62 required: True
63 minimum_threshold:
64 description:
65 - Below this value, the selected pool attribute contributes nothing to the HA score.
66 - This value must be greater than the number of pool members present in the pool.
67 - In TMOS versions 12.x this attribute is named C(threshold), however it has been deprecated
68 in versions 13.x and above.
69 - Specifying this attribute in the module running against v12.x will keep the same behavior
70 as if C(threshold) option was set.
71 type: int
72 partition:
73 description:
74 - Device partition where the specified pool exists.
75 - This parameter is ignored if the C(pool_name) is specified in full path format.
76 type: str
77 default: Common
78 trunks:
79 description:
80 - Specifies trunks to contribute to the HA score.
81 - The trunks must exist on the BIG-IP, otherwise the operation will fail.
82 type: list
83 elements: dict
84 suboptions:
85 trunk_name:
86 description:
87 - The trunk name used to contribute to the HA score.
88 type: str
89 required: True
90 attribute:
91 description:
92 - The trunk attribute that contributes to the HA score.
93 type: str
94 choices:
95 - percent-up-members
96 default: 'percent-up-members'
97 weight:
98 description:
99 - Maximum value the selected trunk attribute contributes to the HA score.
100 type: int
101 required: True
102 minimum_threshold:
103 description:
104 - Below this value the selected trunk attribute contributes nothing to the HA score.
105 - This value must be greater than the number of trunk members.
106 - In TMOS versions 12.x this attribute is named C(threshold), however it has been deprecated
107 in versions 13.x and above.
108 - Specifying this attribute in the module running against v12.x will keep the same behavior
109 as if C(threshold) option was set.
110 type: int
111 state:
112 description:
113 - When C(present), ensures the resource exists.
114 - When C(absent), ensures the resource is removed.
115 type: str
116 choices:
117 - present
118 - absent
119 default: present
120 notes:
121 - This module does not support atomic removal of HA group objects.
122 extends_documentation_fragment: f5networks.f5_modules.f5
123 author:
124 - Wojciech Wypior (@wojtek0806)
125 '''
126
127 EXAMPLES = r'''
128 - name: Create HA group no members, not active
129 bigip_device_ha_group:
130 name: foo_ha
131 description: empty_foo
132 active_bonus: 20
133 enable: false
134 provider:
135 password: secret
136 server: lb.mydomain.com
137 user: admin
138 delegate_to: localhost
139
140 - name: Create HA group with pools and trunks
141 bigip_device_ha_group:
142 name: baz_ha
143 description: non_empty_baz
144 active_bonus: 15
145 pools:
146 - pool_name: foopool
147 weight: 30
148 minimum_threshold: 1
149 trunks:
150 - trunk_name: footrunk
151 weight: 70
152 minimum_threshold: 2
153 provider:
154 password: secret
155 server: lb.mydomain.com
156 user: admin
157 delegate_to: localhost
158
159 - name: Create HA group pools using full_path format
160 bigip_device_ha_group:
161 name: bar_ha
162 description: non_empty_bar
163 active_bonus: 12
164 pools:
165 - pool_name: /Baz/foopool
166 weight: 30
167 minimum_threshold: 1
168 provider:
169 password: secret
170 server: lb.mydomain.com
171 user: admin
172 delegate_to: localhost
173
174 - name: Remove HA group
175 bigip_device_ha_group:
176 name: foo_ha
177 state: absent
178 provider:
179 password: secret
180 server: lb.mydomain.com
181 user: admin
182 delegate_to: localhost
183 '''
184
185 RETURN = r'''
186 name:
187 description: Name of the HA group.
188 returned: changed
189 type: str
190 sample: foo_HA
191 enable:
192 description: Enables or disables the HA score feature.
193 returned: changed
194 type: bool
195 sample: true
196 description:
197 description: User created HA group description.
198 returned: changed
199 type: str
200 sample: Some Group
201 active_bonus:
202 description: The extra value to be added to the HA score of the active unit.
203 returned: changed
204 type: int
205 sample: 20
206 pools:
207 description: The pools to contribute to the HA score.
208 returned: changed
209 type: complex
210 contains:
211 pool_name:
212 description: The pool name which is used to contribute to the HA score.
213 returned: changed
214 type: str
215 sample: foo_pool
216 attribute:
217 description: The pool attribute that contributes to the HA score.
218 returned: changed
219 type: str
220 sample: percent-up-members
221 weight:
222 description: Maximum value the selected pool attribute contributes to the HA score.
223 returned: changed
224 type: int
225 sample: 40
226 minimum_threshold:
227 description: Below this value the selected pool attribute contributes nothing to the HA score.
228 returned: changed
229 type: int
230 sample: 2
231 partition:
232 description: Device partition where the specified pool exists.
233 returned: changed
234 type: str
235 sample: Common
236 sample: hash/dictionary of values
237 trunks:
238 description: The trunks to contribute to the HA score.
239 returned: changed
240 type: complex
241 contains:
242 trunk_name:
243 description: The trunk name used to contribute to the HA score.
244 returned: changed
245 type: str
246 sample: foo_trunk
247 attribute:
248 description: The trunk attribute that contributes to the HA score.
249 returned: changed
250 type: str
251 sample: percent-up-members
252 weight:
253 description: Maximum value the selected trunk attribute contributes to the HA score.
254 returned: changed
255 type: int
256 sample: 40
257 minimum_threshold:
258 description: Below this value, the selected trunk attribute contributes nothing to the HA score.
259 returned: changed
260 type: int
261 sample: 2
262 sample: hash/dictionary of values
263 '''
264 import traceback
265 from datetime import datetime
266
267 try:
268 from packaging.version import Version
269 except ImportError:
270 HAS_PACKAGING = False
271 Version = None
272 PACKAGING_IMPORT_ERROR = traceback.format_exc()
273 else:
274 HAS_PACKAGING = True
275 PACKAGING_IMPORT_ERROR = None
276
277 from ansible.module_utils.basic import (
278 AnsibleModule, env_fallback, missing_required_lib
279 )
280 from ansible.module_utils.six import iteritems
281
282 from ..module_utils.bigip import F5RestClient
283 from ..module_utils.common import (
284 F5ModuleError, AnsibleF5Parameters, fq_name, f5_argument_spec, flatten_boolean
285 )
286 from ..module_utils.icontrol import tmos_version
287 from ..module_utils.teem import send_teem
288
289
290 class Parameters(AnsibleF5Parameters):
291 api_map = {
292 'activeBonus': 'active_bonus'
293 }
294
295 api_attributes = [
296 'activeBonus',
297 'description',
298 'pools',
299 'trunks',
300 'enabled',
301 'disabled',
302 ]
303
304 returnables = [
305 'name',
306 'enabled',
307 'disabled',
308 'description',
309 'active_bonus',
310 'pools',
311 'trunks',
312 ]
313
314 updatables = [
315 'enabled',
316 'disabled',
317 'description',
318 'active_bonus',
319 'pools',
320 'trunks',
321 ]
322
323
324 class ApiParameters(Parameters):
325 @property
326 def enabled(self):
327 result = flatten_boolean(self._values['enabled'])
328 if result == 'yes':
329 return True
330 return None
331
332 @property
333 def disabled(self):
334 result = flatten_boolean(self._values['disabled'])
335 if result == 'yes':
336 return True
337 return None
338
339
340 class ModuleParameters(Parameters):
341 @property
342 def enabled(self):
343 result = flatten_boolean(self._values['enable'])
344 if result == 'yes':
345 return True
346 return None
347
348 @property
349 def disabled(self):
350 result = flatten_boolean(self._values['enable'])
351 if result == 'no':
352 return True
353 return None
354
355 @property
356 def pools(self):
357 version_13 = self._is_v13_and_above()
358 result = list()
359 if self._values['pools'] is None:
360 return None
361 for item in self._values['pools']:
362 pool = dict()
363 pool['name'] = fq_name(item['partition'], item['pool_name'])
364 pool['weight'] = self._handle_weight(item['weight'])
365 if 'attribute' in item:
366 pool['attribute'] = item['attribute']
367 if 'minimum_threshold' in item:
368 if version_13:
369 pool['minimumThreshold'] = item['minimum_threshold']
370 else:
371 pool['threshold'] = item['minimum_threshold']
372 result.append(self._filter_params(pool))
373 return result
374
375 @property
376 def trunks(self):
377 version_13 = self._is_v13_and_above()
378 result = list()
379 if self._values['trunks'] is None:
380 return None
381 for item in self._values['trunks']:
382 trunk = dict()
383 trunk['name'] = item['trunk_name']
384 trunk['weight'] = self._handle_weight(item['weight'])
385 if 'attribute' in item:
386 trunk['attribute'] = item['attribute']
387 if 'minimum_threshold' in item:
388 if version_13:
389 trunk['minimumThreshold'] = item['minimum_threshold']
390 else:
391 trunk['threshold'] = item['minimum_threshold']
392 result.append(self._filter_params(trunk))
393 return result
394
395 def _is_v13_and_above(self):
396 version = tmos_version(self.client)
397 if Version(version) >= Version('13.0.0'):
398 return True
399 return False
400
401 def _handle_weight(self, weight):
402 if weight < 10 or weight > 100:
403 raise F5ModuleError(
404 "Weight value must be in the range: '10 - 100'."
405 )
406 return weight
407
408
409 class Changes(Parameters):
410 def to_return(self):
411 result = {}
412 try:
413 for returnable in self.returnables:
414 result[returnable] = getattr(self, returnable)
415 result = self._filter_params(result)
416 except Exception:
417 raise
418 return result
419
420
421 class UsableChanges(Changes):
422 pass
423
424
425 class ReportableChanges(Changes):
426 returnables = [
427 'name',
428 'enable',
429 'description',
430 'active_bonus',
431 'pools',
432 'trunks',
433 ]
434
435 @property
436 def enable(self):
437 enabled = flatten_boolean(self._values['enabled'])
438 disabled = flatten_boolean(self._values['disabled'])
439 if enabled == 'yes':
440 return 'yes'
441 if disabled == 'yes':
442 return 'no'
443 return None
444
445 @property
446 def pools(self):
447 result = list()
448 if self._values['pools'] is None:
449 return None
450 for item in self._values['pools']:
451 pool = dict()
452 pool['pool_name'] = item['name']
453 pool['weight'] = item['weight']
454 if 'attribute' in item:
455 pool['attribute'] = item['attribute']
456 if 'minimumThreshold' in item:
457 pool['minimum_threshold'] = item['minimumThreshold']
458 if 'threshold' in item:
459 pool['minimum_threshold'] = item['threshold']
460 result.append(pool)
461 return result
462
463 @property
464 def trunks(self):
465 result = list()
466 if self._values['trunks'] is None:
467 return None
468 for item in self._values['trunks']:
469 trunk = dict()
470 trunk['trunk_name'] = item['name']
471 trunk['weight'] = item['weight']
472 if 'attribute' in item:
473 trunk['attribute'] = item['attribute']
474 if 'minimumThreshold' in item:
475 trunk['minimum_threshold'] = item['minimumThreshold']
476 if 'threshold' in item:
477 trunk['minimum_threshold'] = item['threshold']
478 result.append(trunk)
479 return result
480
481
482 class Difference(object):
483 def __init__(self, want, have=None):
484 self.want = want
485 self.have = have
486
487 def compare(self, param):
488 try:
489 result = getattr(self, param)
490 return result
491 except AttributeError:
492 return self.__default(param)
493
494 def __default(self, param):
495 attr1 = getattr(self.want, param)
496 try:
497 attr2 = getattr(self.have, param)
498 if attr1 != attr2:
499 return attr1
500 except AttributeError:
501 return attr1
502
503 def to_tuple(self, items):
504 result = []
505 for x in items:
506 tmp = [(str(k), str(v)) for k, v in iteritems(x)]
507 result += tmp
508 return result
509
510 def _diff_complex_items(self, want, have):
511 if want == [] and have is None:
512 return None
513 if want is None:
514 return None
515 if have is None:
516 return want
517 w = self.to_tuple(want)
518 h = self.to_tuple(have)
519 if set(w).issubset(set(h)):
520 return None
521 else:
522 return want
523
524 @property
525 def pools(self):
526 result = self._diff_complex_items(self.want.pools, self.have.pools)
527 return result
528
529 @property
530 def trunks(self):
531 result = self._diff_complex_items(self.want.trunks, self.have.trunks)
532 return result
533
534
535 class ModuleManager(object):
536 def __init__(self, *args, **kwargs):
537 self.module = kwargs.get('module', None)
538 self.client = F5RestClient(**self.module.params)
539 self.want = ModuleParameters(params=self.module.params, client=self.client)
540 self.have = ApiParameters()
541 self.changes = UsableChanges()
542
543 def _set_changed_options(self):
544 changed = {}
545 for key in Parameters.returnables:
546 if getattr(self.want, key) is not None:
547 changed[key] = getattr(self.want, key)
548 if changed:
549 self.changes = UsableChanges(params=changed)
550
551 def _update_changed_options(self):
552 diff = Difference(self.want, self.have)
553 updatables = Parameters.updatables
554 changed = dict()
555 for k in updatables:
556 change = diff.compare(k)
557 if change is None:
558 continue
559 else:
560 if isinstance(change, dict):
561 changed.update(change)
562 else:
563 changed[k] = change
564 if changed:
565 self.changes = UsableChanges(params=changed)
566 return True
567 return False
568
569 def _announce_deprecations(self, result):
570 warnings = result.pop('__warnings', [])
571 for warning in warnings:
572 self.client.module.deprecate(
573 msg=warning['msg'],
574 version=warning['version']
575 )
576
577 def exec_module(self):
578 start = datetime.now().isoformat()
579 version = tmos_version(self.client)
580 changed = False
581 result = dict()
582 state = self.want.state
583
584 if state == "present":
585 changed = self.present()
586 elif state == "absent":
587 changed = self.absent()
588
589 reportable = ReportableChanges(params=self.changes.to_return())
590 changes = reportable.to_return()
591 result.update(**changes)
592 result.update(dict(changed=changed))
593 self._announce_deprecations(result)
594 send_teem(start, self.client, self.module, version)
595 return result
596
597 def present(self):
598 if self.exists():
599 return self.update()
600 else:
601 return self.create()
602
603 def absent(self):
604 if self.exists():
605 return self.remove()
606 return False
607
608 def should_update(self):
609 result = self._update_changed_options()
610 if result:
611 return True
612 return False
613
614 def update(self):
615 self.have = self.read_current_from_device()
616 if not self.should_update():
617 return False
618 if self.module.check_mode:
619 return True
620 self.update_on_device()
621 return True
622
623 def remove(self):
624 if self.module.check_mode:
625 return True
626 self.remove_from_device()
627 if self.exists():
628 raise F5ModuleError("Failed to delete the resource.")
629 return True
630
631 def create(self):
632 self._set_changed_options()
633 if self.module.check_mode:
634 return True
635 self.create_on_device()
636 return True
637
638 def exists(self):
639 errors = [401, 403, 409, 500, 501, 502, 503, 504]
640 uri = "https://{0}:{1}/mgmt/tm/sys/ha-group/{2}".format(
641 self.client.provider['server'],
642 self.client.provider['server_port'],
643 self.want.name
644 )
645 resp = self.client.api.get(uri)
646 try:
647 response = resp.json()
648 except ValueError as ex:
649 raise F5ModuleError(str(ex))
650
651 if resp.status == 404 or 'code' in response and response['code'] == 404:
652 return False
653 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
654 return True
655
656 if resp.status in errors or 'code' in response and response['code'] in errors:
657 if 'message' in response:
658 raise F5ModuleError(response['message'])
659 else:
660 raise F5ModuleError(resp.content)
661
662 def create_on_device(self):
663 params = self.changes.api_params()
664 params['name'] = self.want.name
665 uri = "https://{0}:{1}/mgmt/tm/sys/ha-group/".format(
666 self.client.provider['server'],
667 self.client.provider['server_port'],
668 )
669 resp = self.client.api.post(uri, json=params)
670 try:
671 response = resp.json()
672 except ValueError as ex:
673 raise F5ModuleError(str(ex))
674
675 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
676 return True
677 raise F5ModuleError(resp.content)
678
679 def update_on_device(self):
680 params = self.changes.api_params()
681 uri = "https://{0}:{1}/mgmt/tm/sys/ha-group/{2}".format(
682 self.client.provider['server'],
683 self.client.provider['server_port'],
684 self.want.name
685 )
686 resp = self.client.api.patch(uri, json=params)
687 try:
688 response = resp.json()
689 except ValueError as ex:
690 raise F5ModuleError(str(ex))
691
692 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
693 return True
694 raise F5ModuleError(resp.content)
695
696 def remove_from_device(self):
697 uri = "https://{0}:{1}/mgmt/tm/sys/ha-group/{2}".format(
698 self.client.provider['server'],
699 self.client.provider['server_port'],
700 self.want.name
701 )
702 response = self.client.api.delete(uri)
703 if response.status == 200:
704 return True
705 raise F5ModuleError(response.content)
706
707 def read_current_from_device(self):
708 uri = "https://{0}:{1}/mgmt/tm/sys/ha-group/{2}".format(
709 self.client.provider['server'],
710 self.client.provider['server_port'],
711 self.want.name
712 )
713 resp = self.client.api.get(uri)
714 try:
715 response = resp.json()
716 except ValueError as ex:
717 raise F5ModuleError(str(ex))
718
719 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
720 return ApiParameters(params=response)
721 raise F5ModuleError(resp.content)
722
723
724 class ArgumentSpec(object):
725 def __init__(self):
726 self.supports_check_mode = True
727 argument_spec = dict(
728 name=dict(
729 required=True
730 ),
731 enable=dict(
732 type='bool',
733 default='yes'
734 ),
735 description=dict(),
736 active_bonus=dict(
737 type='int'
738 ),
739 pools=dict(
740 type='list',
741 elements='dict',
742 options=dict(
743 pool_name=dict(
744 required=True
745 ),
746 attribute=dict(
747 choices=[
748 'percent-up-members'
749 ],
750 default='percent-up-members'
751 ),
752 weight=dict(
753 required=True,
754 type='int'
755 ),
756 minimum_threshold=dict(
757 type='int'
758 ),
759 partition=dict(
760 default='Common',
761 fallback=(env_fallback, ['F5_PARTITION'])
762 )
763 )
764 ),
765 trunks=dict(
766 type='list',
767 elements='dict',
768 options=dict(
769 trunk_name=dict(
770 required=True
771 ),
772 attribute=dict(
773 choices=[
774 'percent-up-members'
775 ],
776 default='percent-up-members'
777 ),
778 weight=dict(
779 required=True,
780 type='int'
781 ),
782 minimum_threshold=dict(
783 type='int'
784 ),
785 )
786 ),
787 state=dict(
788 default='present',
789 choices=['present', 'absent']
790 )
791
792 )
793 self.argument_spec = {}
794 self.argument_spec.update(f5_argument_spec)
795 self.argument_spec.update(argument_spec)
796
797
798 def main():
799 spec = ArgumentSpec()
800
801 module = AnsibleModule(
802 argument_spec=spec.argument_spec,
803 supports_check_mode=spec.supports_check_mode,
804 )
805
806 if not HAS_PACKAGING:
807 module.fail_json(
808 msg=missing_required_lib('packaging'),
809 exception=PACKAGING_IMPORT_ERROR
810 )
811
812 try:
813 mm = ModuleManager(module=module)
814 results = mm.exec_module()
815 module.exit_json(**results)
816 except F5ModuleError as ex:
817 module.fail_json(msg=str(ex))
818
819
820 if __name__ == '__main__':
821 main()