Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_ucs.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_ucs
13 short_description: Manage upload, installation, and removal of UCS files
14 description:
15 - Manage the upload, installation, and removal of UCS files on a BIG-IP system.
16 A user configuration set (UCS) is a backup file that contains BIG-IP configuration
17 data that can be used to fully restore a BIG-IP system in the event of a
18 failure or RMA replacement.
19 version_added: "1.0.0"
20 options:
21 include_chassis_level_config:
22 description:
23 - During restoration of the UCS file, includes chassis level configuration
24 that is shared among boot volume sets. For example, the cluster default
25 configuration.
26 type: bool
27 ucs:
28 description:
29 - The path to the UCS file to install. The parameter must be
30 provided if the C(state) is either C(installed) or C(activated).
31 When C(state) is C(absent), the full path for this parameter is
32 ignored and only the filename is used to select a UCS for removal.
33 Therefore you could specify C(/foo/bar/test.ucs) and this module
34 would only look for C(test.ucs).
35 type: str
36 required: True
37 force:
38 description:
39 - If C(true), the system uploads the file every time and replaces the file on the
40 device. If C(false), the file is only uploaded if it does not already
41 exist. Generally should only be C(true) in cases where you believe
42 the image was corrupted during upload.
43 type: bool
44 default: false
45 no_license:
46 description:
47 - Performs a full restore of the UCS file and all the files it contains,
48 with the exception of the license file. The option must be used to
49 restore a UCS on RMA (Returned Materials Authorization) devices.
50 type: bool
51 no_platform_check:
52 description:
53 - Bypasses the platform check and allows installation of a UCS that was
54 created using a different platform. By default (without this option),
55 installation of a UCS created from a different platform is not allowed.
56 type: bool
57 passphrase:
58 description:
59 - Specifies the passphrase that is necessary to load the specified UCS file.
60 type: str
61 reset_trust:
62 description:
63 - When specified, the device and trust domain certs and keys are not
64 loaded from the UCS. Instead, a new set is generated.
65 type: bool
66 state:
67 description:
68 - When C(installed), ensures the UCS is uploaded and installed
69 on the system. When C(present), ensures the UCS is uploaded.
70 When C(absent), the UCS is removed from the system. When
71 C(installed), the uploading of the UCS is idempotent, however the
72 installation of that configuration is not idempotent.
73 type: str
74 choices:
75 - absent
76 - installed
77 - present
78 default: present
79 notes:
80 - Only the most basic checks are performed by this module. Other checks and
81 considerations need to be taken into account. See
82 https://support.f5.com/kb/en-us/solutions/public/11000/300/sol11318.html
83 - This module does not handle devices with the FIPS 140 HSM.
84 - This module does not handle BIG-IPs systems on the 6400, 6800, 8400, or
85 8800 hardware platforms.
86 - This module does not verify the new or replaced SSH keys from the
87 UCS file are synchronized between the BIG-IP system and the SCCP.
88 - This module does not support the 'rma' option.
89 - This module does not support restoring a UCS archive on a BIG-IP 1500,
90 3400, 4100, 6400, 6800, or 8400 hardware platforms other than the system
91 from which the backup was created.
92 - The UCS restore operation restores the full configuration only if the
93 hostname of the target system matches the hostname on which the UCS
94 archive was created. If the hostname does not match, only the shared
95 configuration is restored. You can ensure hostnames match by using
96 the C(bigip_hostname) Ansible module in a task before using this module.
97 - This module does not support re-licensing a BIG-IP restored from a UCS.
98 - This module does not support restoring encrypted archives on replacement
99 RMA unit.
100 extends_documentation_fragment: f5networks.f5_modules.f5
101 author:
102 - Tim Rupp (@caphrim007)
103 - Wojciech Wypior (@wojtek0806)
104 '''
105
106 EXAMPLES = r'''
107 - name: Upload UCS
108 bigip_ucs:
109 ucs: /root/bigip.localhost.localdomain.ucs
110 state: present
111 provider:
112 server: lb.mydomain.com
113 user: admin
114 password: secret
115 delegate_to: localhost
116
117 - name: Install (upload, install) UCS.
118 bigip_ucs:
119 ucs: /root/bigip.localhost.localdomain.ucs
120 state: installed
121 provider:
122 server: lb.mydomain.com
123 user: admin
124 password: secret
125 delegate_to: localhost
126
127 - name: Install (upload, install) UCS without installing the license portion
128 bigip_ucs:
129 ucs: /root/bigip.localhost.localdomain.ucs
130 state: installed
131 no_license: true
132 provider:
133 server: lb.mydomain.com
134 user: admin
135 password: secret
136 delegate_to: localhost
137
138 - name: Install (upload, install) UCS except the license, and bypassing the platform check
139 bigip_ucs:
140 ucs: /root/bigip.localhost.localdomain.ucs
141 state: installed
142 no_license: true
143 no_platform_check: true
144 provider:
145 server: lb.mydomain.com
146 user: admin
147 password: secret
148 delegate_to: localhost
149
150 - name: Install (upload, install) UCS using a passphrase necessary to load the UCS
151 bigip_ucs:
152 ucs: /root/bigip.localhost.localdomain.ucs
153 state: installed
154 passphrase: MyPassphrase1234
155 provider:
156 server: lb.mydomain.com
157 user: admin
158 password: secret
159 delegate_to: localhost
160
161 - name: Remove uploaded UCS file
162 bigip_ucs:
163 ucs: bigip.localhost.localdomain.ucs
164 state: absent
165 provider:
166 server: lb.mydomain.com
167 user: admin
168 password: secret
169 delegate_to: localhost
170 '''
171
172 RETURN = r'''
173 # only common fields returned
174 '''
175
176 import os
177 import re
178 import time
179 import traceback
180 from datetime import datetime
181
182 try:
183 from packaging.version import Version
184 except ImportError:
185 HAS_PACKAGING = False
186 Version = None
187 PACKAGING_IMPORT_ERROR = traceback.format_exc()
188 else:
189 HAS_PACKAGING = True
190 PACKAGING_IMPORT_ERROR = None
191
192 from ansible.module_utils.basic import (
193 AnsibleModule, missing_required_lib
194 )
195 from ansible.module_utils.six import iteritems
196
197 from ..module_utils.bigip import F5RestClient
198 from ..module_utils.common import (
199 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
200 )
201 from ..module_utils.icontrol import (
202 upload_file, tmos_version
203 )
204 from ..module_utils.teem import send_teem
205
206 try:
207 from collections import OrderedDict
208 except ImportError:
209 try:
210 from ordereddict import OrderedDict
211 except ImportError:
212 pass
213
214
215 class Parameters(AnsibleF5Parameters):
216 api_map = {}
217 updatables = []
218 returnables = []
219 api_attributes = []
220
221
222 class ApiParameters(Parameters):
223 pass
224
225
226 class ModuleParameters(Parameters):
227 def _check_required_if(self, parameter):
228 if self._values[parameter] is not True:
229 return self._values[parameter]
230 if self.state != 'installed':
231 raise F5ModuleError(
232 '"{0}" parameters requires "installed" state'.format(parameter)
233 )
234
235 @property
236 def basename(self):
237 return os.path.basename(self.ucs)
238
239 @property
240 def options(self):
241 return {
242 'include-chassis-level-config': self.include_chassis_level_config,
243 'no-license': self.no_license,
244 'no-platform-check': self.no_platform_check,
245 'passphrase': self.passphrase,
246 'reset-trust': self.reset_trust
247 }
248
249 @property
250 def reset_trust(self):
251 self._check_required_if('reset_trust')
252 return self._values['reset_trust']
253
254 @property
255 def passphrase(self):
256 self._check_required_if('passphrase')
257 return self._values['passphrase']
258
259 @property
260 def no_platform_check(self):
261 self._check_required_if('no_platform_check')
262 return self._values['no_platform_check']
263
264 @property
265 def no_license(self):
266 self._check_required_if('no_license')
267 return self._values['no_license']
268
269 @property
270 def include_chassis_level_config(self):
271 self._check_required_if('include_chassis_level_config')
272 return self._values['include_chassis_level_config']
273
274 @property
275 def install_command(self):
276 cmd = 'tmsh load sys ucs /var/local/ucs/{0}'.format(self.basename)
277 # Append any options that might be specified
278 options = OrderedDict(sorted(self.options.items(), key=lambda t: t[0]))
279 for k, v in iteritems(options):
280 if v is False or v is None:
281 continue
282 elif k == 'passphrase':
283 cmd += ' %s %s' % (k, v)
284 else:
285 cmd += ' %s' % (k)
286 return cmd
287
288
289 class Changes(Parameters):
290 def to_return(self):
291 result = {}
292 try:
293 for returnable in self.returnables:
294 result[returnable] = getattr(self, returnable)
295 result = self._filter_params(result)
296 except Exception:
297 pass
298 return result
299
300
301 class ReportableChanges(Changes):
302 pass
303
304
305 class UsableChanges(Changes):
306 pass
307
308
309 class ModuleManager(object):
310 def __init__(self, *args, **kwargs):
311 self.kwargs = kwargs
312 self.module = kwargs.get('module', None)
313 self.client = F5RestClient(**self.module.params)
314
315 def exec_module(self):
316 if self.is_version_v1():
317 manager = V1Manager(**self.kwargs)
318 else:
319 manager = V2Manager(**self.kwargs)
320
321 return manager.exec_module()
322
323 def is_version_v1(self):
324 """Checks to see if the TMOS version is less than 12.1.0
325
326 Versions prior to 12.1.0 have a bug which prevents the REST
327 API from properly listing any UCS files when you query the
328 /mgmt/tm/sys/ucs endpoint. Therefore you need to do everything
329 through tmsh over REST.
330
331 :return: Bool
332 """
333 version = tmos_version(self.client)
334 if Version(version) < Version('12.1.0'):
335 return True
336 else:
337 return False
338
339
340 class Difference(object):
341 pass
342
343
344 class BaseManager(object):
345 def __init__(self, *args, **kwargs):
346 self.module = kwargs.get('module', None)
347 self.client = F5RestClient(**self.module.params)
348 self.want = ModuleParameters(params=self.module.params)
349 self.changes = UsableChanges()
350
351 def _announce_deprecations(self, result):
352 warnings = result.pop('__warnings', [])
353 for warning in warnings:
354 self.client.module.deprecate(
355 msg=warning['msg'],
356 version=warning['version']
357 )
358
359 def exec_module(self):
360 start = datetime.now().isoformat()
361 version = tmos_version(self.client)
362 changed = False
363 result = dict()
364 state = self.want.state
365
366 if state in ['present', 'installed']:
367 changed = self.present()
368 elif state == "absent":
369 changed = self.absent()
370
371 reportable = ReportableChanges(params=self.changes.to_return())
372 changes = reportable.to_return()
373 result.update(**changes)
374 result.update(dict(changed=changed))
375 self._announce_deprecations(result)
376 send_teem(start, self.client, self.module, version)
377 return result
378
379 def present(self):
380 if self.exists():
381 return self.update()
382 else:
383 return self.create()
384
385 def update(self):
386 if self.module.check_mode:
387 if self.want.force:
388 return True
389 return False
390 elif self.want.force:
391 self.remove()
392 return self.create()
393 elif self.want.state == 'installed':
394 return self.install_on_device()
395 else:
396 return False
397
398 def create(self):
399 if self.module.check_mode:
400 return True
401 self.create_on_device()
402 if not self.exists():
403 raise F5ModuleError("Failed to upload the UCS file")
404 if self.want.state == 'installed':
405 self.install_on_device()
406 return True
407
408 def absent(self):
409 if self.exists():
410 return self.remove()
411 return False
412
413 def should_update(self):
414 result = self._update_changed_options()
415 if result:
416 return True
417 return False
418
419 def remove(self):
420 if self.module.check_mode:
421 return True
422 self.remove_from_device()
423 if self.exists():
424 raise F5ModuleError("Failed to delete the UCS file")
425 return True
426
427 def wait_for_rest_api_restart(self):
428 time.sleep(5)
429 for x in range(0, 60):
430 try:
431 self.client.reconnect()
432 break
433 except Exception:
434 time.sleep(3)
435
436 def wait_for_configuration_reload(self):
437 noops = 0
438 while noops < 4:
439 time.sleep(3)
440 try:
441 params = dict(command="run",
442 utilCmdArgs='-c "tmsh show sys mcp-state"'
443 )
444 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
445 self.client.provider['server'],
446 self.client.provider['server_port']
447 )
448 resp = self.client.api.post(uri, json=params)
449 try:
450 output = resp.json()
451 except ValueError as ex:
452 raise F5ModuleError(str(ex))
453 if 'code' in output and output['code'] in [400, 403]:
454 if 'message' in output:
455 raise F5ModuleError(output['message'])
456 else:
457 raise F5ModuleError(resp.content)
458 except Exception:
459 # This can be caused by restjavad restarting.
460 continue
461
462 if 'commandResult' not in output:
463 continue
464
465 # Need to re-connect here because the REST framework will be restarting
466 # and thus be clearing its authorization cache
467 result = output['commandResult']
468 if self._is_config_reloading_failed_on_device(result):
469 raise F5ModuleError(
470 "Failed to reload the configuration. This may be due "
471 "to a cross-version incompatibility. {0}".format(result)
472 )
473 if self._is_config_reloading_success_on_device(result):
474 if self._is_config_reloading_running_on_device(result):
475 noops += 1
476 continue
477 noops = 0
478
479 def _is_config_reloading_success_on_device(self, output):
480 succeed = r'Last Configuration Load Status\s+full-config-load-succeed'
481 matches = re.search(succeed, output)
482 if matches:
483 return True
484 return False
485
486 def _is_config_reloading_running_on_device(self, output):
487 running = r'Running Phase\s+running'
488 matches = re.search(running, output)
489 if matches:
490 return True
491 return False
492
493 def _is_config_reloading_failed_on_device(self, output):
494 failed = r'Last Configuration Load Status\s+base-config-load-failed'
495 matches = re.search(failed, output)
496 if matches:
497 return True
498 return False
499
500
501 class V1Manager(BaseManager):
502 """Manager class for V1 product
503
504 V1 products include versions of BIG-IP < 12.1.0, but >= 12.0.0.
505
506 These versions had a number of API deficiencies. These include, but
507 are not limited to,
508
509 * UCS collection endpoint listed no items
510 * No API to upload UCS files
511
512 """
513
514 def _set_mode_and_ownership(self):
515 url = 'https://{0}:{1}/mgmt/tm/util/bash'.format(
516 self.client.provider['server'],
517 self.client.provider['server_port']
518 )
519 ownership = 'root:root'
520 ucs_path = '/var/local/ucs/{0}'.format(self.want.basename)
521 file_mode = oct(os.stat(self.want.ucs).st_mode)[-3:]
522 args = dict(
523 command='run',
524 utilCmdArgs='-c "chown {0} {1};chmod {2} {1}"'.format(ownership, ucs_path, file_mode)
525 )
526
527 self.client.api.post(url, json=args)
528
529 def upload_file_to_device(self, content, name):
530 url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format(
531 self.client.provider['server'],
532 self.client.provider['server_port']
533 )
534 try:
535 upload_file(self.client, url, content, name)
536 except F5ModuleError:
537 raise F5ModuleError(
538 "Failed to upload the file."
539 )
540
541 def create_on_device(self):
542 remote_path = "/var/local/ucs"
543 tpath_name = '/var/config/rest/downloads'
544
545 self.upload_file_to_device(self.want.ucs, self.want.basename)
546
547 uri = "https://{0}:{1}/mgmt/tm/util/unix-mv/".format(
548 self.client.provider['server'],
549 self.client.provider['server_port'],
550 )
551 args = dict(
552 command='run',
553 utilCmdArgs='{0}/{2} {1}/{2}'.format(
554 tpath_name, remote_path, self.want.basename
555 )
556 )
557 resp = self.client.api.post(uri, json=args)
558 try:
559 response = resp.json()
560 except ValueError as ex:
561 raise F5ModuleError(str(ex))
562 if 'code' in response and response['code'] == 400:
563 if 'message' in response:
564 raise F5ModuleError(response['message'])
565 else:
566 raise F5ModuleError(resp.content)
567
568 self._set_mode_and_ownership()
569 return True
570
571 def read_current_from_device(self):
572 result = []
573 params = dict(command="run",
574 utilCmdArgs='-c "tmsh list sys ucs"'
575 )
576 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
577 self.client.provider['server'],
578 self.client.provider['server_port']
579 )
580 resp = self.client.api.post(uri, json=params)
581 try:
582 output = resp.json()
583 except ValueError as ex:
584 raise F5ModuleError(str(ex))
585 if 'code' in output and output['code'] in [400, 403]:
586 if 'message' in output:
587 raise F5ModuleError(output['message'])
588 else:
589 raise F5ModuleError(resp.content)
590 if 'commandResult' in output:
591 lines = output['commandResult'].split("\n")
592 result = [x.strip() for x in lines]
593 result = list(set(result))
594 return result
595
596 def exists(self):
597 collection = self.read_current_from_device()
598 if self.want.basename in collection:
599 return True
600 return False
601
602 def remove_from_device(self):
603 params = dict(command="run",
604 utilCmdArgs='-c "tmsh delete sys ucs {0}"'.format(self.want.basename)
605 )
606 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
607 self.client.provider['server'],
608 self.client.provider['server_port']
609 )
610 resp = self.client.api.post(uri, json=params)
611 try:
612 output = resp.json()
613 except ValueError as ex:
614 raise F5ModuleError(str(ex))
615 if 'code' in output and output['code'] in [400, 403]:
616 if 'message' in output:
617 raise F5ModuleError(output['message'])
618 else:
619 raise F5ModuleError(resp.content)
620 if 'commandResult' in output:
621 if '{0} is deleted'.format(self.want.basename) in output['commandResult']:
622 return True
623 return False
624
625 def install_on_device(self):
626 try:
627 params = dict(command="run",
628 utilCmdArgs='-c "{0}"'.format(self.want.install_command)
629 )
630 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
631 self.client.provider['server'],
632 self.client.provider['server_port']
633 )
634 resp = self.client.api.post(uri, json=params)
635 try:
636 output = resp.json()
637 except ValueError as ex:
638 raise F5ModuleError(str(ex))
639 if 'code' in output and output['code'] in [400, 403]:
640 if 'message' in output:
641 raise F5ModuleError(output['message'])
642 else:
643 raise F5ModuleError(resp.content)
644 except Exception as ex:
645 # Reloading a UCS configuration will cause restjavad to restart,
646 # aborting the connection.
647 if 'Connection aborted' in str(ex):
648 pass
649 elif 'TimeoutException' in str(ex):
650 # Timeouts appear to be able to happen in 12.1.2
651 pass
652 elif 'remoteSender' in str(ex):
653 # catching some edge cases where API becomes unstable after installation
654 pass
655 elif 'Proxy Error' in str(ex):
656 # catching some edge cases where API becomes unstable after installation
657 pass
658 elif 'object has no attribute' in str(ex):
659 pass
660 elif 'Expecting value' in str(ex):
661 pass
662 else:
663 raise F5ModuleError(str(ex))
664 self.wait_for_rest_api_restart()
665 self.wait_for_configuration_reload()
666 return True
667
668
669 class V2Manager(V1Manager):
670 """Manager class for V2 product
671
672 V2 products include versions of BIG-IP >= 12.1.0 but < 13.0.0.
673
674 These versions fixed the collection bug in V1, but had yet to add the
675 ability to upload files using a dedicated UCS upload API.
676
677 """
678
679 def read_current_from_device(self):
680 result = []
681 uri = "https://{0}:{1}/mgmt/tm/sys/ucs/".format(
682 self.client.provider['server'],
683 self.client.provider['server_port'],
684 )
685 resp = self.client.api.get(uri)
686 try:
687 response = resp.json()
688 except ValueError as ex:
689 raise F5ModuleError(str(ex))
690
691 if 'code' in response and response['code'] == 400:
692 if 'message' in response:
693 raise F5ModuleError(response['message'])
694 else:
695 raise F5ModuleError(resp.content)
696 items = response.get('items', [])
697 for item in items:
698 result.append(os.path.basename(item['apiRawValues']['filename']))
699 return result
700
701 def exists(self):
702 collection = self.read_current_from_device()
703 if self.want.basename in collection:
704 return True
705 return False
706
707
708 class ArgumentSpec(object):
709 def __init__(self):
710 self.supports_check_mode = True
711 argument_spec = dict(
712 force=dict(
713 type='bool',
714 default='no'
715 ),
716 include_chassis_level_config=dict(
717 type='bool'
718 ),
719 no_license=dict(
720 type='bool'
721 ),
722 no_platform_check=dict(
723 type='bool'
724 ),
725 passphrase=dict(no_log=True),
726 reset_trust=dict(type='bool'),
727 state=dict(
728 default='present',
729 choices=['absent', 'installed', 'present']
730 ),
731 ucs=dict(required=True)
732 )
733 self.argument_spec = {}
734 self.argument_spec.update(f5_argument_spec)
735 self.argument_spec.update(argument_spec)
736
737
738 def main():
739 spec = ArgumentSpec()
740
741 module = AnsibleModule(
742 argument_spec=spec.argument_spec,
743 supports_check_mode=spec.supports_check_mode
744 )
745
746 if not HAS_PACKAGING:
747 module.fail_json(
748 msg=missing_required_lib('packaging'),
749 exception=PACKAGING_IMPORT_ERROR
750 )
751
752 try:
753 mm = ModuleManager(module=module)
754 results = mm.exec_module()
755 module.exit_json(**results)
756 except F5ModuleError as ex:
757 module.fail_json(msg=str(ex))
758
759
760 if __name__ == '__main__':
761 main()