Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_discovery.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2021-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r'''
17 ---
18 module: ome_discovery
19 short_description: Create, modify, or delete a discovery job on OpenManage Enterprise
20 version_added: "3.3.0"
21 description: This module allows to create, modify, or delete a discovery job.
22 extends_documentation_fragment:
23 - dellemc.openmanage.oment_auth_options
24 options:
25 state:
26 description:
27 - C(present) creates a discovery job or modifies an existing discovery job.
28 - I(discovery_job_name) is mandatory for the creation of a new discovery job.
29 - If multiple discoveries of the same I(discovery_job_name) exist, then the new discovery job will not be created.
30 - C(absent) deletes an existing discovery job(s) with the specified I(discovery_job_name).
31 choices: [present, absent]
32 default: present
33 type: str
34 discovery_job_name:
35 description:
36 - Name of the discovery configuration job.
37 - It is mutually exclusive with I(discovery_id).
38 type: str
39 discovery_id:
40 description:
41 - ID of the discovery configuration group.
42 - This value is DiscoveryConfigGroupId in the return values under discovery_status.
43 - It is mutually exclusive with I(discovery_job_name).
44 type: int
45 new_name:
46 description: New name of the discovery configuration job.
47 type: str
48 schedule:
49 description:
50 - Provides the option to schedule the discovery job.
51 - If C(RunLater) is selected, then I(cron) must be specified.
52 choices: [RunNow, RunLater]
53 default: RunNow
54 type: str
55 cron:
56 description:
57 - Provide a cron expression based on Quartz cron format.
58 type: str
59 trap_destination:
60 description:
61 - Enable OpenManage Enterprise to receive the incoming SNMP traps from the discovered devices.
62 - This is effective only for servers discovered by using their iDRAC interface.
63 type: bool
64 default: false
65 community_string:
66 description: "Enable the use of SNMP community strings to receive SNMP traps using Application Settings in
67 OpenManage Enterprise. This option is available only for the discovered iDRAC servers and MX7000 chassis."
68 type: bool
69 default: false
70 email_recipient:
71 description: "Enter the email address to which notifications are to be sent about the discovery job status.
72 Configure the SMTP settings to allow sending notifications to an email address."
73 type: str
74 job_wait:
75 description:
76 - Provides the option to wait for job completion.
77 - This option is applicable when I(state) is C(present).
78 type: bool
79 default: true
80 job_wait_timeout:
81 description:
82 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
83 - This option is applicable when I(job_wait) is C(true).
84 type: int
85 default: 10800
86 ignore_partial_failure:
87 description:
88 - "Provides the option to ignore partial failures. Partial failures occur when there is a combination of both
89 discovered and undiscovered IPs."
90 - If C(false), then the partial failure is not ignored, and the module will error out.
91 - If C(true), then the partial failure is ignored.
92 - This option is only applicable if I(job_wait) is C(true).
93 type: bool
94 default: false
95 discovery_config_targets:
96 description:
97 - Provide the list of discovery targets.
98 - "Each discovery target is a set of I(network_address_detail), I(device_types), and one or more protocol
99 credentials."
100 - This is mandatory when I(state) is C(present).
101 - "C(WARNING) Modification of this field is not supported, this field is overwritten every time. Ensure to provide
102 all the required details for this field."
103 type: list
104 elements: dict
105 suboptions:
106 network_address_detail:
107 description:
108 - "Provide the list of IP addresses, host names, or the range of IP addresses of the devices to be discovered
109 or included."
110 - "Sample Valid IP Range Formats"
111 - " 192.35.0.0"
112 - " 192.36.0.0-10.36.0.255"
113 - " 192.37.0.0/24"
114 - " 2345:f2b1:f083:135::5500/118"
115 - " 2345:f2b1:f083:135::a500-2607:f2b1:f083:135::a600"
116 - " hostname.domain.tld"
117 - " hostname"
118 - " 2345:f2b1:f083:139::22a"
119 - "Sample Invalid IP Range Formats"
120 - " 192.35.0.*"
121 - " 192.36.0.0-255"
122 - " 192.35.0.0/255.255.255.0"
123 - C(NOTE) The range size for the number of IP addresses is limited to 16,385 (0x4001).
124 - C(NOTE) Both IPv6 and IPv6 CIDR formats are supported.
125 type: list
126 elements: str
127 required: true
128 device_types:
129 description:
130 - Provide the type of devices to be discovered.
131 - The accepted types are SERVER, CHASSIS, NETWORK SWITCH, and STORAGE.
132 - A combination or all of the above can be provided.
133 - "Supported protocols for each device type are:"
134 - SERVER - I(wsman), I(redfish), I(snmp), I(ipmi), I(ssh), and I(vmware).
135 - CHASSIS - I(wsman), and I(redfish).
136 - NETWORK SWITCH - I(snmp).
137 - STORAGE - I(storage), and I(snmp).
138 type: list
139 elements: str
140 required: true
141 wsman:
142 description: Web Services-Management (WS-Man).
143 type: dict
144 suboptions:
145 username:
146 description: Provide a username for the protocol.
147 type: str
148 required: true
149 password:
150 description: Provide a password for the protocol.
151 type: str
152 required: true
153 domain:
154 description: Provide a domain for the protocol.
155 type: str
156 port:
157 description: Enter the port number that the job must use to discover the devices.
158 type: int
159 default: 443
160 retries:
161 description: Enter the number of repeated attempts required to discover a device.
162 type: int
163 default: 3
164 timeout:
165 description: Enter the time in seconds after which a job must stop running.
166 type: int
167 default: 60
168 cn_check:
169 description: Enable the Common Name (CN) check.
170 type: bool
171 default: false
172 ca_check:
173 description: Enable the Certificate Authority (CA) check.
174 type: bool
175 default: false
176 certificate_data:
177 description: Provide certificate data for the CA check.
178 type: str
179 redfish:
180 description: REDFISH protocol.
181 type: dict
182 suboptions:
183 username:
184 description: Provide a username for the protocol.
185 type: str
186 required: true
187 password:
188 description: Provide a password for the protocol.
189 type: str
190 required: true
191 domain:
192 description: Provide a domain for the protocol.
193 type: str
194 port:
195 description: Enter the port number that the job must use to discover the devices.
196 type: int
197 default: 443
198 retries:
199 description: Enter the number of repeated attempts required to discover a device.
200 type: int
201 default: 3
202 timeout:
203 description: Enter the time in seconds after which a job must stop running.
204 type: int
205 default: 60
206 cn_check:
207 description: Enable the Common Name (CN) check.
208 type: bool
209 default: false
210 ca_check:
211 description: Enable the Certificate Authority (CA) check.
212 type: bool
213 default: false
214 certificate_data:
215 description: Provide certificate data for the CA check.
216 type: str
217 snmp:
218 description: Simple Network Management Protocol (SNMP).
219 type: dict
220 suboptions:
221 community:
222 description: Community string for the SNMP protocol.
223 type: str
224 required: true
225 port:
226 description: Enter the port number that the job must use to discover the devices.
227 type: int
228 default: 161
229 retries:
230 description: Enter the number of repeated attempts required to discover a device.
231 type: int
232 default: 3
233 timeout:
234 description: Enter the time in seconds after which a job must stop running.
235 type: int
236 default: 3
237 storage:
238 description: HTTPS Storage protocol.
239 type: dict
240 suboptions:
241 username:
242 description: Provide a username for the protocol.
243 type: str
244 required: true
245 password:
246 description: Provide a password for the protocol.
247 type: str
248 required: true
249 domain:
250 description: Provide a domain for the protocol.
251 type: str
252 port:
253 description: Enter the port number that the job must use to discover the devices.
254 type: int
255 default: 443
256 retries:
257 description: Enter the number of repeated attempts required to discover a device.
258 type: int
259 default: 3
260 timeout:
261 description: Enter the time in seconds after which a job must stop running.
262 type: int
263 default: 60
264 cn_check:
265 description: Enable the Common Name (CN) check.
266 type: bool
267 default: false
268 ca_check:
269 description: Enable the Certificate Authority (CA) check.
270 type: bool
271 default: false
272 certificate_data:
273 description: Provide certificate data for the CA check.
274 type: str
275 vmware:
276 description: VMWARE protocol.
277 type: dict
278 suboptions:
279 username:
280 description: Provide a username for the protocol.
281 type: str
282 required: true
283 password:
284 description: Provide a password for the protocol.
285 type: str
286 required: true
287 domain:
288 description: Provide a domain for the protocol.
289 type: str
290 port:
291 description: Enter the port number that the job must use to discover the devices.
292 type: int
293 default: 443
294 retries:
295 description: Enter the number of repeated attempts required to discover a device.
296 type: int
297 default: 3
298 timeout:
299 description: Enter the time in seconds after which a job must stop running.
300 type: int
301 default: 60
302 cn_check:
303 description: Enable the Common Name (CN) check.
304 type: bool
305 default: false
306 ca_check:
307 description: Enable the Certificate Authority (CA) check.
308 type: bool
309 default: false
310 certificate_data:
311 description: Provide certificate data for the CA check.
312 type: str
313 ssh:
314 description: Secure Shell (SSH).
315 type: dict
316 suboptions:
317 username:
318 description: Provide a username for the protocol.
319 type: str
320 required: true
321 password:
322 description: Provide a password for the protocol.
323 type: str
324 required: true
325 port:
326 description: Enter the port number that the job must use to discover the devices.
327 type: int
328 default: 22
329 retries:
330 description: Enter the number of repeated attempts required to discover a device.
331 type: int
332 default: 3
333 timeout:
334 description: Enter the time in seconds after which a job must stop running.
335 type: int
336 default: 60
337 check_known_hosts:
338 description: Verify the known host key.
339 type: bool
340 default: false
341 is_sudo_user:
342 description: Use the SUDO option.
343 type: bool
344 default: false
345 ipmi:
346 description: Intelligent Platform Management Interface (IPMI)
347 type: dict
348 suboptions:
349 username:
350 description: Provide a username for the protocol.
351 type: str
352 required: true
353 password:
354 description: Provide a password for the protocol.
355 type: str
356 required: true
357 retries:
358 description: Enter the number of repeated attempts required to discover a device.
359 type: int
360 default: 3
361 timeout:
362 description: Enter the time in seconds after which a job must stop running.
363 type: int
364 default: 60
365 kgkey:
366 description: KgKey for the IPMI protocol.
367 type: str
368 requirements:
369 - "python >= 3.9.6"
370 author:
371 - "Jagadeesh N V (@jagadeeshnv)"
372 - "Sajna Shetty (@Sajna-Shetty)"
373 - "Abhishek Sinha (@Abhishek-Dell)"
374 notes:
375 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
376 - This module does not support C(check_mode).
377 - If I(state) is C(present), then Idempotency is not supported.
378 '''
379
380 EXAMPLES = r'''
381 ---
382 - name: Discover servers in a range
383 dellemc.openmanage.ome_discovery:
384 hostname: "192.168.0.1"
385 username: "username"
386 password: "password"
387 ca_path: "/path/to/ca_cert.pem"
388 discovery_job_name: "Discovery_server_1"
389 discovery_config_targets:
390 - network_address_detail:
391 - 192.96.24.1-192.96.24.255
392 device_types:
393 - SERVER
394 wsman:
395 username: user
396 password: password
397
398 - name: Discover chassis in a range
399 dellemc.openmanage.ome_discovery:
400 hostname: "192.168.0.1"
401 username: "username"
402 password: "password"
403 ca_path: "/path/to/ca_cert.pem"
404 discovery_job_name: "Discovery_chassis_1"
405 discovery_config_targets:
406 - network_address_detail:
407 - 192.96.24.1-192.96.24.255
408 device_types:
409 - CHASSIS
410 wsman:
411 username: user
412 password: password
413
414 - name: Discover switches in a range
415 dellemc.openmanage.ome_discovery:
416 hostname: "192.168.0.1"
417 username: "username"
418 password: "password"
419 ca_path: "/path/to/ca_cert.pem"
420 discovery_job_name: "Discover_switch_1"
421 discovery_config_targets:
422 - network_address_detail:
423 - 192.96.24.1-192.96.24.255
424 device_types:
425 - NETWORK SWITCH
426 snmp:
427 community: snmp_creds
428
429 - name: Discover storage in a range
430 dellemc.openmanage.ome_discovery:
431 hostname: "192.168.0.1"
432 username: "username"
433 password: "password"
434 ca_path: "/path/to/ca_cert.pem"
435 discovery_job_name: "Discover_storage_1"
436 discovery_config_targets:
437 - network_address_detail:
438 - 192.96.24.1-192.96.24.255
439 device_types:
440 - STORAGE
441 storage:
442 username: user
443 password: password
444 snmp:
445 community: snmp_creds
446
447 - name: Delete a discovery job
448 dellemc.openmanage.ome_discovery:
449 hostname: "192.168.0.1"
450 username: "username"
451 password: "password"
452 ca_path: "/path/to/ca_cert.pem"
453 state: "absent"
454 discovery_job_name: "Discovery-123"
455
456 - name: Schedule the discovery of multiple devices ignoring partial failure and enable trap to receive alerts
457 dellemc.openmanage.ome_discovery:
458 hostname: "192.168.0.1"
459 username: "username"
460 password: "password"
461 ca_path: "/path/to/ca_cert.pem"
462 state: "present"
463 discovery_job_name: "Discovery-123"
464 discovery_config_targets:
465 - network_address_detail:
466 - 192.96.24.1-192.96.24.255
467 - 192.96.0.0/24
468 - 192.96.26.108
469 device_types:
470 - SERVER
471 - CHASSIS
472 - STORAGE
473 - NETWORK SWITCH
474 wsman:
475 username: wsman_user
476 password: wsman_pwd
477 redfish:
478 username: redfish_user
479 password: redfish_pwd
480 snmp:
481 community: snmp_community
482 - network_address_detail:
483 - 192.96.25.1-192.96.25.255
484 - ipmihost
485 - esxiserver
486 - sshserver
487 device_types:
488 - SERVER
489 ssh:
490 username: ssh_user
491 password: ssh_pwd
492 vmware:
493 username: vm_user
494 password: vmware_pwd
495 ipmi:
496 username: ipmi_user
497 password: ipmi_pwd
498 schedule: RunLater
499 cron: "0 0 9 ? * MON,WED,FRI *"
500 ignore_partial_failure: true
501 trap_destination: true
502 community_string: true
503 email_recipient: [email protected]
504
505 - name: Discover servers with ca check enabled
506 dellemc.openmanage.ome_discovery:
507 hostname: "192.168.0.1"
508 username: "username"
509 password: "password"
510 ca_path: "/path/to/ca_cert.pem"
511 discovery_job_name: "Discovery_server_ca1"
512 discovery_config_targets:
513 - network_address_detail:
514 - 192.96.24.108
515 device_types:
516 - SERVER
517 wsman:
518 username: user
519 password: password
520 ca_check: true
521 certificate_data: "{{ lookup('ansible.builtin.file', '/path/to/certificate_data_file') }}"
522
523 - name: Discover chassis with ca check enabled data
524 dellemc.openmanage.ome_discovery:
525 hostname: "192.168.0.1"
526 username: "username"
527 password: "password"
528 ca_path: "/path/to/ca_cert.pem"
529 discovery_job_name: "Discovery_chassis_ca1"
530 discovery_config_targets:
531 - network_address_detail:
532 - 192.96.24.108
533 device_types:
534 - CHASSIS
535 redfish:
536 username: user
537 password: password
538 ca_check: true
539 certificate_data: "-----BEGIN CERTIFICATE-----\r\n
540 ABCDEFGHIJKLMNOPQRSTUVWXYZaqwertyuiopasdfghjklzxcvbnmasdasagasvv\r\n
541 ABCDEFGHIJKLMNOPQRSTUVWXYZaqwertyuiopasdfghjklzxcvbnmasdasagasvv\r\n
542 ABCDEFGHIJKLMNOPQRSTUVWXYZaqwertyuiopasdfghjklzxcvbnmasdasagasvv\r\n
543 aqwertyuiopasdfghjklzxcvbnmasdasagasvv=\r\n
544 -----END CERTIFICATE-----"
545 '''
546
547 RETURN = r'''
548 ---
549 msg:
550 description: Overall status of the discovery operation.
551 returned: always
552 type: str
553 sample: "Successfully deleted 1 discovery job(s)."
554 discovery_status:
555 description:
556 - Details of the discovery job created or modified.
557 - If I(job_wait) is true, Completed and Failed IPs are also listed.
558 returned: when I(state) is C(present)
559 type: dict
560 sample: {
561 "Completed": [
562 "192.168.24.17",
563 "192.168.24.20",
564 "192.168.24.22"
565 ],
566 "Failed": [
567 "192.168.24.15",
568 "192.168.24.16",
569 "192.168.24.18",
570 "192.168.24.19",
571 "192.168.24.21",
572 "host123"
573 ],
574 "DiscoveredDevicesByType": [
575 {
576 "Count": 3,
577 "DeviceType": "SERVER"
578 }
579 ],
580 "DiscoveryConfigDiscoveredDeviceCount": 3,
581 "DiscoveryConfigEmailRecipient": "[email protected]",
582 "DiscoveryConfigExpectedDeviceCount": 9,
583 "DiscoveryConfigGroupId": 125,
584 "JobDescription": "D1",
585 "JobEnabled": true,
586 "JobEndTime": "2021-01-01 06:27:29.99",
587 "JobId": 12666,
588 "JobName": "D1",
589 "JobNextRun": null,
590 "JobProgress": "100",
591 "JobSchedule": "startnow",
592 "JobStartTime": "2021-01-01 06:24:10.071",
593 "JobStatusId": 2090,
594 "LastUpdateTime": "2021-01-01 06:27:30.001",
595 "UpdatedBy": "admin"
596 }
597 discovery_ids:
598 description: IDs of the discoveries with duplicate names.
599 returned: when discoveries with duplicate name exist for I(state) is C(present)
600 type: list
601 sample: [1234, 5678]
602 job_detailed_status:
603 description: Detailed last execution history of a job.
604 returned: All time.
605 type: list
606 sample: [
607 {
608 "ElapsedTime": "00:00:00",
609 "EndTime": null,
610 "ExecutionHistoryId": 564873,
611 "Id": 656893,
612 "IdBaseEntity": 0,
613 "JobStatus": {
614 "Id": 2050,
615 "Name": "Running"
616 },
617 "Key": "192.96.24.1",
618 "Progress": "0",
619 "StartTime": "2023-07-04 06:23:54.008",
620 "Value": "Running\nDiscovery of target 192.96.24.1 started.\nDiscovery target resolved to IP 192.96.24.1 ."
621 }
622 ]
623 error_info:
624 description: Details of the HTTP Error.
625 returned: on HTTP error
626 type: dict
627 sample: {
628 "error": {
629 "code": "Base.1.0.GeneralError",
630 "message": "A general error has occurred. See ExtendedInfo for more information.",
631 "@Message.ExtendedInfo": [
632 {
633 "MessageId": "GEN1234",
634 "RelatedProperties": [],
635 "Message": "Unable to process the request because an error occurred.",
636 "MessageArgs": [],
637 "Severity": "Critical",
638 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
639 }
640 ]
641 }
642 }
643 '''
644
645 import json
646 import time
647 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
648 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import strip_substr_dict
649 from ansible.module_utils.urls import ConnectionError, SSLValidationError
650 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
651 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
652
653 CONFIG_GROUPS_URI = "DiscoveryConfigService/DiscoveryConfigGroups"
654 DISCOVERY_JOBS_URI = "DiscoveryConfigService/Jobs"
655 DELETE_JOB_URI = "DiscoveryConfigService/Actions/DiscoveryConfigService.RemoveDiscoveryGroup"
656 PROTOCOL_DEVICE = "DiscoveryConfigService/ProtocolToDeviceType"
657 JOB_EXEC_HISTORY = "JobService/Jobs({job_id})/ExecutionHistories"
658 CONFIG_GROUPS_ID_URI = "DiscoveryConfigService/DiscoveryConfigGroups({group_id})"
659 NO_CHANGES_MSG = "No changes found to be applied."
660 DISC_JOB_RUNNING = "Discovery job '{name}' with ID {id} is running. Please retry after job completion."
661 DISC_DEL_JOBS_SUCCESS = "Successfully deleted {n} discovery job(s)."
662 MULTI_DISCOVERY = "Multiple discoveries present. Run the job again using a specific ID."
663 DISCOVERY_SCHEDULED = "Successfully scheduled the Discovery job."
664 DISCOVER_JOB_COMPLETE = "Successfully completed the Discovery job."
665 JOB_TRACK_SUCCESS = "Discovery job has {0}."
666 JOB_TRACK_FAIL = "No devices discovered, job is in {0} state."
667 JOB_TRACK_UNABLE = "Unable to track discovery job status of {0}."
668 JOB_TRACK_INCOMPLETE = "Discovery job {0} incomplete after polling {1} times."
669 INVALID_DEVICES = "Invalid device types found - {0}."
670 DISCOVERY_PARTIAL = "Some IPs are not discovered."
671 ATLEAST_ONE_PROTOCOL = "Protocol not applicable for given device types."
672 INVALID_DISCOVERY_ID = "Invalid discovery ID provided."
673 SETTLING_TIME = 5
674 JOB_STATUS_MAP = {
675 2020: "Scheduled", 2030: "Queued", 2040: "Starting", 2050: "Running", 2060: "completed successfully",
676 2070: "Failed", 2090: "completed with errors", 2080: "New", 2100: "Aborted", 2101: "Paused", 2102: "Stopped",
677 2103: "Canceled"
678 }
679
680
681 def check_existing_discovery(module, rest_obj):
682 discovery_cfgs = []
683 discovery_id = module.params.get("discovery_id")
684 srch_key = "DiscoveryConfigGroupName"
685 srch_val = module.params.get("discovery_job_name")
686 if discovery_id:
687 srch_key = "DiscoveryConfigGroupId"
688 srch_val = module.params.get("discovery_id")
689 resp = rest_obj.invoke_request('GET', CONFIG_GROUPS_URI + "?$top=9999")
690 discovs = resp.json_data.get("value")
691 for d in discovs:
692 if d[srch_key] == srch_val:
693 discovery_cfgs.append(d)
694 if discovery_id:
695 break
696 return discovery_cfgs
697
698
699 def get_discovery_states(rest_obj, key="JobStatusId"):
700 resp = rest_obj.invoke_request('GET', DISCOVERY_JOBS_URI)
701 disc_jobs = resp.json_data.get("value")
702 job_state_dict = dict([(item["DiscoveryConfigGroupId"], item[key]) for item in disc_jobs])
703 return job_state_dict
704
705
706 def get_protocol_device_map(rest_obj):
707 prot_dev_map = {}
708 dev_id_map = {}
709 resp = rest_obj.invoke_request('GET', PROTOCOL_DEVICE)
710 prot_dev = resp.json_data.get('value')
711 for item in prot_dev:
712 dname = item["DeviceTypeName"]
713 dlist = prot_dev_map.get(dname, [])
714 dlist.append(item["ProtocolName"])
715 prot_dev_map[dname] = dlist
716 dev_id_map[dname] = item["DeviceTypeId"]
717 if dname == "DELL STORAGE":
718 prot_dev_map['STORAGE'] = dlist
719 dev_id_map['STORAGE'] = item["DeviceTypeId"]
720 return prot_dev_map, dev_id_map
721
722
723 def get_other_discovery_payload(module):
724 trans_dict = {'discovery_job_name': "DiscoveryConfigGroupName",
725 'trap_destination': "TrapDestination",
726 'community_string': "CommunityString",
727 'email_recipient': "DiscoveryStatusEmailRecipient"}
728 other_dict = {}
729 for key, val in trans_dict.items():
730 if module.params.get(key) is not None:
731 other_dict[val] = module.params.get(key)
732 return other_dict
733
734
735 def get_schedule(module):
736 schedule_payload = {}
737 schedule = module.params.get('schedule')
738 if not schedule or schedule == 'RunNow':
739 schedule_payload['RunNow'] = True
740 schedule_payload['RunLater'] = False
741 schedule_payload['Cron'] = 'startnow'
742 else:
743 schedule_payload['RunNow'] = False
744 schedule_payload['RunLater'] = True
745 schedule_payload['Cron'] = module.params.get('cron')
746 return schedule_payload
747
748
749 def get_execution_details(rest_obj, job_id):
750 try:
751 ips = {"Completed": [], "Failed": []}
752 job_detail_status = []
753 resp = rest_obj.invoke_request('GET', JOB_EXEC_HISTORY.format(job_id=job_id))
754 ex_hist = resp.json_data.get('value')
755 # Sorting based on startTime and to get latest execution instance.
756 tmp_dict = dict((x["StartTime"], x["Id"]) for x in ex_hist)
757 sorted_dates = sorted(tmp_dict.keys())
758 ex_url = JOB_EXEC_HISTORY.format(job_id=job_id) + "({0})/ExecutionHistoryDetails".format(tmp_dict[sorted_dates[-1]])
759 all_exec = rest_obj.get_all_items_with_pagination(ex_url)
760 for jb_ip in all_exec.get('value'):
761 jb_ip = strip_substr_dict(jb_ip)
762 jb_ip.get('JobStatus', {}).pop('@odata.type', None)
763 job_detail_status.append(jb_ip)
764 jobstatus = jb_ip.get('JobStatus', {}).get('Name', 'Unknown')
765 jlist = ips.get(jobstatus, [])
766 jlist.append(jb_ip.get('Key'))
767 ips[jobstatus] = jlist
768 except Exception:
769 pass
770 return ips, job_detail_status
771
772
773 def discovery_job_tracking(rest_obj, job_id, job_wait_sec):
774 sleep_interval = 30
775 max_retries = job_wait_sec // sleep_interval
776 failed_job_status = [2070, 2100, 2101, 2102, 2103]
777 success_job_status = [2060, 2020, 2090]
778 job_url = (DISCOVERY_JOBS_URI + "({job_id})").format(job_id=job_id)
779 loop_ctr = 0
780 time.sleep(SETTLING_TIME)
781 while loop_ctr < max_retries:
782 loop_ctr += 1
783 try:
784 job_resp = rest_obj.invoke_request('GET', job_url)
785 job_dict = job_resp.json_data
786 job_status = job_dict['JobStatusId']
787 if job_status in success_job_status:
788 return JOB_TRACK_SUCCESS.format(JOB_STATUS_MAP[job_status])
789 elif job_status in failed_job_status:
790 return JOB_TRACK_FAIL.format(JOB_STATUS_MAP[job_status])
791 time.sleep(sleep_interval)
792 except HTTPError:
793 return JOB_TRACK_UNABLE.format(job_id)
794 except Exception as err:
795 return str(err)
796 return JOB_TRACK_INCOMPLETE.format(job_id, max_retries)
797
798
799 def get_job_data(discovery_json, rest_obj):
800 job_list = discovery_json['DiscoveryConfigTaskParam']
801 if len(job_list) == 1:
802 job_id = job_list[0].get('TaskId')
803 else:
804 srch_key = 'DiscoveryConfigGroupId'
805 srch_val = discovery_json[srch_key]
806 resp = rest_obj.invoke_request('GET', DISCOVERY_JOBS_URI + "?$top=9999")
807 discovs = resp.json_data.get("value")
808 for d in discovs:
809 if d[srch_key] == srch_val:
810 job_id = d['JobId']
811 break
812 return job_id
813
814
815 def get_connection_profile(disc_config):
816 proto_add_dict = {
817 'wsman': {
818 'certificateDetail': None,
819 'isHttp': False,
820 'keepAlive': True,
821 # 'version': None
822 },
823 'redfish': {'certificateDetail': None, 'isHttp': False, 'keepAlive': True},
824 'snmp': {
825 # 'authenticationPassphrase': None,
826 # 'authenticationProtocol': None,
827 'enableV1V2': True,
828 'enableV3': False,
829 # 'localizationEngineID': None,
830 # 'privacyPassphrase': None,
831 # 'privacyProtocol': None,
832 # 'securityName': None
833 },
834 'vmware': {'certificateDetail': None, 'isHttp': False, 'keepAlive': False},
835 'ssh': {'useKey': False, 'key': None, 'knownHostKey': None, 'passphrase': None},
836 'ipmi': {'privilege': 2},
837 'storage': {
838 'certificateDetail': None,
839 'isHttp': False,
840 'keepAlive': True,
841 # 'version': None
842 }
843 }
844 proto_list = ['wsman', 'snmp', 'vmware', 'ssh', 'ipmi', 'redfish', 'storage']
845 conn_profile = {"profileId": 0, "profileName": "", "profileDescription": "", "type": "DISCOVERY"}
846 creds_dict = {}
847 for p in proto_list:
848 if disc_config.get(p):
849 xproto = {"type": p.upper(),
850 "authType": "Basic",
851 "modified": False}
852 xproto['credentials'] = snake_dict_to_camel_dict(disc_config[p])
853 (xproto['credentials']).update(proto_add_dict.get(p, {}))
854 creds_dict[p] = xproto
855 # Special handling, duplicating wsman to redfish as in GUI
856 if p == 'wsman':
857 rf = xproto.copy()
858 rf['type'] = 'REDFISH'
859 creds_dict['redfish'] = rf
860 conn_profile['credentials'] = list(creds_dict.values())
861 return conn_profile
862
863
864 def get_discovery_config(module, rest_obj):
865 disc_cfg_list = []
866 proto_dev_map, dev_id_map = get_protocol_device_map(rest_obj)
867 discovery_config_list = module.params.get("discovery_config_targets")
868 for disc_config in discovery_config_list:
869 disc_cfg = {}
870 disc_cfg['DeviceType'] = list(
871 dev_id_map[dev] for dev in disc_config.get('device_types') if dev in dev_id_map.keys())
872 devices = list(set(disc_config.get('device_types')))
873 if len(devices) != len(disc_cfg['DeviceType']):
874 invalid_dev = set(devices) - set(dev_id_map.keys())
875 module.fail_json(msg=INVALID_DEVICES.format(','.join(invalid_dev)))
876 disc_cfg["DiscoveryConfigTargets"] = list({"NetworkAddressDetail": ip} for ip in disc_config["network_address_detail"])
877 conn_profile = get_connection_profile(disc_config)
878 given_protos = list(x["type"] for x in conn_profile['credentials'])
879 req_protos = []
880 for dev in disc_config.get('device_types'):
881 proto_dev_value = proto_dev_map.get(dev, [])
882 req_protos.extend(proto_dev_value)
883 if not (set(req_protos) & set(given_protos)):
884 module.fail_json(msg=ATLEAST_ONE_PROTOCOL, discovery_status=proto_dev_map)
885 disc_cfg["ConnectionProfile"] = json.dumps(conn_profile)
886 disc_cfg_list.append(disc_cfg)
887 return disc_cfg_list
888
889
890 def get_discovery_job(rest_obj, job_id):
891 resp = rest_obj.invoke_request('GET', DISCOVERY_JOBS_URI + "({0})".format(job_id))
892 djob = resp.json_data
893 nlist = list(djob)
894 for k in nlist:
895 if str(k).lower().startswith('@odata'):
896 djob.pop(k)
897 return djob
898
899
900 def exit_discovery(module, rest_obj, job_id):
901 msg = DISCOVERY_SCHEDULED
902 time.sleep(SETTLING_TIME)
903 djob = get_discovery_job(rest_obj, job_id)
904 detailed_job = []
905 if module.params.get("job_wait") and module.params.get('schedule') == 'RunNow':
906 job_message = discovery_job_tracking(rest_obj, job_id, job_wait_sec=module.params["job_wait_timeout"])
907 msg = job_message
908 ip_details, detailed_job = get_execution_details(rest_obj, job_id)
909 djob = get_discovery_job(rest_obj, job_id)
910 djob.update(ip_details)
911 if djob["JobStatusId"] == 2090 and not module.params.get("ignore_partial_failure"):
912 module.fail_json(msg=DISCOVERY_PARTIAL, discovery_status=djob, job_detailed_status=detailed_job)
913 if djob["JobStatusId"] == 2090 and module.params.get("ignore_partial_failure"):
914 module.exit_json(msg=JOB_TRACK_SUCCESS.format(JOB_STATUS_MAP[djob["JobStatusId"]]), discovery_status=djob,
915 job_detailed_status=detailed_job, changed=True)
916 if ip_details.get("Failed"):
917 module.fail_json(msg=JOB_TRACK_FAIL.format(JOB_STATUS_MAP[djob["JobStatusId"]]), discovery_status=djob,
918 job_detailed_status=detailed_job)
919 module.exit_json(msg=msg, discovery_status=djob, job_detailed_status=detailed_job, changed=True)
920
921
922 def create_discovery(module, rest_obj):
923 discovery_payload = {}
924 discovery_payload['DiscoveryConfigModels'] = get_discovery_config(module, rest_obj)
925 discovery_payload['Schedule'] = get_schedule(module)
926 other_params = get_other_discovery_payload(module)
927 discovery_payload.update(other_params)
928 resp = rest_obj.invoke_request("POST", CONFIG_GROUPS_URI, data=discovery_payload)
929 job_id = get_job_data(resp.json_data, rest_obj)
930 exit_discovery(module, rest_obj, job_id)
931
932
933 def update_modify_payload(discovery_modify_payload, current_payload, new_name=None):
934 parent_items = ["DiscoveryConfigGroupName",
935 "TrapDestination",
936 "CommunityString",
937 "DiscoveryStatusEmailRecipient",
938 "CreateGroup",
939 "UseAllProfiles"]
940 for key in parent_items:
941 if key not in discovery_modify_payload and key in current_payload:
942 discovery_modify_payload[key] = current_payload[key]
943 if not discovery_modify_payload.get("Schedule"):
944 exist_schedule = current_payload.get("Schedule", {})
945 schedule_payload = {}
946 if exist_schedule.get('Cron') == 'startnow':
947 schedule_payload['RunNow'] = True
948 schedule_payload['RunLater'] = False
949 schedule_payload['Cron'] = 'startnow'
950 else:
951 schedule_payload['RunNow'] = False
952 schedule_payload['RunLater'] = True
953 schedule_payload['Cron'] = exist_schedule.get('Cron')
954 discovery_modify_payload['Schedule'] = schedule_payload
955 discovery_modify_payload["DiscoveryConfigGroupId"] = current_payload["DiscoveryConfigGroupId"]
956 if new_name:
957 discovery_modify_payload["DiscoveryConfigGroupName"] = new_name
958
959
960 def modify_discovery(module, rest_obj, discov_list):
961 if len(discov_list) > 1:
962 dup_discovery = list(item["DiscoveryConfigGroupId"] for item in discov_list)
963 module.fail_json(msg=MULTI_DISCOVERY, discovery_ids=dup_discovery)
964 job_state_dict = get_discovery_states(rest_obj)
965 for d in discov_list:
966 if job_state_dict.get(d["DiscoveryConfigGroupId"]) == 2050:
967 module.fail_json(
968 msg=DISC_JOB_RUNNING.format(name=d["DiscoveryConfigGroupName"], id=d["DiscoveryConfigGroupId"]))
969 discovery_payload = {'DiscoveryConfigModels': get_discovery_config(module, rest_obj),
970 'Schedule': get_schedule(module)}
971 other_params = get_other_discovery_payload(module)
972 discovery_payload.update(other_params)
973 update_modify_payload(discovery_payload, discov_list[0], module.params.get("new_name"))
974 resp = rest_obj.invoke_request("PUT",
975 CONFIG_GROUPS_ID_URI.format(group_id=discovery_payload["DiscoveryConfigGroupId"]),
976 data=discovery_payload)
977 job_id = get_job_data(resp.json_data, rest_obj)
978 exit_discovery(module, rest_obj, job_id)
979
980
981 def delete_discovery(module, rest_obj, discov_list):
982 job_state_dict = get_discovery_states(rest_obj)
983 delete_ids = []
984 for d in discov_list:
985 if job_state_dict.get(d["DiscoveryConfigGroupId"]) == 2050:
986 module.fail_json(msg=DISC_JOB_RUNNING.format(name=d["DiscoveryConfigGroupName"],
987 id=d["DiscoveryConfigGroupId"]))
988 else:
989 delete_ids.append(d["DiscoveryConfigGroupId"])
990 delete_payload = {"DiscoveryGroupIds": delete_ids}
991 rest_obj.invoke_request('POST', DELETE_JOB_URI, data=delete_payload)
992 module.exit_json(msg=DISC_DEL_JOBS_SUCCESS.format(n=len(delete_ids)), changed=True)
993
994
995 def main():
996 http_creds = {"username": {"type": 'str', "required": True},
997 "password": {"type": 'str', "required": True, "no_log": True},
998 "domain": {"type": 'str'},
999 "retries": {"type": 'int', "default": 3},
1000 "timeout": {"type": 'int', "default": 60},
1001 "port": {"type": 'int', "default": 443},
1002 "cn_check": {"type": 'bool', "default": False},
1003 "ca_check": {"type": 'bool', "default": False},
1004 "certificate_data": {"type": 'str', "no_log": True}
1005 }
1006 snmp_creds = {"community": {"type": 'str', "required": True},
1007 "retries": {"type": 'int', "default": 3},
1008 "timeout": {"type": 'int', "default": 3},
1009 "port": {"type": 'int', "default": 161},
1010 }
1011 ssh_creds = {"username": {"type": 'str', "required": True},
1012 "password": {"type": 'str', "required": True, "no_log": True},
1013 "retries": {"type": 'int', "default": 3},
1014 "timeout": {"type": 'int', "default": 60},
1015 "port": {"type": 'int', "default": 22},
1016 "check_known_hosts": {"type": 'bool', "default": False},
1017 "is_sudo_user": {"type": 'bool', "default": False}
1018 }
1019 ipmi_creds = {"username": {"type": 'str', "required": True},
1020 "password": {"type": 'str', "required": True, "no_log": True},
1021 "retries": {"type": 'int', "default": 3},
1022 "timeout": {"type": 'int', "default": 60},
1023 "kgkey": {"type": 'str', "no_log": True}
1024 }
1025 discovery_config_model = {"device_types": {"required": True, 'type': 'list', "elements": 'str'},
1026 "network_address_detail": {"required": True, "type": 'list', "elements": 'str'},
1027 "wsman": {"type": 'dict', "options": http_creds,
1028 "required_if": [['ca_check', True, ('certificate_data',)]]},
1029 "storage": {"type": 'dict', "options": http_creds,
1030 "required_if": [['ca_check', True, ('certificate_data',)]]},
1031 "redfish": {"type": 'dict', "options": http_creds,
1032 "required_if": [['ca_check', True, ('certificate_data',)]]},
1033 "vmware": {"type": 'dict', "options": http_creds,
1034 "required_if": [['ca_check', True, ('certificate_data',)]]},
1035 "snmp": {"type": 'dict', "options": snmp_creds},
1036 "ssh": {"type": 'dict', "options": ssh_creds},
1037 "ipmi": {"type": 'dict', "options": ipmi_creds},
1038 }
1039 specs = {
1040 "discovery_job_name": {"type": 'str'},
1041 "discovery_id": {"type": 'int'},
1042 "state": {"default": "present", "choices": ['present', 'absent']},
1043 "new_name": {"type": 'str'},
1044 "discovery_config_targets":
1045 {"type": 'list', "elements": 'dict', "options": discovery_config_model,
1046 "required_one_of": [
1047 ('wsman', 'storage', 'redfish', 'vmware', 'snmp', 'ssh', 'ipmi')
1048 ]},
1049 "schedule": {"default": 'RunNow', "choices": ['RunNow', 'RunLater']},
1050 "cron": {"type": 'str'},
1051 "job_wait": {"type": 'bool', "default": True},
1052 "job_wait_timeout": {"type": 'int', "default": 10800},
1053 "trap_destination": {"type": 'bool', "default": False},
1054 "community_string": {"type": 'bool', "default": False},
1055 "email_recipient": {"type": 'str'},
1056 "ignore_partial_failure": {"type": 'bool', "default": False}
1057 }
1058
1059 module = OmeAnsibleModule(
1060 argument_spec=specs,
1061 required_if=[
1062 ['state', 'present', ('discovery_config_targets',)],
1063 ['schedule', 'RunLater', ('cron',)]
1064 ],
1065 required_one_of=[('discovery_job_name', 'discovery_id')],
1066 mutually_exclusive=[('discovery_job_name', 'discovery_id')],
1067 supports_check_mode=False
1068 )
1069 try:
1070 with RestOME(module.params, req_session=True) as rest_obj:
1071 discov_list = check_existing_discovery(module, rest_obj)
1072 if module.params.get('state') == 'absent':
1073 if discov_list:
1074 delete_discovery(module, rest_obj, discov_list)
1075 module.exit_json(msg=NO_CHANGES_MSG)
1076 else:
1077 if discov_list:
1078 modify_discovery(module, rest_obj, discov_list)
1079 else:
1080 if module.params.get('discovery_id'):
1081 module.fail_json(msg=INVALID_DISCOVERY_ID)
1082 create_discovery(module, rest_obj)
1083 except HTTPError as err:
1084 module.fail_json(msg=str(err), error_info=json.load(err))
1085 except URLError as err:
1086 module.exit_json(msg=str(err), unreachable=True)
1087 except (IOError, ValueError, TypeError, ConnectionError, SSLValidationError, OSError) as err:
1088 module.fail_json(msg=str(err))
1089
1090
1091 if __name__ == "__main__":
1092 main()