Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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: bigiq_device_discovery
13 short_description: Manage BIG-IP devices through BIG-IQ
14 description:
15 - Discovers and imports BIG-IP device configuration on the BIG-IQ.
16 version_added: "1.0.0"
17 options:
18 device_address:
19 description:
20 - The IP address of the BIG-IP device to be imported/managed.
21 - For this module, C(provider) block should point to C(BIG-IQ) credentials
22 type: str
23 required: True
24 device_username:
25 description:
26 - The administrator username for the BIG-IP device.
27 - This parameter is only required when adding a new BIG-IP device to be managed.
28 type: str
29 device_password:
30 description:
31 - The administrator password for the BIG-IP device.
32 - This parameter is only required when adding a new BIG-IP device to be managed.
33 type: str
34 device_port:
35 description:
36 - The port on which a device trust setup between BIG-IQ and BIG-IP should happen.
37 type: int
38 default: 443
39 ha_name:
40 description:
41 - DSC cluster name of the BIG-IP device to be managed.
42 - This is optional if the managed device is not a part of a cluster group.
43 - When C(use_bigiq_sync) is set to C(true), this parameter is required.
44 type: str
45 use_bigiq_sync:
46 description:
47 - When set to C(false), initiate BIG-IP DSC sync when deploying configuration changes.
48 - When set to C(true), ignore BIG-IP DSC sync when deploying configuration changes.
49 type: bool
50 default: false
51 conflict_policy:
52 description:
53 - Sets the conflict resolution policy for shared objects across BIG-IP devices, except LTM profiles and monitors.
54 type: str
55 choices:
56 - use_bigiq
57 - use_bigip
58 default: use_bigiq
59 versioned_conflict_policy:
60 description:
61 - Sets the conflict resolution policy for LTM profile and monitor objects that are specific to a BIG-IP software
62 version.
63 type: str
64 choices:
65 - use_bigiq
66 - use_bigip
67 - keep_version
68 device_conflict_policy:
69 description:
70 - Sets the conflict resolution policy for objects that are specific to a particular to a BIG-IP device
71 and not shared among BIG-IP devices.
72 type: str
73 choices:
74 - use_bigiq
75 - use_bigip
76 default: use_bigiq
77 access_conflict_policy:
78 description:
79 - Sets the conflict resolution policy for Access module C(apm) objects. Only used when the C(apm) module is specified.
80 type: str
81 choices:
82 - use_bigiq
83 - use_bigip
84 - keep_version
85 access_group_name:
86 description:
87 - Access group name to import Access configuration for devices. Once set it cannot be changed.
88 type: str
89 access_group_first_device:
90 description:
91 - Specifies if the imported device is the first device in the access group to import shared configuration for that
92 access group.
93 type: bool
94 default: true
95 force:
96 description:
97 - Forces rediscovery and import of existing modules on the managed BIG-IP.
98 type: bool
99 default: false
100 modules:
101 description:
102 - List of modules to be discovered and imported into the device.
103 - These modules must be provisioned on the target device, otherwise operation will fail.
104 - The C(ltm) module must always be specified when performing discovery or re-discovery of the the device.
105 - When C(asm) or C(afm) are specified, the C(shared_security) module also needs to be declared.
106 type: list
107 elements: str
108 choices:
109 - ltm
110 - asm
111 - apm
112 - afm
113 - dns
114 - websafe
115 - security_shared
116 statistics:
117 description:
118 - Specify the statistics collection for discovered device.
119 type: dict
120 suboptions:
121 enable:
122 description:
123 - Enables statistics collection on a device.
124 type: bool
125 default: false
126 interval:
127 description:
128 - Specifies the interval the data is collected from the discovered device, in seconds.
129 type: int
130 default: 60
131 choices:
132 - 30
133 - 60
134 - 120
135 - 500
136 zone:
137 description:
138 - Specifies in which DCD zone is collecting the data from device.
139 type: str
140 default: default
141 stat_modules:
142 description:
143 - Specifies for which modules the data is being collected.
144 type: list
145 elements: str
146 default: ['device', 'ltm']
147 choices:
148 - device
149 - ltm
150 - dns
151 state:
152 description:
153 - The state of the managed device on the system.
154 - When C(present), enables new device addition as well as device rediscovery/import.
155 - When C(absent), completely removes the device from the system.
156 type: str
157 choices:
158 - absent
159 - present
160 default: present
161 extends_documentation_fragment: f5networks.f5_modules.f5
162 notes:
163 - BIG-IQ >= 6.1.0.
164 - This module does not support atomic removal of discovered modules on the device.
165 - Provider should point to the BIG-IQ credentials
166 author:
167 - Wojciech Wypior (@wojtek0806)
168 '''
169
170 EXAMPLES = r'''
171 - name: Discover a new device and import config, use default conflict policy.
172 bigiq_device_discovery:
173 device_address: 192.168.1.1
174 device_username: bigipadmin
175 device_password: bigipsecret
176 modules:
177 - ltm
178 - afm
179 - shared_security
180 provider:
181 password: secret
182 server: cm.mydomain.com
183 user: admin
184 delegate_to: localhost
185
186 - name: Discover a new device and import config, use non- default conflict policy.
187 bigiq_device_discovery:
188 device_address: 192.168.1.1
189 modules:
190 - ltm
191 - dns
192 conflict_policy: use_bigip
193 provider:
194 password: secret
195 server: cm.mydomain.com
196 user: admin
197 delegate_to: localhost
198
199 - name: Force full device rediscovery
200 bigiq_device_discovery:
201 device_address: 192.168.1.1
202 modules:
203 - ltm
204 - afm
205 - dns
206 - shared_security
207 force: true
208 provider:
209 password: secret
210 server: cm.mydomain.com
211 user: admin
212 delegate_to: localhost
213
214 - name: Remove discovered device and its config
215 bigiq_device_discovery:
216 device_address: 192.168.1.1
217 state: absent
218 provider:
219 password: secret
220 server: cm.mydomain.com
221 user: admin
222 delegate_to: localhost
223 '''
224
225 RETURN = r'''
226 device_address:
227 description: The IP address of the BIG-IP device to be imported/managed.
228 returned: changed
229 type: str
230 sample: 192.168.1.1
231 device_port:
232 description: The port on which a device trust setup between BIG-IQ and BIG-IP should happen.
233 returned: changed
234 type: int
235 sample: 10443
236 ha_name:
237 description: DSC cluster name of the BIG-IP device to be managed.
238 returned: changed
239 type: str
240 sample: GROUP_1
241 use_bigiq_sync:
242 description: Indicates if BIG-IQ should manually synchronize DSC configuration.
243 returned: changed
244 type: bool
245 sample: true
246 conflict_policy:
247 description: Sets the conflict resolution policy for shared objects across BIG-IP devices.
248 returned: changed
249 type: str
250 sample: use_bigip
251 device_conflict_policy:
252 description: Sets the conflict resolution policy for objects that are specific to a particular to a BIG-IP device.
253 returned: changed
254 type: str
255 sample: use_bigip
256 versioned_conflict_policy:
257 description: Sets the conflict resolution policy for LTM profile and monitor objects.
258 returned: changed
259 type: str
260 sample: keep_version
261 access_conflict_policy:
262 description: Sets the conflict resolution policy for Access module C(apm) objects.
263 returned: changed
264 type: str
265 sample: keep_version
266 access_group_name:
267 description: Access group name to import Access configuration for devices.
268 returned: changed
269 type: str
270 sample: foo_group
271 access_group_first_device:
272 description: First device in the access group to import shared configuration for that access group.
273 returned: changed
274 type: bool
275 sample: true
276 modules:
277 description: List of modules to be discovered and imported into the device.
278 returned: changed
279 type: list
280 sample: ['ltm', 'dns']
281
282 '''
283
284 import time
285 import traceback
286 from datetime import datetime
287
288 try:
289 from packaging.version import Version
290 except ImportError:
291 HAS_PACKAGING = False
292 Version = None
293 PACKAGING_IMPORT_ERROR = traceback.format_exc()
294 else:
295 HAS_PACKAGING = True
296 PACKAGING_IMPORT_ERROR = None
297
298 from ansible.module_utils.basic import (
299 AnsibleModule, missing_required_lib
300 )
301
302 from ..module_utils.bigip import F5RestClient
303 from ..module_utils.common import (
304 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean
305 )
306 from ..module_utils.icontrol import bigiq_version
307 from ..module_utils.ipaddress import is_valid_ip
308 from ..module_utils.teem import send_teem
309
310
311 class Parameters(AnsibleF5Parameters):
312 api_map = {
313 'address': 'device_address',
314 'userName': 'device_username',
315 'password': 'device_password',
316 'httpsPort': 'device_port',
317 'clusterName': 'ha_name',
318 'useBigiqSync': 'use_bigiq_sync',
319 }
320
321 api_attributes = [
322 'address',
323 'userName',
324 'password',
325 'httpsPort',
326 'clusterName',
327 'useBigiqSync',
328 ]
329
330 returnables = [
331 'device_address',
332 'device_username',
333 'device_password',
334 'device_port',
335 'ha_name',
336 'use_bigiq_sync',
337 'modules',
338 'conflict_policy',
339 'versioned_conflict_policy',
340 'device_conflict_policy',
341 'access_group_name',
342 'access_group_first_device',
343 'access_conflict_policy',
344 'module_list',
345 'apm_properties',
346 ]
347
348 updatables = [
349 'modules',
350 'access_group_name',
351 'apm_properties',
352 'module_list',
353 ]
354
355
356 class ApiParameters(Parameters):
357 module_map = {
358 'cm-security-shared-allSharedDevices': 'security_shared',
359 'cm-asm-allAsmDevices': 'asm',
360 'cm-firewall-allFirewallDevices': 'firewall',
361 'cm-websafe-allFpsDevices': 'fps',
362 'cm-dns-allBigIpDevices': 'dns',
363 'cm-adccore-allbigipDevices': 'adc_core',
364 'cm-access-allBigIpDevices': 'access',
365 }
366
367 @property
368 def modules(self):
369 raw_data = self._values['properties']
370 if raw_data is None:
371 return None
372 result = list()
373 for item in raw_data.keys():
374 if item in self.module_map:
375 if raw_data[item]['discovered'] is True and raw_data[item]['imported'] is True:
376 result.append(self.module_map[item])
377 return result
378
379 @property
380 def access_group_name(self):
381 raw_data = self._values['properties']
382 if raw_data is None:
383 return None
384 for item in raw_data.keys():
385 if 'cm:access:access-group-name' in raw_data[item]:
386 return raw_data[item]['cm:access:access-group-name']
387 return None
388
389
390 class ModuleParameters(Parameters):
391 module_map = {
392 'ltm': 'adc_core',
393 'afm': 'firewall',
394 'websafe': 'fps',
395 'apm': 'access',
396 }
397
398 @property
399 def device_password(self):
400 if self._values['device_password'] is None:
401 return None
402 return self._values['device_password']
403
404 @property
405 def device_username(self):
406 if self._values['device_username'] is None:
407 return None
408 return self._values['device_username']
409
410 @property
411 def device_address(self):
412 if is_valid_ip(self._values['device_address']):
413 return self._values['device_address']
414 raise F5ModuleError(
415 'Provided device address: {0} is not a valid IP.'.format(self._values['device_address'])
416 )
417
418 @property
419 def device_port(self):
420 if self._values['device_port'] is None:
421 return None
422 return int(self._values['device_port'])
423
424 @property
425 def conflict_policy(self):
426 return self._values['conflict_policy'].upper()
427
428 @property
429 def device_conflict_policy(self):
430 return self._values['device_conflict_policy'].upper()
431
432 @property
433 def versioned_conflict_policy(self):
434 if self._values['versioned_conflict_policy'] is None:
435 return None
436 return self._values['versioned_conflict_policy'].upper()
437
438 @property
439 def access_conflict_policy(self):
440 if self._values['access_conflict_policy'] is None:
441 return None
442 return self._values['device_conflict_policy'].upper()
443
444 @property
445 def modules(self):
446 if self._values['modules'] is None:
447 return None
448 result = list()
449 if 'security_shared' not in self._values['modules']:
450 if 'afm' in self._values['modules']:
451 raise F5ModuleError(
452 "Module 'shared_security' required for 'afm' module."
453 )
454 if 'asm' in self._values['modules']:
455 raise F5ModuleError(
456 "Module 'shared_security' required for 'asm' module."
457 )
458 if 'ltm' not in self._values['modules']:
459 raise F5ModuleError(
460 "LTM module must be specified for device discovery and import."
461 )
462 if 'apm' in self._values['modules']:
463 if not self.access_group_name or not self.access_conflict_policy:
464 raise F5ModuleError(
465 "When importing APM 'access_group_name' and 'access_conflict_policy' must be specified."
466 )
467 for item in self._values['modules']:
468 if item in self.module_map:
469 result.append(self.module_map[item])
470 else:
471 result.append(item)
472 return result
473
474 @property
475 def apm_properties(self):
476 if self._values['modules'] is None:
477 return None
478 if 'apm' in self._values['modules']:
479 result = {
480 'cm:access:conflict-resolution': self.access_conflict_policy,
481 'cm:access:access-group-name': self.access_group_name,
482 'cm:access:import-shared': self.access_group_first_device
483 }
484 return result
485
486 @property
487 def use_bigiq_sync(self):
488 result = flatten_boolean(self._values['use_bigiq_sync'])
489 if result:
490 if result == 'yes':
491 return True
492 return False
493
494 @property
495 def access_group_first_device(self):
496 result = flatten_boolean(self._values['access_group_first_device'])
497 if result:
498 if result == 'yes':
499 return True
500 return False
501
502 @property
503 def stats_enabled(self):
504 if self._values['statistics'] is None:
505 return None
506 result = flatten_boolean(self._values['statistics']['enable'])
507 if result:
508 if result == 'yes':
509 return True
510 return False
511
512 @property
513 def interval(self):
514 if self._values['statistics'] is None:
515 return None
516 return self._values['statistics']['interval']
517
518 @property
519 def zone(self):
520 if self._values['statistics'] is None:
521 return None
522 return self._values['statistics']['zone']
523
524 @property
525 def stat_modules(self):
526 if self._values['statistics'] is None:
527 return None
528 modules = self._values['statistics']['stat_modules']
529 result = list()
530 for module in modules:
531 result.append((dict(module=module.upper())))
532 return result
533
534
535 class Changes(Parameters):
536 def to_return(self):
537 result = {}
538 try:
539 for returnable in self.returnables:
540 result[returnable] = getattr(self, returnable)
541 result = self._filter_params(result)
542 except Exception:
543 pass
544 return result
545
546
547 class UsableChanges(Changes):
548 @property
549 def modules(self):
550 if self._values['modules'] is None:
551 return None
552 result = list()
553 for item in self._values['modules']:
554 result.append(dict(module=item))
555 return result
556
557 @property
558 def module_list(self):
559 if self._values['modules'] is None:
560 return None
561 result = list()
562 for item in self._values['modules']:
563 if item == 'access':
564 result.append(dict(module=item, properties=self._values['apm_properties']))
565 else:
566 result.append(dict(module=item))
567 return result
568
569
570 class ReportableChanges(Changes):
571 @property
572 def module_list(self):
573 return None
574
575 @property
576 def apm_properties(self):
577 return None
578
579
580 class Difference(object):
581 def __init__(self, want, have=None):
582 self.want = want
583 self.have = have
584
585 def compare(self, param):
586 try:
587 result = getattr(self, param)
588 return result
589 except AttributeError:
590 return self.__default(param)
591
592 def __default(self, param):
593 attr1 = getattr(self.want, param)
594 try:
595 attr2 = getattr(self.have, param)
596 if attr1 != attr2:
597 return attr1
598 except AttributeError:
599 return attr1
600
601 @property
602 def modules(self):
603 if self.want.modules is None:
604 return None
605 if self.have.modules is None:
606 return self.want.modules
607 if set(self.want.modules).issubset(self.have.modules):
608 return None
609 if set(self.want.modules) != set(self.have.modules):
610 return self.want.modules
611
612 @property
613 def access_group_name(self):
614 if self.want.access_group_name != self.have.access_group_name:
615 raise F5ModuleError(
616 'Access group name cannot be modified once it is set.'
617 )
618
619 @property
620 def apm_properties(self):
621 # This is required for idempotency and updates as we do not compare these properties
622 return None
623
624
625 class ModuleManager(object):
626 def __init__(self, *args, **kwargs):
627 self.module = kwargs.get('module', None)
628 self.client = F5RestClient(**self.module.params)
629 self.want = ModuleParameters(params=self.module.params)
630 self.have = ApiParameters()
631 self.changes = UsableChanges()
632 self.device_id = None
633 self.task_id = None
634
635 def _set_changed_options(self):
636 changed = {}
637 for key in Parameters.returnables:
638 if getattr(self.want, key) is not None:
639 changed[key] = getattr(self.want, key)
640 if changed:
641 self.changes = UsableChanges(params=changed)
642
643 def _update_changed_options(self):
644 diff = Difference(self.want, self.have)
645 updatables = Parameters.updatables
646 changed = dict()
647 for k in updatables:
648 change = diff.compare(k)
649 if change is None:
650 continue
651 else:
652 if isinstance(change, dict):
653 changed.update(change)
654 else:
655 changed[k] = change
656 if changed:
657 changed['apm_properties'] = self.want.apm_properties
658 self.changes = UsableChanges(params=changed)
659 return True
660 return False
661
662 def _announce_deprecations(self, result):
663 warnings = result.pop('__warnings', [])
664 for warning in warnings:
665 self.client.module.deprecate(
666 msg=warning['msg'],
667 version=warning['version']
668 )
669
670 def check_bigiq_version(self, version):
671 if Version(version) < Version('6.1.0'):
672 raise F5ModuleError(
673 'Module supports only BIGIQ version 6.1.x or higher.'
674 )
675
676 def exec_module(self):
677 start = datetime.now().isoformat()
678 version = bigiq_version(self.client)
679 self.check_bigiq_version(version)
680 changed = False
681 result = dict()
682 state = self.want.state
683
684 if state == "present":
685 changed = self.present()
686 elif state == "absent":
687 changed = self.absent()
688
689 reportable = ReportableChanges(params=self.changes.to_return())
690 changes = reportable.to_return()
691 result.update(**changes)
692 result.update(dict(changed=changed))
693 self._announce_deprecations(result)
694 send_teem(start, self.client, self.module, version)
695 return result
696
697 def present(self):
698 if self.exists():
699 return self.update()
700 else:
701 return self.create()
702
703 def absent(self):
704 if self.exists():
705 return self.remove()
706 return False
707
708 def should_update(self):
709 result = self._update_changed_options()
710 if result:
711 return True
712 return False
713
714 def update(self):
715 self.have = self.read_current_from_device()
716 if not self.should_update() and not self.want.force:
717 return False
718 if self.module.check_mode:
719 return True
720 if self.want.force:
721 self._set_changed_options()
722 self.discover_on_device()
723 self.import_modules_on_device()
724 if self.want.stats_enabled:
725 self.enable_stats_on_device()
726 return True
727
728 def remove(self):
729 if self.module.check_mode:
730 return True
731 self.remove_autority_from_device()
732 self.remove_trust_from_device()
733 return True
734
735 def create(self):
736 if self.want.modules is None:
737 raise F5ModuleError(
738 'List of modules cannot be empty if discovering a device.'
739 )
740 self._set_changed_options()
741 if self.module.check_mode:
742 return True
743 self.set_trust_with_device()
744 self.discover_on_device()
745 self.import_modules_on_device()
746 if self.want.stats_enabled:
747 self.enable_stats_on_device()
748 return True
749
750 def exists(self):
751 uri = "https://{0}:{1}/mgmt/cm/system/machineid-resolver".format(
752 self.client.provider['server'],
753 self.client.provider['server_port'],
754 )
755
756 query = "?$filter=address%20eq%20'{0}'".format(self.want.device_address)
757 resp = self.client.api.get(uri + query)
758
759 try:
760 response = resp.json()
761 except ValueError:
762 return False
763
764 if resp.status == 404 or 'code' in response and response['code'] == 404:
765 raise F5ModuleError(response.message)
766
767 if 'items' in response:
768 if not response['items']:
769 return False
770 self.device_id = response['items'][0]['machineId']
771 return True
772 return False
773
774 def set_trust_with_device(self):
775 params = self.changes.api_params()
776 params['name'] = 'trust_{0}'.format(self.want.device_address)
777 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-trust/".format(
778 self.client.provider['server'],
779 self.client.provider['server_port'],
780 )
781 resp = self.client.api.post(uri, json=params)
782 try:
783 response = resp.json()
784 except ValueError as ex:
785 raise F5ModuleError(str(ex))
786
787 if 'code' in response and response['code'] in [400, 409]:
788 if 'message' in response:
789 raise F5ModuleError(response['message'])
790 else:
791 raise F5ModuleError(resp.content)
792
793 task = "https://{0}:{1}/mgmt/cm/global/tasks/device-trust/{2}".format(
794 self.client.provider['server'],
795 self.client.provider['server_port'],
796 response['id']
797 )
798 query = "?$select=status,currentStep,errorMessage"
799
800 if self._wait_for_task(task + query):
801 self._set_device_id(task)
802 return True
803
804 def _set_device_id(self, uri):
805 resp = self.client.api.get(uri)
806
807 try:
808 response = resp.json()
809 except ValueError as ex:
810 raise F5ModuleError(str(ex))
811
812 if 'code' in response and response['code'] == 400:
813 if 'message' in response:
814 raise F5ModuleError(response['message'])
815 else:
816 raise F5ModuleError(resp.content)
817
818 self.device_id = response['machineId']
819
820 def _wait_for_task(self, uri):
821 while True:
822 resp = self.client.api.get(uri)
823
824 if resp.status == 401:
825 # handle expired tokens
826 self.client.reconnect()
827 resp = self.client.api.get(uri)
828
829 try:
830 response = resp.json()
831 except ValueError as ex:
832 raise F5ModuleError(str(ex))
833
834 if 'code' in response and response['code'] == 400:
835 if 'message' in response:
836 raise F5ModuleError(response['message'])
837 else:
838 raise F5ModuleError(resp.content)
839
840 if response['status'] in ['FINISHED', 'FAILED', 'CANCELLED']:
841 break
842
843 time.sleep(1)
844
845 if response['status'] == 'FAILED':
846 raise F5ModuleError(response['errorMessage'])
847 if response['status'] == 'CANCELLED':
848 raise F5ModuleError(
849 'The task process has been cancelled.'
850 )
851 if response['status'] == 'FINISHED':
852 return True
853
854 def discover_on_device(self):
855 tmp = self.changes.to_return()
856 if self.reuse_task_on_device('discovery'):
857 params = dict(
858 moduleList=tmp['modules'],
859 status='STARTED'
860 )
861 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-discovery/{2}".format(
862 self.client.provider['server'],
863 self.client.provider['server_port'],
864 self.task_id
865 )
866 resp = self.client.api.patch(uri, json=params)
867
868 else:
869 params = dict(
870 name='discovery_{0}'.format(self.want.device_address),
871 moduleList=tmp['modules'],
872 deviceReference=dict(link='https://localhost/mgmt/cm/system/machineid-resolver/{0}'.format(
873 self.device_id
874 )
875 ),
876 status='STARTED'
877 )
878 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-discovery".format(
879 self.client.provider['server'],
880 self.client.provider['server_port'],
881 )
882 resp = self.client.api.post(uri, json=params)
883
884 try:
885 response = resp.json()
886 except ValueError as ex:
887 raise F5ModuleError(str(ex))
888
889 if 'code' in response and response['code'] in [400, 409]:
890 if 'message' in response:
891 raise F5ModuleError(response['message'])
892 else:
893 raise F5ModuleError(resp.content)
894
895 task = "https://{0}:{1}/mgmt/cm/global/tasks/device-discovery/{2}".format(
896 self.client.provider['server'],
897 self.client.provider['server_port'],
898 response['id']
899 )
900 query = "?$select=status,currentStep,errorMessage"
901
902 self._wait_for_task(task + query)
903
904 return True
905
906 def import_modules_on_device(self):
907 tmp = self.changes.to_return()
908 if self.reuse_task_on_device('import'):
909 params = dict(
910 moduleList=tmp['module_list'],
911 conflictPolicy=self.want.conflict_policy,
912 deviceConflictPolicy=self.want.device_conflict_policy,
913 status='STARTED'
914 )
915
916 if self.want.versioned_conflict_policy:
917 params['versionedConflictPolicy'] = self.want.versioned_conflict_policy
918
919 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-import/{2}".format(
920 self.client.provider['server'],
921 self.client.provider['server_port'],
922 self.task_id
923 )
924 resp = self.client.api.patch(uri, json=params)
925
926 else:
927 params = dict(
928 name='import_{0}'.format(self.want.device_address),
929 moduleList=tmp['module_list'],
930 conflictPolicy=self.want.conflict_policy,
931 deviceConflictPolicy=self.want.device_conflict_policy,
932 deviceReference=dict(link='https://localhost/mgmt/cm/system/machineid-resolver/{0}'.format(
933 self.device_id
934 )
935 ),
936 status='STARTED'
937 )
938
939 if self.want.versioned_conflict_policy:
940 params['versionedConflictPolicy'] = self.want.versioned_conflict_policy
941
942 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-import".format(
943 self.client.provider['server'],
944 self.client.provider['server_port'],
945 )
946 resp = self.client.api.post(uri, json=params)
947
948 try:
949 response = resp.json()
950 except ValueError as ex:
951 raise F5ModuleError(str(ex))
952
953 if 'code' in response and response['code'] in [400, 409]:
954 if 'message' in response:
955 raise F5ModuleError(response['message'])
956 else:
957 raise F5ModuleError(resp.content)
958
959 task = "https://{0}:{1}/mgmt/cm/global/tasks/device-import/{2}".format(
960 self.client.provider['server'],
961 self.client.provider['server_port'],
962 response['id']
963 )
964 query = "?$select=status,currentStep,errorMessage"
965
966 self._wait_for_task(task + query)
967
968 return True
969
970 def enable_stats_on_device(self):
971 params = dict(
972 enabled=self.want.stats_enabled,
973 pushIntervalSecs=self.want.interval,
974 zone=self.want.zone,
975 modules=self.want.stat_modules,
976 targetDeviceReference=dict(
977 link='https://localhost/mgmt/cm/system/machineid-resolver/{0}'.format(
978 self.device_id
979 )
980 ),
981 )
982
983 uri = "https://{0}:{1}/mgmt/cm/shared/stats-mgmt/agent-install-and-config-task".format(
984 self.client.provider['server'],
985 self.client.provider['server_port'],
986 )
987 resp = self.client.api.post(uri, json=params)
988
989 try:
990 response = resp.json()
991 except ValueError as ex:
992 raise F5ModuleError(str(ex))
993
994 if 'code' in response and response['code'] in [400, 409]:
995 if 'message' in response:
996 raise F5ModuleError(response['message'])
997 else:
998 raise F5ModuleError(resp.content)
999
1000 task = "https://{0}:{1}/mgmt/cm/shared/stats-mgmt/agent-install-and-config-task/{2}".format(
1001 self.client.provider['server'],
1002 self.client.provider['server_port'],
1003 response['id']
1004 )
1005 query = "?$select=status,currentStep,errorMessage"
1006
1007 self._wait_for_task(task + query)
1008
1009 return True
1010
1011 def reuse_task_on_device(self, task):
1012 if task == 'discovery':
1013 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-discovery".format(
1014 self.client.provider['server'],
1015 self.client.provider['server_port'],
1016 )
1017 else:
1018 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-import".format(
1019 self.client.provider['server'],
1020 self.client.provider['server_port'],
1021 )
1022
1023 query = "?$filter=deviceReference/link%20eq%20'{0}'".format(self.device_id)
1024 resp = self.client.api.get(uri + query)
1025
1026 try:
1027 response = resp.json()
1028 except ValueError as ex:
1029 raise F5ModuleError(str(ex))
1030
1031 if 'code' in response and response['code'] in [400, 409]:
1032 if 'message' in response:
1033 raise F5ModuleError(response['message'])
1034 else:
1035 raise F5ModuleError(resp.content)
1036 if 'items' in response:
1037 if response['items']:
1038 self.task_id = response['id']
1039 return True
1040 return False
1041
1042 def remove_autority_from_device(self):
1043 # We can provide all of the modules for removal task, without ensuring they were discovered
1044 modules = [
1045 {'module': 'adc_core'},
1046 {'module': 'access'},
1047 {'module': 'asm'},
1048 {'module': 'fps'},
1049 {'module': 'firewall'},
1050 {'module': 'security_shared'},
1051 {'module': 'dns'}
1052 ]
1053 params = dict(
1054 moduleList=modules,
1055 deviceReference=dict(
1056 link="https://localhost/mgmt/cm/system/machineid-resolver/{0}".format(self.device_id)
1057 ),
1058 name='remove_auth_{0}'.format(self.want.device_address)
1059
1060 )
1061 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-remove-mgmt-authority/".format(
1062 self.client.provider['server'],
1063 self.client.provider['server_port'],
1064 )
1065 resp = self.client.api.post(uri, json=params)
1066
1067 try:
1068 response = resp.json()
1069 except ValueError as ex:
1070 raise F5ModuleError(str(ex))
1071
1072 if 'code' in response and response['code'] in [400, 409]:
1073 if 'message' in response:
1074 raise F5ModuleError(response['message'])
1075 else:
1076 raise F5ModuleError(resp.content)
1077
1078 task = "https://{0}:{1}/mgmt/cm/global/tasks/device-remove-mgmt-authority/{2}".format(
1079 self.client.provider['server'],
1080 self.client.provider['server_port'],
1081 response['id']
1082 )
1083 query = "?$select=status,currentStep,errorMessage"
1084
1085 self._wait_for_task(task + query)
1086
1087 def remove_trust_from_device(self):
1088 params = dict(
1089 deviceReference=dict(
1090 link="https://localhost/mgmt/cm/system/machineid-resolver/{0}".format(self.device_id)
1091 ),
1092 name='remove_auth_{0}'.format(self.want.device_address)
1093
1094 )
1095 uri = "https://{0}:{1}/mgmt/cm/global/tasks/device-remove-trust/".format(
1096 self.client.provider['server'],
1097 self.client.provider['server_port'],
1098 )
1099 resp = self.client.api.post(uri, json=params)
1100
1101 try:
1102 response = resp.json()
1103 except ValueError as ex:
1104 raise F5ModuleError(str(ex))
1105
1106 if 'code' in response and response['code'] in [400, 409]:
1107 if 'message' in response:
1108 raise F5ModuleError(response['message'])
1109 else:
1110 raise F5ModuleError(resp.content)
1111
1112 task = "https://{0}:{1}/mgmt/cm/global/tasks/device-remove-trust/{2}".format(
1113 self.client.provider['server'],
1114 self.client.provider['server_port'],
1115 response['id']
1116 )
1117 query = "?$select=status,currentStep,errorMessage"
1118
1119 self._wait_for_task(task + query)
1120
1121 def read_current_from_device(self):
1122 uri = "https://{0}:{1}/mgmt/cm/system/machineid-resolver/{2}".format(
1123 self.client.provider['server'],
1124 self.client.provider['server_port'],
1125 self.device_id
1126 )
1127 resp = self.client.api.get(uri)
1128 try:
1129 response = resp.json()
1130 except ValueError as ex:
1131 raise F5ModuleError(str(ex))
1132
1133 if 'code' in response and response['code'] == 400:
1134 if 'message' in response:
1135 raise F5ModuleError(response['message'])
1136 else:
1137 raise F5ModuleError(resp.content)
1138 return ApiParameters(params=response)
1139
1140
1141 class ArgumentSpec(object):
1142 def __init__(self):
1143 self.supports_check_mode = True
1144 self.conflict = ['use_bigip', 'use_bigiq']
1145 argument_spec = dict(
1146 device_address=dict(
1147 required=True
1148 ),
1149 device_username=dict(
1150 no_log=True
1151 ),
1152 device_password=dict(
1153 no_log=True
1154 ),
1155 device_port=dict(
1156 type='int',
1157 default=443
1158 ),
1159 ha_name=dict(),
1160 use_bigiq_sync=dict(
1161 type='bool',
1162 default='no'
1163 ),
1164 conflict_policy=dict(
1165 choices=self.conflict,
1166 default='use_bigiq'
1167 ),
1168 versioned_conflict_policy=dict(
1169 choices=self.conflict + ['keep_version'],
1170 ),
1171 device_conflict_policy=dict(
1172 choices=self.conflict,
1173 default='use_bigiq'
1174 ),
1175 force=dict(
1176 type='bool',
1177 default='no'
1178 ),
1179 modules=dict(
1180 type='list',
1181 elements='str',
1182 choices=[
1183 'ltm', 'asm', 'afm', 'dns', 'websafe', 'security_shared', 'apm'
1184 ]
1185 ),
1186 access_conflict_policy=dict(
1187 choices=self.conflict + ['keep_version']
1188 ),
1189 access_group_name=dict(),
1190 access_group_first_device=dict(
1191 type='bool',
1192 default='yes'
1193 ),
1194 statistics=dict(
1195 type='dict',
1196 options=dict(
1197 enable=dict(
1198 type='bool',
1199 default='no'
1200 ),
1201 interval=dict(
1202 type='int',
1203 choices=[
1204 30, 60, 120, 500
1205 ],
1206 default=60
1207 ),
1208 zone=dict(
1209 type='str',
1210 default='default'
1211 ),
1212 stat_modules=dict(
1213 type='list',
1214 elements='str',
1215 choices=[
1216 'device', 'ltm', 'dns'
1217 ],
1218 default=[
1219 'device', 'ltm'
1220 ]
1221 )
1222 )
1223
1224 ),
1225 state=dict(default='present', choices=['absent', 'present']),
1226 )
1227 self.required_if = [
1228 ['use_bigiq_sync', True, ['ha_name']]
1229 ]
1230 self.argument_spec = {}
1231 self.argument_spec.update(f5_argument_spec)
1232 self.argument_spec.update(argument_spec)
1233
1234
1235 def main():
1236 spec = ArgumentSpec()
1237
1238 module = AnsibleModule(
1239 argument_spec=spec.argument_spec,
1240 supports_check_mode=spec.supports_check_mode,
1241 required_if=spec.required_if
1242 )
1243
1244 if not HAS_PACKAGING:
1245 module.fail_json(
1246 msg=missing_required_lib('packaging'),
1247 exception=PACKAGING_IMPORT_ERROR
1248 )
1249
1250 try:
1251 mm = ModuleManager(module=module)
1252 results = mm.exec_module()
1253 module.exit_json(**results)
1254 except F5ModuleError as ex:
1255 module.fail_json(msg=str(ex))
1256
1257
1258 if __name__ == '__main__':
1259 main()