Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_device_connectivity.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_connectivity
13 short_description: Manages device IP configuration settings for HA on a BIG-IP.
14 description:
15 - Manages device IP configuration settings for High Availability (HA) on a BIG-IP. Each BIG-IP device
16 has synchronization and failover connectivity information (IP addresses) that
17 you define as part of HA pairing or clustering. This module allows you to configure
18 that information.
19 version_added: "1.0.0"
20 options:
21 config_sync_ip:
22 description:
23 - Local IP address the system uses for ConfigSync operations.
24 type: str
25 mirror_primary_address:
26 description:
27 - Specifies the primary IP address for the system to use to mirror
28 connections.
29 type: str
30 mirror_secondary_address:
31 description:
32 - Specifies the secondary IP address for the system to use to mirror
33 connections.
34 type: str
35 unicast_failover:
36 description:
37 - Addresses to use for failover operations. Options C(address)
38 and C(port) are supported with dictionary structure, where C(address) is the
39 local IP address the system uses for failover operations.
40 - Port specifies the port the system uses for failover operations. If C(port)
41 is not specified, the default value C(1026) will be used.
42 - If you are specifying the (recommended) management IP address, use 'management-ip' in
43 the address field.
44 - When the value is set to empty list, the parameter value is removed from device.
45 type: list
46 elements: dict
47 failover_multicast:
48 description:
49 - When C(true), ensures the Failover Multicast configuration is enabled
50 and, if no further multicast configuration is provided, ensures that
51 C(multicast_interface), C(multicast_address) and C(multicast_port) are
52 the defaults specified in the description of each option.
53 - When C(false), ensures that Failover Multicast configuration is disabled.
54 type: bool
55 multicast_interface:
56 description:
57 - Interface over which the system sends multicast messages associated
58 with failover.
59 - When C(failover_multicast) is C(true) and this option is not provided, a default of C(eth0) will be used.
60 type: str
61 multicast_address:
62 description:
63 - IP address for the system to send multicast messages associated with
64 failover.
65 - When C(failover_multicast) is C(true) and this option is not provided, a default of C(224.0.0.245) will be used.
66 type: str
67 multicast_port:
68 description:
69 - Port for the system to send multicast messages associated with
70 failover.
71 - When C(failover_multicast) is C(true) and this option is not provided, a default of C(62960) will be used.
72 This value must be between 0 and 65535.
73 type: int
74 cluster_mirroring:
75 description:
76 - Specifies whether mirroring occurs within the same cluster or between
77 different clusters on a multi-bladed system.
78 - This parameter is only supported on platforms that have multiple blades,
79 such as Viprion hardware. It is not supported on Virtual Editions (VEs).
80 type: str
81 choices:
82 - between-clusters
83 - within-cluster
84 notes:
85 - This module is primarily used as a component of configuring HA pairs of
86 BIG-IP devices.
87 - Requires BIG-IP >= 12.0.0
88 extends_documentation_fragment: f5networks.f5_modules.f5
89 author:
90 - Tim Rupp (@caphrim007)
91 - Wojciech Wypior (@wojtek0806)
92 '''
93
94 EXAMPLES = r'''
95 - name: Configure device connectivity for standard HA pair
96 bigip_device_connectivity:
97 config_sync_ip: 10.1.30.1
98 mirror_primary_address: 10.1.30.1
99 unicast_failover:
100 - address: management-ip
101 - address: 10.1.30.1
102 provider:
103 server: lb.mydomain.com
104 user: admin
105 password: secret
106 delegate_to: localhost
107 '''
108
109 RETURN = r'''
110 changed:
111 description: Denotes if the F5 configuration was updated.
112 returned: always
113 type: bool
114 config_sync_ip:
115 description: The new value of the C(config_sync_ip) setting.
116 returned: changed
117 type: str
118 sample: 10.1.1.1
119 mirror_primary_address:
120 description: The new value of the C(mirror_primary_address) setting.
121 returned: changed
122 type: str
123 sample: 10.1.1.2
124 mirror_secondary_address:
125 description: The new value of the C(mirror_secondary_address) setting.
126 returned: changed
127 type: str
128 sample: 10.1.1.3
129 unicast_failover:
130 description: The new value of the C(unicast_failover) setting.
131 returned: changed
132 type: list
133 sample: [{'address': '10.1.1.2', 'port': 1026}]
134 failover_multicast:
135 description: Whether a failover multicast attribute has been changed or not.
136 returned: changed
137 type: bool
138 multicast_interface:
139 description: The new value of the C(multicast_interface) setting.
140 returned: changed
141 type: str
142 sample: eth0
143 multicast_address:
144 description: The new value of the C(multicast_address) setting.
145 returned: changed
146 type: str
147 sample: 224.0.0.245
148 multicast_port:
149 description: The new value of the C(multicast_port) setting.
150 returned: changed
151 type: int
152 sample: 1026
153 cluster_mirroring:
154 description: The current cluster-mirroring setting.
155 returned: changed
156 type: str
157 sample: between-clusters
158 '''
159 from datetime import datetime
160 from ansible.module_utils.basic import AnsibleModule
161 from ansible.module_utils.six import iteritems
162
163 from ..module_utils.bigip import F5RestClient
164 from ..module_utils.common import (
165 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
166 )
167 from ..module_utils.ipaddress import is_valid_ip
168 from ..module_utils.icontrol import tmos_version
169 from ..module_utils.teem import send_teem
170
171
172 class Parameters(AnsibleF5Parameters):
173 api_map = {
174 'unicastAddress': 'unicast_failover',
175 'configsyncIp': 'config_sync_ip',
176 'multicastInterface': 'multicast_interface',
177 'multicastIp': 'multicast_address',
178 'multicastPort': 'multicast_port',
179 'mirrorIp': 'mirror_primary_address',
180 'mirrorSecondaryIp': 'mirror_secondary_address',
181 'managementIp': 'management_ip',
182 }
183 api_attributes = [
184 'configsyncIp',
185 'multicastInterface',
186 'multicastIp',
187 'multicastPort',
188 'mirrorIp',
189 'mirrorSecondaryIp',
190 'unicastAddress',
191 ]
192 returnables = [
193 'config_sync_ip',
194 'multicast_interface',
195 'multicast_address',
196 'multicast_port',
197 'mirror_primary_address',
198 'mirror_secondary_address',
199 'failover_multicast',
200 'unicast_failover',
201 'cluster_mirroring',
202 ]
203 updatables = [
204 'config_sync_ip',
205 'multicast_interface',
206 'multicast_address',
207 'multicast_port',
208 'mirror_primary_address',
209 'mirror_secondary_address',
210 'failover_multicast',
211 'unicast_failover',
212 'cluster_mirroring',
213 ]
214
215 @property
216 def multicast_port(self):
217 if self._values['multicast_port'] is None:
218 return None
219 result = int(self._values['multicast_port'])
220 if result < 0 or result > 65535:
221 raise F5ModuleError(
222 "The specified 'multicast_port' must be between 0 and 65535."
223 )
224 return result
225
226 @property
227 def multicast_address(self):
228 if self._values['multicast_address'] is None:
229 return None
230 elif self._values['multicast_address'] in ["none", "any6", '']:
231 return "any6"
232 elif self._values['multicast_address'] == 'any':
233 return 'any'
234 result = self._get_validated_ip_address('multicast_address')
235 return result
236
237 @property
238 def mirror_primary_address(self):
239 if self._values['mirror_primary_address'] is None:
240 return None
241 elif self._values['mirror_primary_address'] in ["none", "any6", '']:
242 return "any6"
243 result = self._get_validated_ip_address('mirror_primary_address')
244 return result
245
246 @property
247 def mirror_secondary_address(self):
248 if self._values['mirror_secondary_address'] is None:
249 return None
250 elif self._values['mirror_secondary_address'] in ["none", "any6", '']:
251 return "any6"
252 result = self._get_validated_ip_address('mirror_secondary_address')
253 return result
254
255 @property
256 def config_sync_ip(self):
257 if self._values['config_sync_ip'] is None:
258 return None
259 elif self._values['config_sync_ip'] in ["none", '']:
260 return "none"
261 result = self._get_validated_ip_address('config_sync_ip')
262 return result
263
264 def _validate_unicast_failover_port(self, port):
265 try:
266 result = int(port)
267 except ValueError:
268 raise F5ModuleError(
269 "The provided 'port' for unicast failover is not a valid number"
270 )
271 except TypeError:
272 result = 1026
273 return result
274
275 def _validate_unicast_failover_address(self, address):
276 if address != 'management-ip':
277 if is_valid_ip(address):
278 return address
279 else:
280 raise F5ModuleError(
281 "'address' field in unicast failover is not a valid IP address"
282 )
283 else:
284 return address
285
286 def _get_validated_ip_address(self, address):
287 if is_valid_ip(self._values[address]):
288 return self._values[address]
289 raise F5ModuleError(
290 "The specified '{0}' is not a valid IP address".format(address)
291 )
292
293
294 class ApiParameters(Parameters):
295 @property
296 def cluster_mirroring(self):
297 if self._values['cluster_mirroring'] is None:
298 return None
299 if self._values['cluster_mirroring'] == 'between':
300 return 'between-clusters'
301 return 'within-cluster'
302
303
304 class ModuleParameters(Parameters):
305 @property
306 def unicast_failover(self):
307 if self._values['unicast_failover'] is None:
308 return None
309 if not self._values['unicast_failover']:
310 return []
311 result = []
312 for item in self._values['unicast_failover']:
313 address = item.get('address', None)
314 port = item.get('port', None)
315 address = self._validate_unicast_failover_address(address)
316 port = self._validate_unicast_failover_port(port)
317 result.append(
318 dict(
319 effectiveIp=address,
320 effectivePort=port,
321 ip=address,
322 port=port
323 )
324 )
325 if result:
326 return result
327 else:
328 return None
329
330
331 class Changes(Parameters):
332 def to_return(self):
333 result = {}
334 try:
335 for returnable in self.returnables:
336 change = getattr(self, returnable)
337 if isinstance(change, dict):
338 result.update(change)
339 else:
340 result[returnable] = change
341 result = self._filter_params(result)
342 except Exception:
343 pass
344 return result
345
346
347 class ReportableChanges(Changes):
348 returnables = [
349 'config_sync_ip', 'multicast_interface', 'multicast_address',
350 'multicast_port', 'mirror_primary_address', 'mirror_secondary_address',
351 'failover_multicast', 'unicast_failover'
352 ]
353
354 @property
355 def mirror_secondary_address(self):
356 if self._values['mirror_secondary_address'] in ['none', 'any6']:
357 return 'none'
358 return self._values['mirror_secondary_address']
359
360 @property
361 def mirror_primary_address(self):
362 if self._values['mirror_primary_address'] in ['none', 'any6']:
363 return 'none'
364 return self._values['mirror_primary_address']
365
366 @property
367 def multicast_address(self):
368 if self._values['multicast_address'] in ['none', 'any6']:
369 return 'none'
370 return self._values['multicast_address']
371
372
373 class UsableChanges(Changes):
374 @property
375 def mirror_primary_address(self):
376 if self._values['mirror_primary_address'] == ['any6', 'none', 'any']:
377 return "any6"
378 else:
379 return self._values['mirror_primary_address']
380
381 @property
382 def mirror_secondary_address(self):
383 if self._values['mirror_secondary_address'] == ['any6', 'none', 'any']:
384 return "any6"
385 else:
386 return self._values['mirror_secondary_address']
387
388 @property
389 def multicast_address(self):
390 if self._values['multicast_address'] == ['any6', 'none', 'any']:
391 return "any"
392 else:
393 return self._values['multicast_address']
394
395 @property
396 def unicast_failover(self):
397 if self._values['unicast_failover'] is None:
398 return None
399 elif self._values['unicast_failover']:
400 return self._values['unicast_failover']
401 return "none"
402
403 @property
404 def cluster_mirroring(self):
405 if self._values['cluster_mirroring'] is None:
406 return None
407 elif self._values['cluster_mirroring'] == 'between-clusters':
408 return 'between'
409 return 'within'
410
411
412 class Difference(object):
413 def __init__(self, want, have=None):
414 self.want = want
415 self.have = have
416
417 def compare(self, param):
418 try:
419 result = getattr(self, param)
420 return result
421 except AttributeError:
422 return self.__default(param)
423
424 def __default(self, param):
425 attr1 = getattr(self.want, param)
426 try:
427 attr2 = getattr(self.have, param)
428 if attr1 != attr2:
429 return attr1
430 except AttributeError:
431 return attr1
432
433 def to_tuple(self, failovers):
434 result = []
435 for x in failovers:
436 for k, v in iteritems(x):
437 # Have to do this in cases where the BIG-IP stores the word
438 # "management-ip" when you specify the management IP address.
439 #
440 # Otherwise, a difference would be registered.
441 if v == self.have.management_ip:
442 v = 'management-ip'
443 result += [(str(k), str(v))]
444 return result
445
446 @property
447 def unicast_failover(self):
448 if self.want.unicast_failover == [] and self.have.unicast_failover is None:
449 return None
450 if self.want.unicast_failover is None:
451 return None
452 if self.have.unicast_failover is None:
453 return self.want.unicast_failover
454 want = self.to_tuple(self.want.unicast_failover)
455 have = self.to_tuple(self.have.unicast_failover)
456 if set(want) == set(have):
457 return None
458 else:
459 return self.want.unicast_failover
460
461 @property
462 def failover_multicast(self):
463 values = ['multicast_address', 'multicast_interface', 'multicast_port']
464 if self.want.failover_multicast is False:
465 if self.have.multicast_interface == 'eth0' and self.have.multicast_address == 'any' and self.have.multicast_port == 0:
466 return None
467 else:
468 result = dict(
469 failover_multicast=True,
470 multicast_port=0,
471 multicast_interface='eth0',
472 multicast_address='any'
473 )
474 return result
475 else:
476 if all(self.have._values[x] in [None, 'any6', 'any'] for x in values):
477 return True
478
479
480 class ModuleManager(object):
481 def __init__(self, *args, **kwargs):
482 self.module = kwargs.get('module', None)
483 self.client = F5RestClient(**self.module.params)
484 self.want = ModuleParameters(params=self.module.params)
485 self.have = ApiParameters()
486 self.changes = UsableChanges()
487
488 def _update_changed_options(self):
489 diff = Difference(self.want, self.have)
490 updatables = Parameters.updatables
491 changed = dict()
492 for k in updatables:
493 change = diff.compare(k)
494 if change is None:
495 continue
496 else:
497 if isinstance(change, dict):
498 changed.update(change)
499 else:
500 changed[k] = change
501 if changed:
502 self.changes = UsableChanges(params=changed)
503 return True
504 return False
505
506 def should_update(self):
507 start = datetime.now().isoformat()
508 version = tmos_version(self.client)
509 result = self._update_changed_options()
510 if result:
511 return True
512 return False
513
514 def exec_module(self):
515 start = datetime.now().isoformat()
516 version = tmos_version(self.client)
517 result = dict()
518
519 changed = self.update()
520
521 reportable = ReportableChanges(params=self.changes.to_return())
522 changes = reportable.to_return()
523 result.update(**changes)
524 result.update(dict(changed=changed))
525 send_teem(start, self.client, self.module, version)
526 return result
527
528 def update(self):
529 self.have = self.read_current_from_device()
530 if not self.should_update():
531 return False
532 if self.module.check_mode:
533 return True
534 self.update_on_device()
535 if self.changes.cluster_mirroring:
536 self.update_cluster_mirroring_on_device()
537 return True
538
539 def update_on_device(self):
540 params = self.changes.api_params()
541 if not params:
542 return
543 uri = "https://{0}:{1}/mgmt/tm/cm/device/".format(
544 self.client.provider['server'],
545 self.client.provider['server_port'],
546 )
547 resp = self.client.api.get(uri)
548 try:
549 response = resp.json()
550 except ValueError as ex:
551 raise F5ModuleError(str(ex))
552
553 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
554 raise F5ModuleError(resp.content)
555
556 for item in response['items']:
557 if item['selfDevice'] == 'true':
558 uri = "https://{0}:{1}/mgmt/tm/cm/device/{2}".format(
559 self.client.provider['server'],
560 self.client.provider['server_port'],
561 transform_name(item['partition'], item['name'])
562 )
563 resp = self.client.api.patch(uri, json=params)
564 try:
565 response = resp.json()
566 except ValueError as ex:
567 raise F5ModuleError(str(ex))
568
569 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
570 return True
571 raise F5ModuleError(resp.content)
572
573 raise F5ModuleError(
574 "The host device was not found."
575 )
576
577 def update_cluster_mirroring_on_device(self):
578 uri = "https://{0}:{1}/mgmt/tm/sys/db/{2}".format(
579 self.client.provider['server'],
580 self.client.provider['server_port'],
581 'statemirror.clustermirroring'
582 )
583 payload = {"value": self.changes.cluster_mirroring}
584 resp = self.client.api.patch(uri, json=payload)
585 try:
586 response = resp.json()
587 except ValueError as ex:
588 raise F5ModuleError(str(ex))
589
590 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
591 return True
592 raise F5ModuleError(resp.content)
593
594 def read_current_from_device(self):
595 db = self.read_cluster_mirroring_from_device()
596 uri = "https://{0}:{1}/mgmt/tm/cm/device/".format(
597 self.client.provider['server'],
598 self.client.provider['server_port'],
599 )
600 resp = self.client.api.get(uri)
601 try:
602 response = resp.json()
603 except ValueError as ex:
604 raise F5ModuleError(str(ex))
605
606 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
607 raise F5ModuleError(resp.content)
608
609 for item in response['items']:
610 if item['selfDevice'] == 'true':
611 uri = "https://{0}:{1}/mgmt/tm/cm/device/{2}".format(
612 self.client.provider['server'],
613 self.client.provider['server_port'],
614 transform_name(item['partition'], item['name'])
615 )
616 resp = self.client.api.get(uri)
617 try:
618 response = resp.json()
619 except ValueError as ex:
620 raise F5ModuleError(str(ex))
621
622 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
623 if db:
624 response['cluster_mirroring'] = db['value']
625 return ApiParameters(params=response)
626 raise F5ModuleError(resp.content)
627
628 raise F5ModuleError(
629 "The host device was not found."
630 )
631
632 def read_cluster_mirroring_from_device(self):
633 uri = "https://{0}:{1}/mgmt/tm/sys/db/{2}".format(
634 self.client.provider['server'],
635 self.client.provider['server_port'],
636 'statemirror.clustermirroring'
637 )
638 resp = self.client.api.get(uri)
639 try:
640 response = resp.json()
641 except ValueError as ex:
642 raise F5ModuleError(str(ex))
643
644 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
645 return response
646 raise F5ModuleError(resp.content)
647
648
649 class ArgumentSpec(object):
650 def __init__(self):
651 self.supports_check_mode = True
652 argument_spec = dict(
653 multicast_port=dict(
654 type='int'
655 ),
656 multicast_address=dict(),
657 multicast_interface=dict(),
658 failover_multicast=dict(
659 type='bool'
660 ),
661 unicast_failover=dict(
662 type='list',
663 elements='dict',
664 ),
665 mirror_primary_address=dict(),
666 mirror_secondary_address=dict(),
667 config_sync_ip=dict(),
668 cluster_mirroring=dict(
669 choices=['within-cluster', 'between-clusters']
670 )
671 )
672 self.argument_spec = {}
673 self.argument_spec.update(f5_argument_spec)
674 self.argument_spec.update(argument_spec)
675 self.required_together = [
676 ['multicast_address', 'multicast_interface', 'multicast_port']
677 ]
678
679
680 def main():
681 spec = ArgumentSpec()
682
683 module = AnsibleModule(
684 argument_spec=spec.argument_spec,
685 supports_check_mode=spec.supports_check_mode,
686 required_together=spec.required_together
687 )
688
689 try:
690 mm = ModuleManager(module=module)
691 results = mm.exec_module()
692 module.exit_json(**results)
693 except F5ModuleError as ex:
694 module.fail_json(msg=str(ex))
695
696
697 if __name__ == '__main__':
698 main()