Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_device_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_group
13 short_description: Manage device groups on a BIG-IP
14 description:
15 - Managing device groups allows you to create HA pairs and clusters
16 of BIG-IP devices. Usage of this module should be done in conjunction
17 with the C(bigip_configsync_actions) to sync the configuration across
18 the pair or cluster if auto-sync is disabled.
19 version_added: "1.0.0"
20 options:
21 name:
22 description:
23 - Specifies the name of the device group.
24 type: str
25 required: True
26 type:
27 description:
28 - Specifies the type of group.
29 - A C(sync-failover) device group contains devices that synchronize their
30 configuration data and fail over to one another when a device becomes
31 unavailable.
32 - A C(sync-only) device group has no such failover. When creating a new
33 device group, this option defaults to C(sync-only).
34 - This setting cannot be changed once it has been set.
35 type: str
36 choices:
37 - sync-failover
38 - sync-only
39 description:
40 description:
41 - Description of the device group.
42 type: str
43 auto_sync:
44 description:
45 - Indicates whether configuration synchronization occurs manually or
46 automatically.
47 - When creating a new device group, this option defaults to C(false).
48 type: bool
49 asm_sync:
50 description:
51 - Specifies whether to synchronize ASM configurations of device group members.
52 - A device can be a member of only one ASM-enabled device group.
53 - When creating a new device group, this option defaults to C(false).
54 type: bool
55 version_added: "1.22.0"
56 save_on_auto_sync:
57 description:
58 - When performing an auto-sync, specifies whether the configuration
59 is saved or not.
60 - When C(false), only the running configuration is changed on the
61 device(s) being synced to.
62 - When creating a new device group, this option defaults to C(false).
63 type: bool
64 full_sync:
65 description:
66 - Specifies whether the system synchronizes the entire configuration
67 during synchronization operations.
68 - When C(no), the system performs incremental synchronization operations,
69 based on the cache size specified in C(max_incremental_sync_size).
70 - Incremental configuration synchronization is a mechanism for synchronizing
71 a device-group's configuration among its members, without requiring a
72 full configuration load for each configuration change.
73 - In order for this to work, all devices in the device-group must initially
74 agree on the configuration. Typically this requires at least one full
75 configuration load to each device.
76 - When creating a new device group, this option defaults to C(false).
77 type: bool
78 max_incremental_sync_size:
79 description:
80 - Specifies the size of the changes cache for incremental sync.
81 - For example, using the default, if you make more than 1024 KB worth of
82 incremental changes, the system performs a full synchronization operation.
83 - Using incremental synchronization operations can reduce the per-device sync/load
84 time for configuration changes.
85 - This setting is relevant only when C(full_sync) is C(no).
86 type: int
87 state:
88 description:
89 - When C(state) is C(present), ensures the device group exists.
90 - When C(state) is C(absent), ensures the device group is removed.
91 type: str
92 choices:
93 - present
94 - absent
95 default: present
96 network_failover:
97 description:
98 - Indicates whether failover occurs over the network or is hard-wired.
99 - This parameter is only valid for C(type)s that are C(sync-failover).
100 type: bool
101 notes:
102 - This module is primarily used as a component of configuring HA pairs of
103 BIG-IP devices.
104 - Requires BIG-IP >= 12.1.x.
105 extends_documentation_fragment: f5networks.f5_modules.f5
106 author:
107 - Tim Rupp (@caphrim007)
108 - Wojciech Wypior (@wojtek0806)
109 '''
110
111 EXAMPLES = r'''
112 - name: Create a sync-only device group
113 bigip_device_group:
114 name: foo-group
115 provider:
116 password: secret
117 server: lb.mydomain.com
118 user: admin
119 delegate_to: localhost
120
121 - name: Create a sync-only device group with auto-sync enabled
122 bigip_device_group:
123 name: foo-group
124 auto_sync: true
125 provider:
126 password: secret
127 server: lb.mydomain.com
128 user: admin
129 delegate_to: localhost
130
131 - name: Create a sync-only device group with auto-sync and asm-sync enabled
132 bigip_device_group:
133 name: foo-group
134 auto_sync: true
135 asm_sync: true
136 provider:
137 password: secret
138 server: lb.mydomain.com
139 user: admin
140 delegate_to: localhost
141 '''
142
143 RETURN = r'''
144 save_on_auto_sync:
145 description: The new save_on_auto_sync value of the device group.
146 returned: changed
147 type: bool
148 sample: true
149 full_sync:
150 description: The new full_sync value of the device group.
151 returned: changed
152 type: bool
153 sample: false
154 description:
155 description: The new description of the device group.
156 returned: changed
157 type: str
158 sample: this is a device group
159 type:
160 description: The new type of the device group.
161 returned: changed
162 type: str
163 sample: sync-failover
164 auto_sync:
165 description: The new auto_sync value of the device group.
166 returned: changed
167 type: bool
168 sample: true
169 asm_sync:
170 description: The new asm_sync value of the device group.
171 returned: changed
172 type: bool
173 sample: true
174 max_incremental_sync_size:
175 description: The new sync size of the device group.
176 returned: changed
177 type: int
178 sample: 1000
179 network_failover:
180 description: Whether or not network failover is enabled.
181 returned: changed
182 type: bool
183 sample: true
184 '''
185 from datetime import datetime
186 from ansible.module_utils.basic import AnsibleModule
187
188 from ..module_utils.bigip import F5RestClient
189 from ..module_utils.common import (
190 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean
191 )
192 from ..module_utils.icontrol import tmos_version
193 from ..module_utils.teem import send_teem
194
195
196 class Parameters(AnsibleF5Parameters):
197 api_map = {
198 'saveOnAutoSync': 'save_on_auto_sync',
199 'fullLoadOnSync': 'full_sync',
200 'autoSync': 'auto_sync',
201 'asmSync': 'asm_sync',
202 'incrementalConfigSyncSizeMax': 'max_incremental_sync_size',
203 'networkFailover': 'network_failover',
204 }
205 api_attributes = [
206 'saveOnAutoSync',
207 'fullLoadOnSync',
208 'description',
209 'type',
210 'autoSync',
211 'asmSync',
212 'incrementalConfigSyncSizeMax',
213 'networkFailover',
214 ]
215 returnables = [
216 'save_on_auto_sync',
217 'full_sync',
218 'description',
219 'type',
220 'auto_sync',
221 'asm_sync',
222 'max_incremental_sync_size',
223 'network_failover',
224 ]
225 updatables = [
226 'save_on_auto_sync',
227 'full_sync',
228 'description',
229 'auto_sync',
230 'asm_sync',
231 'max_incremental_sync_size',
232 'network_failover',
233 ]
234
235 @property
236 def max_incremental_sync_size(self):
237 if not self.full_sync and self._values['max_incremental_sync_size'] is not None:
238 if self._values['__warnings'] is None:
239 self._values['__warnings'] = []
240 self._values['__warnings'].append(
241 [
242 dict(
243 msg='"max_incremental_sync_size has no effect if "full_sync" is not true',
244 version='2.4'
245 )
246 ]
247 )
248 if self._values['max_incremental_sync_size'] is None:
249 return None
250 return int(self._values['max_incremental_sync_size'])
251
252
253 class ApiParameters(Parameters):
254 pass
255
256
257 class ModuleParameters(Parameters):
258 @property
259 def asm_sync(self):
260 result = flatten_boolean(self._values['asm_sync'])
261 if result == 'yes':
262 return 'enabled'
263 if result == 'no':
264 return 'disabled'
265
266 @property
267 def network_failover(self):
268 result = flatten_boolean(self._values['network_failover'])
269 if result == 'yes':
270 return 'enabled'
271 if result == 'no':
272 return 'disabled'
273
274 @property
275 def auto_sync(self):
276 result = flatten_boolean(self._values['auto_sync'])
277 if result == 'yes':
278 return 'enabled'
279 if result == 'no':
280 return 'disabled'
281
282 @property
283 def save_on_auto_sync(self):
284 result = flatten_boolean(self._values['save_on_auto_sync'])
285 if result == 'yes':
286 return 'true'
287 if result == 'no':
288 return 'false'
289
290 @property
291 def full_sync(self):
292 result = flatten_boolean(self._values['full_sync'])
293 if result == 'yes':
294 return 'true'
295 if result == 'no':
296 return 'false'
297
298
299 class Changes(Parameters):
300 def to_return(self):
301 result = {}
302 try:
303 for returnable in self.returnables:
304 change = getattr(self, returnable)
305 if isinstance(change, dict):
306 result.update(change)
307 else:
308 result[returnable] = change
309 result = self._filter_params(result)
310 except Exception:
311 raise
312 return result
313
314
315 class UsableChanges(Changes):
316 pass
317
318
319 class ReportableChanges(Changes):
320 @property
321 def network_failover(self):
322 return flatten_boolean(self._values['network_failover'])
323
324 @property
325 def auto_sync(self):
326 return flatten_boolean(self._values['auto_sync'])
327
328 @property
329 def asm_sync(self):
330 return flatten_boolean(self._values['asm_sync'])
331
332 @property
333 def save_on_auto_sync(self):
334 return flatten_boolean(self._values['save_on_auto_sync'])
335
336 @property
337 def full_sync(self):
338 return flatten_boolean(self._values['full_sync'])
339
340
341 class ModuleManager(object):
342 def __init__(self, *args, **kwargs):
343 self.module = kwargs.get('module', None)
344 self.client = F5RestClient(**self.module.params)
345 self.want = ModuleParameters(params=self.module.params)
346 self.have = ApiParameters()
347 self.changes = UsableChanges()
348
349 def _set_changed_options(self):
350 changed = {}
351 for key in Parameters.returnables:
352 if getattr(self.want, key) is not None:
353 changed[key] = getattr(self.want, key)
354 if changed:
355 self.changes = UsableChanges(params=changed)
356
357 def _update_changed_options(self):
358 changed = {}
359 for key in Parameters.updatables:
360 if getattr(self.want, key) is not None:
361 attr1 = getattr(self.want, key)
362 attr2 = getattr(self.have, key)
363 if attr1 != attr2:
364 changed[key] = attr1
365 if changed:
366 self.changes = UsableChanges(params=changed)
367 return True
368 return False
369
370 def _announce_deprecations(self, result):
371 warnings = result.pop('__warnings', [])
372 for warning in warnings:
373 self.module.deprecate(
374 msg=warning['msg'],
375 version=warning['version']
376 )
377
378 def exec_module(self):
379 start = datetime.now().isoformat()
380 version = tmos_version(self.client)
381 changed = False
382 result = dict()
383 state = self.want.state
384
385 if state == "present":
386 changed = self.present()
387 elif state == "absent":
388 changed = self.absent()
389
390 reportable = ReportableChanges(params=self.changes.to_return())
391 changes = reportable.to_return()
392 result.update(**changes)
393 result.update(dict(changed=changed))
394 self._announce_deprecations(result)
395 send_teem(start, self.client, self.module, version)
396 return result
397
398 def present(self):
399 if self.exists():
400 return self.update()
401 else:
402 return self.create()
403
404 def should_update(self):
405 result = self._update_changed_options()
406 if result:
407 return True
408 return False
409
410 def update(self):
411 self.have = self.read_current_from_device()
412 if not self.should_update():
413 return False
414 if self.module.check_mode:
415 return True
416 self.update_on_device()
417 return True
418
419 def remove(self):
420 if self.module.check_mode:
421 return True
422 self.remove_members_in_group_from_device()
423 self.remove_from_device()
424 if self.exists():
425 raise F5ModuleError("Failed to delete the device group")
426 return True
427
428 def create(self):
429 self._set_changed_options()
430 if self.want.type == 'sync-only' and self.want.network_failover is not None:
431 raise F5ModuleError(
432 "'network_failover' may only be specified when 'type' is 'sync-failover'."
433 )
434 if self.module.check_mode:
435 return True
436 self.create_on_device()
437 return True
438
439 def absent(self):
440 if self.exists():
441 return self.remove()
442 return False
443
444 def exists(self):
445 errors = [401, 403, 409, 500, 501, 502, 503, 504]
446 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}".format(
447 self.client.provider['server'],
448 self.client.provider['server_port'],
449 self.want.name
450 )
451 resp = self.client.api.get(uri)
452 try:
453 response = resp.json()
454 except ValueError as ex:
455 raise F5ModuleError(str(ex))
456
457 if resp.status == 404 or 'code' in response and response['code'] == 404:
458 return False
459 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
460 return True
461
462 if resp.status in errors or 'code' in response and response['code'] in errors:
463 if 'message' in response:
464 raise F5ModuleError(response['message'])
465 else:
466 raise F5ModuleError(resp.content)
467
468 def remove_members_in_group_from_device(self):
469 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}/devices/".format(
470 self.client.provider['server'],
471 self.client.provider['server_port'],
472 self.want.name
473 )
474 resp = self.client.api.get(uri)
475 try:
476 response = resp.json()
477 except ValueError as ex:
478 raise F5ModuleError(str(ex))
479
480 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
481 raise F5ModuleError(resp.content)
482
483 for item in response['items']:
484 new_uri = uri + '{0}'.format(item['name'])
485 response = self.client.api.delete(new_uri)
486 if response.status == 200:
487 return True
488 raise F5ModuleError(response.content)
489
490 def _set_create_defaults(self, params):
491 if self.want.auto_sync is None:
492 params['autoSync'] = 'disabled'
493 if self.want.full_sync is None:
494 params['fullLoadOnSync'] = 'false'
495 if self.want.save_on_auto_sync is None:
496 params['saveOnAutoSync'] = 'false'
497 if self.want.asm_sync is None:
498 params['asmSync'] = 'disabled'
499
500 params['name'] = self.want.name
501 params['partition'] = self.want.partition
502 return params
503
504 def create_on_device(self):
505 params = self._set_create_defaults(self.changes.api_params())
506
507 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/".format(
508 self.client.provider['server'],
509 self.client.provider['server_port'],
510 )
511 resp = self.client.api.post(uri, json=params)
512 try:
513 response = resp.json()
514 except ValueError as ex:
515 raise F5ModuleError(str(ex))
516
517 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
518 return True
519 raise F5ModuleError(resp.content)
520
521 def update_on_device(self):
522 params = self.changes.api_params()
523 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}".format(
524 self.client.provider['server'],
525 self.client.provider['server_port'],
526 self.want.name
527 )
528 resp = self.client.api.patch(uri, json=params)
529 try:
530 response = resp.json()
531 except ValueError as ex:
532 raise F5ModuleError(str(ex))
533
534 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
535 return True
536 raise F5ModuleError(resp.content)
537
538 def remove_from_device(self):
539 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}".format(
540 self.client.provider['server'],
541 self.client.provider['server_port'],
542 self.want.name
543 )
544 response = self.client.api.delete(uri)
545 if response.status == 200:
546 return True
547 raise F5ModuleError(response.content)
548
549 def read_current_from_device(self):
550 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}".format(
551 self.client.provider['server'],
552 self.client.provider['server_port'],
553 self.want.name
554 )
555 resp = self.client.api.get(uri)
556 try:
557 response = resp.json()
558 except ValueError as ex:
559 raise F5ModuleError(str(ex))
560
561 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
562 return ApiParameters(params=response)
563 raise F5ModuleError(resp.content)
564
565
566 class ArgumentSpec(object):
567 def __init__(self):
568 self.supports_check_mode = True
569 argument_spec = dict(
570 type=dict(
571 choices=['sync-failover', 'sync-only']
572 ),
573 description=dict(),
574 auto_sync=dict(
575 type='bool'
576 ),
577 asm_sync=dict(
578 type='bool'
579 ),
580 save_on_auto_sync=dict(
581 type='bool',
582 ),
583 full_sync=dict(
584 type='bool'
585 ),
586 name=dict(
587 required=True
588 ),
589 max_incremental_sync_size=dict(
590 type='int'
591 ),
592 state=dict(
593 default='present',
594 choices=['absent', 'present']
595 ),
596 network_failover=dict(type='bool'),
597 )
598 self.argument_spec = {}
599 self.argument_spec.update(f5_argument_spec)
600 self.argument_spec.update(argument_spec)
601
602
603 def main():
604 spec = ArgumentSpec()
605
606 module = AnsibleModule(
607 argument_spec=spec.argument_spec,
608 supports_check_mode=spec.supports_check_mode
609 )
610
611 try:
612 mm = ModuleManager(module=module)
613 results = mm.exec_module()
614 module.exit_json(**results)
615 except F5ModuleError as ex:
616 module.fail_json(msg=str(ex))
617
618
619 if __name__ == '__main__':
620 main()