Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_device_traffic_group.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_device_traffic_group
13 short_description: Manages traffic groups on BIG-IP
14 description:
15 - Supports managing traffic groups and their attributes on a BIG-IP.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - The name of the traffic group.
21 type: str
22 required: True
23 mac_address:
24 description:
25 - Specifies the floating Media Access Control (MAC) address associated with the floating IP addresses
26 defined for a traffic group.
27 - Primarily, a MAC masquerade address minimizes ARP communications or dropped packets as a result of failover.
28 - A MAC masquerade address ensures any traffic destined for a specific traffic group reaches an available
29 device after failover, which happens because, along with the traffic group, the MAC masquerade address floats
30 to the available device.
31 - Without a MAC masquerade address, the sending host must learn the MAC address for a newly-active device,
32 either by sending an ARP request or by relying on the gratuitous ARP from the newly-active device.
33 - To unset the MAC address, specify an empty value (C("")) to this parameter.
34 type: str
35 ha_order:
36 description:
37 - Specifies the order in which you would like to assign devices for failover.
38 - If you configure this setting, you must configure the setting on every traffic group in the device group.
39 - The values should be device names of the devices that belong to the failover group configured previously.
40 - The order in which the devices are placed as arguments to this parameter determines their HA order
41 on the device. Meaning that changing the order of the same elements will cause a change on the unit.
42 - To disable an HA order failover method, specify an empty string value (C("")) to this parameter.
43 - Disabling an HA order will revert the device back to using the Load Aware method (the default),
44 unless the C(ha_group) setting is also configured.
45 - Device names will be prepended with a partition by the module, so you can provide either the full path format
46 name C(/Common/bigip1) or just the name string C(bigip1).
47 type: list
48 elements: str
49 ha_group:
50 description:
51 - Specifies a configured C(HA group) to be associated with the traffic group.
52 - Once you create an HA group on a device and associate the HA group with a traffic group,
53 you must create an HA group and associate it with that same traffic group on every device in the device group.
54 - To disable an HA group failover method, specify an empty string value (C("")) to this parameter.
55 - Disabling an HA group will revert the device back to using C(Load Aware) method (the default),
56 unless C(ha_order) setting is also configured.
57 - The C(auto_failback) and C(auto_failback_time) are not compatible with C(ha_group).
58 type: str
59 ha_load_factor:
60 description:
61 - The value of the load the traffic-group presents the system relative to other traffic groups.
62 - This parameter only takes effect when C(Load Aware) failover method is in use.
63 - The correct value range is C(1 - 1000) inclusive.
64 type: int
65 auto_failback:
66 description:
67 - Specifies whether the traffic group fails back to the initial device specified in C(ha_order).
68 type: bool
69 auto_failback_time:
70 description:
71 - Specifies the number of seconds the system delays before failing back to the initial device
72 specified in C(ha_order).
73 - The correct value range is C(0 - 300) inclusive.
74 type: int
75 partition:
76 description:
77 - Device partition to manage resources on.
78 type: str
79 default: Common
80 state:
81 description:
82 - When C(present), ensures the traffic group exists.
83 - When C(absent), ensures the traffic group is removed.
84 type: str
85 choices:
86 - present
87 - absent
88 default: present
89 extends_documentation_fragment: f5networks.f5_modules.f5
90 author:
91 - Tim Rupp (@caphrim007)
92 - Wojciech Wypior (@wojtek0806)
93 '''
94
95 EXAMPLES = r'''
96 - name: Create a traffic group
97 bigip_device_traffic_group:
98 name: foo1
99 state: present
100 provider:
101 user: admin
102 password: secret
103 server: lb.mydomain.com
104 delegate_to: localhost
105
106 - name: Create a traffic group with ha_group failover
107 bigip_device_traffic_group:
108 name: foo2
109 state: present
110 ha_group: foo_HA_grp
111 provider:
112 user: admin
113 password: secret
114 server: lb.mydomain.com
115 delegate_to: localhost
116
117 - name: Create a traffic group with ha_order failover
118 bigip_device_traffic_group:
119 name: foo3
120 state: present
121 ha_order:
122 - /Common/bigip1.lab.local
123 - /Common/bigip2.lab.local
124 auto_failback: true
125 auto_failback_time: 40
126 provider:
127 user: admin
128 password: secret
129 server: lb.mydomain.com
130 delegate_to: localhost
131
132 - name: Change traffic group ha_order to ha_group
133 bigip_device_traffic_group:
134 name: foo3
135 state: present
136 ha_group: foo_HA_grp
137 ha_order: ""
138 auto_failback: false
139 provider:
140 user: admin
141 password: secret
142 server: lb.mydomain.com
143 delegate_to: localhost
144
145 - name: Remove traffic group
146 bigip_device_traffic_group:
147 name: foo
148 state: absent
149 provider:
150 user: admin
151 password: secret
152 server: lb.mydomain.com
153 delegate_to: localhost
154 '''
155
156 RETURN = r'''
157 mac_address:
158 description: The MAC masquerade address
159 returned: changed
160 type: str
161 sample: "02:01:d7:93:35:08"
162 ha_group:
163 description: The configured HA group associated with traffic group.
164 returned: changed
165 type: str
166 sample: foo_HA_grp
167 ha_order:
168 description: Specifies the order in which the devices will failover.
169 returned: changed
170 type: list
171 sample: ['/Common/bigip1', '/Common/bigip2']
172 ha_load_factor:
173 description: The value of the load the traffic-group presents the system relative to other traffic groups.
174 returned: changed
175 type: int
176 sample: 20
177 auto_failback:
178 description: Specifies whether the traffic group fails back to the initial device specified in ha_order.
179 returned: changed
180 type: bool
181 sample: true
182 auto_failback_time:
183 description: Specifies the number of seconds the system delays before failing back.
184 returned: changed
185 type: int
186 sample: 60
187 '''
188 from datetime import datetime
189 from ansible.module_utils.basic import (
190 AnsibleModule, env_fallback
191 )
192
193 from ..module_utils.bigip import F5RestClient
194 from ..module_utils.common import (
195 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
196 )
197 from ..module_utils.icontrol import tmos_version
198 from ..module_utils.teem import send_teem
199
200
201 class Parameters(AnsibleF5Parameters):
202 api_map = {
203 'mac': 'mac_address',
204 'haGroup': 'ha_group',
205 'haOrder': 'ha_order',
206 'haLoadFactor': 'ha_load_factor',
207 'autoFailbackTime': 'auto_failback_time',
208 'autoFailbackEnabled': 'auto_failback',
209 }
210
211 api_attributes = [
212 'mac',
213 'haGroup',
214 'haOrder',
215 'haLoadFactor',
216 'autoFailbackTime',
217 'autoFailbackEnabled',
218
219 ]
220
221 returnables = [
222 'mac_address',
223 'ha_group',
224 'ha_order',
225 'ha_load_factor',
226 'auto_failback_time',
227 'auto_failback',
228 ]
229
230 updatables = [
231 'mac_address',
232 'ha_group',
233 'ha_order',
234 'ha_load_factor',
235 'auto_failback_time',
236 'auto_failback',
237 ]
238
239
240 class ApiParameters(Parameters):
241 pass
242
243
244 class ModuleParameters(Parameters):
245 @property
246 def mac_address(self):
247 if self._values['mac_address'] is None:
248 return None
249 if self._values['mac_address'] == '':
250 return 'none'
251 return self._values['mac_address']
252
253 @property
254 def ha_group(self):
255 if self._values['ha_group'] is None:
256 return None
257 if self._values['ha_group'] == '':
258 return 'none'
259 if self.auto_failback == 'true':
260 raise F5ModuleError(
261 "The auto_failback cannot be enabled when ha_group is specified."
262 )
263 return self._values['ha_group']
264
265 @property
266 def ha_load_factor(self):
267 if self._values['ha_load_factor'] is None:
268 return None
269 value = self._values['ha_load_factor']
270 if value < 1 or value > 1000:
271 raise F5ModuleError(
272 "Invalid ha_load_factor value, correct range is 1 - 1000, specified value: {0}.".format(value))
273 return value
274
275 @property
276 def auto_failback_time(self):
277 if self._values['auto_failback_time'] is None:
278 return None
279 value = self._values['auto_failback_time']
280 if value < 0 or value > 300:
281 raise F5ModuleError(
282 "Invalid auto_failback_time value, correct range is 0 - 300, specified value: {0}.".format(value))
283 return value
284
285 @property
286 def auto_failback(self):
287 result = flatten_boolean(self._values['auto_failback'])
288 if result == 'yes':
289 return 'true'
290 if result == 'no':
291 return 'false'
292 return None
293
294 @property
295 def ha_order(self):
296 if self._values['ha_order'] is None:
297 return None
298 if len(self._values['ha_order']) == 1 and self._values['ha_order'][0] == '':
299 if self.auto_failback == 'true':
300 raise F5ModuleError(
301 'Cannot enable auto failback when HA order list is empty, at least one device must be specified.'
302 )
303 return 'none'
304 result = [fq_name(self.partition, value) for value in self._values['ha_order']]
305 return result
306
307
308 class Changes(Parameters):
309 def to_return(self):
310 result = {}
311 try:
312 for returnable in self.returnables:
313 result[returnable] = getattr(self, returnable)
314 result = self._filter_params(result)
315 except Exception:
316 raise
317 return result
318
319
320 class UsableChanges(Changes):
321 pass
322
323
324 class ReportableChanges(Changes):
325
326 @property
327 def mac_address(self):
328 if self._values['mac_address'] is None:
329 return None
330 if self._values['mac_address'] == 'none':
331 return ''
332 return self._values['mac_address']
333
334 @property
335 def ha_group(self):
336 if self._values['ha_group'] is None:
337 return None
338 if self._values['ha_group'] == 'none':
339 return ''
340 return self._values['ha_group']
341
342 @property
343 def auto_failback(self):
344 result = self._values['auto_failback']
345 if result == 'true':
346 return 'yes'
347 if result == 'false':
348 return 'no'
349 return None
350
351 @property
352 def ha_order(self):
353 if self._values['ha_order'] is None:
354 return None
355 if self._values['ha_order'] == 'none':
356 return ''
357 return self._values['ha_order']
358
359
360 class Difference(object):
361 def __init__(self, want, have=None):
362 self.want = want
363 self.have = have
364
365 def compare(self, param):
366 try:
367 result = getattr(self, param)
368 return result
369 except AttributeError:
370 return self.__default(param)
371
372 def __default(self, param):
373 attr1 = getattr(self.want, param)
374 try:
375 attr2 = getattr(self.have, param)
376 if attr1 != attr2:
377 return attr1
378 except AttributeError:
379 return attr1
380
381 @property
382 def ha_group(self):
383 if self.want.ha_group is None:
384 return None
385 if self.have.ha_group is None and self.want.ha_group == 'none':
386 return None
387 if self.want.ha_group != self.have.ha_group:
388 if self.have.auto_failback == 'true' and self.want.auto_failback != 'false':
389 raise F5ModuleError(
390 "The auto_failback parameter on the device must disabled to use ha_group failover method."
391 )
392 return self.want.ha_group
393
394 @property
395 def ha_order(self):
396 # Device order is literally derived from the order in the array,
397 # hence lists with the same elements but in different order cannot be equal, so cmp_simple_list
398 # function will not work here.
399 if self.want.ha_order is None:
400 return None
401 if self.have.ha_order is None and self.want.ha_order == 'none':
402 return None
403 if self.want.ha_order != self.have.ha_order:
404 return self.want.ha_order
405
406 @property
407 def partition(self):
408 raise F5ModuleError(
409 "Partition cannot be changed for a traffic group. Only /Common is allowed."
410 )
411
412
413 class ModuleManager(object):
414 def __init__(self, *args, **kwargs):
415 self.module = kwargs.get('module', None)
416 self.client = F5RestClient(**self.module.params)
417 self.have = None
418 self.want = ModuleParameters(params=self.module.params)
419 self.changes = UsableChanges()
420
421 def _set_changed_options(self):
422 changed = {}
423 for key in Parameters.returnables:
424 if getattr(self.want, key) is not None:
425 changed[key] = getattr(self.want, key)
426 if changed:
427 self.changes = UsableChanges(params=changed)
428
429 def _update_changed_options(self):
430 diff = Difference(self.want, self.have)
431 updatables = Parameters.updatables
432 changed = dict()
433 for k in updatables:
434 change = diff.compare(k)
435 if change is None:
436 continue
437 else:
438 if isinstance(change, dict):
439 changed.update(change)
440 else:
441 changed[k] = change
442 if changed:
443 self.changes = UsableChanges(params=changed)
444 return True
445 return False
446
447 def _announce_deprecations(self, result):
448 warnings = result.pop('__warnings', [])
449 for warning in warnings:
450 self.module.deprecate(
451 msg=warning['msg'],
452 version=warning['version']
453 )
454
455 def exec_module(self):
456 start = datetime.now().isoformat()
457 version = tmos_version(self.client)
458 changed = False
459 result = dict()
460 state = self.want.state
461
462 if state == "present":
463 changed = self.present()
464 elif state == "absent":
465 changed = self.absent()
466
467 reportable = ReportableChanges(params=self.changes.to_return())
468 changes = reportable.to_return()
469 result.update(**changes)
470 result.update(dict(changed=changed))
471 self._announce_deprecations(result)
472 send_teem(start, self.client, self.module, version)
473 return result
474
475 def present(self):
476 if self.exists():
477 return self.update()
478 else:
479 return self.create()
480
481 def absent(self):
482 if self.exists():
483 return self.remove()
484 return False
485
486 def should_update(self):
487 result = self._update_changed_options()
488 if result:
489 return True
490 return False
491
492 def update(self):
493 self.have = self.read_current_from_device()
494 if not self.should_update():
495 return False
496 if self.module.check_mode:
497 return True
498 self.update_on_device()
499 return True
500
501 def remove(self):
502 if self.module.check_mode:
503 return True
504 self.remove_from_device()
505 if self.exists():
506 raise F5ModuleError("Failed to delete the resource.")
507 return True
508
509 def create(self):
510 self._set_changed_options()
511 if self.want.partition.lower().strip('/') != 'common':
512 raise F5ModuleError(
513 "Traffic groups can only be created in the /Common partition"
514 )
515 if self.module.check_mode:
516 return True
517 self.create_on_device()
518 return True
519
520 def exists(self):
521 errors = [401, 403, 409, 500, 501, 502, 503, 504]
522 uri = "https://{0}:{1}/mgmt/tm/cm/traffic-group/{2}".format(
523 self.client.provider['server'],
524 self.client.provider['server_port'],
525 transform_name(self.want.partition, self.want.name)
526 )
527 resp = self.client.api.get(uri)
528 try:
529 response = resp.json()
530 except ValueError as ex:
531 raise F5ModuleError(str(ex))
532
533 if resp.status == 404 or 'code' in response and response['code'] == 404:
534 return False
535 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
536 return True
537
538 if resp.status in errors or 'code' in response and response['code'] in errors:
539 if 'message' in response:
540 raise F5ModuleError(response['message'])
541 else:
542 raise F5ModuleError(resp.content)
543
544 def create_on_device(self):
545 params = self.changes.api_params()
546 params['name'] = self.want.name
547 params['partition'] = self.want.partition
548 uri = "https://{0}:{1}/mgmt/tm/cm/traffic-group/".format(
549 self.client.provider['server'],
550 self.client.provider['server_port'],
551 )
552 resp = self.client.api.post(uri, json=params)
553 try:
554 response = resp.json()
555 except ValueError as ex:
556 raise F5ModuleError(str(ex))
557
558 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
559 return True
560 raise F5ModuleError(resp.content)
561
562 def update_on_device(self):
563 params = self.changes.api_params()
564 uri = "https://{0}:{1}/mgmt/tm/cm/traffic-group/{2}".format(
565 self.client.provider['server'],
566 self.client.provider['server_port'],
567 transform_name(self.want.partition, self.want.name)
568 )
569 resp = self.client.api.patch(uri, json=params)
570 try:
571 response = resp.json()
572 except ValueError as ex:
573 raise F5ModuleError(str(ex))
574
575 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
576 return True
577 raise F5ModuleError(resp.content)
578
579 def read_current_from_device(self):
580 uri = "https://{0}:{1}/mgmt/tm/cm/traffic-group/{2}".format(
581 self.client.provider['server'],
582 self.client.provider['server_port'],
583 transform_name(self.want.partition, self.want.name)
584 )
585
586 resp = self.client.api.get(uri)
587
588 try:
589 response = resp.json()
590 except ValueError as ex:
591 raise F5ModuleError(str(ex))
592
593 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
594 return ApiParameters(params=response)
595 raise F5ModuleError(resp.content)
596
597 def remove_from_device(self):
598 uri = "https://{0}:{1}/mgmt/tm/cm/traffic-group/{2}".format(
599 self.client.provider['server'],
600 self.client.provider['server_port'],
601 transform_name(self.want.partition, self.want.name)
602 )
603 response = self.client.api.delete(uri)
604 if response.status == 200:
605 return True
606 raise F5ModuleError(response.content)
607
608
609 class ArgumentSpec(object):
610 def __init__(self):
611 self.supports_check_mode = True
612 argument_spec = dict(
613 name=dict(required=True),
614 mac_address=dict(),
615 ha_order=dict(
616 type='list',
617 elements='str',
618 ),
619 ha_group=dict(),
620 ha_load_factor=dict(
621 type='int'
622 ),
623 auto_failback=dict(
624 type='bool',
625 ),
626 auto_failback_time=dict(
627 type='int'
628 ),
629 state=dict(
630 default='present',
631 choices=['absent', 'present']
632 ),
633 partition=dict(
634 default='Common',
635 fallback=(env_fallback, ['F5_PARTITION'])
636 ),
637
638 )
639 self.argument_spec = {}
640 self.argument_spec.update(f5_argument_spec)
641 self.argument_spec.update(argument_spec)
642
643
644 def main():
645 spec = ArgumentSpec()
646
647 module = AnsibleModule(
648 argument_spec=spec.argument_spec,
649 supports_check_mode=spec.supports_check_mode,
650 )
651
652 try:
653 mm = ModuleManager(module=module)
654 results = mm.exec_module()
655 module.exit_json(**results)
656 except F5ModuleError as ex:
657 module.fail_json(msg=str(ex))
658
659
660 if __name__ == '__main__':
661 main()