Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.4
7 # Copyright (C) 2019-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 from __future__ import (absolute_import, division, print_function)
13 __metaclass__ = type
14
15 DOCUMENTATION = r'''
16 ---
17 module: ome_device_info
18 short_description: Retrieves the information of devices inventoried by OpenManage Enterprise
19 version_added: "2.0.0"
20 description:
21 - This module retrieves the list of devices in the inventory of OpenManage Enterprise along with the details of each device.
22 extends_documentation_fragment:
23 - dellemc.openmanage.ome_auth_options
24 options:
25 fact_subset:
26 description:
27 - C(basic_inventory) returns the list of the devices.
28 - C(detailed_inventory) returns the inventory details of specified devices.
29 - C(subsystem_health) returns the health status of specified devices.
30 type: str
31 choices: [basic_inventory, detailed_inventory, subsystem_health ]
32 default: basic_inventory
33 system_query_options:
34 description:
35 - I(system_query_options) applicable for the choices of the fact_subset. Either I(device_id) or I(device_service_tag)
36 is mandatory for C(detailed_inventory) and C(subsystem_health) or both can be applicable.
37 type: dict
38 suboptions:
39 device_id:
40 description:
41 - A list of unique identifier is applicable
42 for C(detailed_inventory) and C(subsystem_health).
43 type: list
44 elements: int
45 device_service_tag:
46 description:
47 - A list of service tags are applicable for C(detailed_inventory)
48 and C(subsystem_health).
49 type: list
50 elements: str
51 inventory_type:
52 description:
53 - For C(detailed_inventory), it returns details of the specified inventory type.
54 type: str
55 filter:
56 description:
57 - For C(basic_inventory), it filters the collection of devices.
58 I(filter) query format should be aligned with OData standards.
59 type: str
60
61 requirements:
62 - "python >= 3.9.6"
63 author:
64 - "Sajna Shetty (@Sajna-Shetty)"
65 - "Felix Stephen (@felixs88)"
66 - "Sapana Gupta (@sapana05)"
67 notes:
68 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
69 - This module supports C(check_mode).
70 '''
71
72 EXAMPLES = """
73 ---
74 - name: Retrieve basic inventory of all devices
75 dellemc.openmanage.ome_device_info:
76 hostname: "192.168.0.1"
77 username: "username"
78 password: "password"
79 ca_path: "/path/to/ca_cert.pem"
80
81 - name: Retrieve basic inventory for devices identified by IDs 33333 or 11111 using filtering
82 dellemc.openmanage.ome_device_info:
83 hostname: "192.168.0.1"
84 username: "username"
85 password: "password"
86 ca_path: "/path/to/ca_cert.pem"
87 fact_subset: "basic_inventory"
88 system_query_options:
89 filter: "Id eq 33333 or Id eq 11111"
90
91 - name: Retrieve inventory details of specified devices identified by IDs 11111 and 22222
92 dellemc.openmanage.ome_device_info:
93 hostname: "192.168.0.1"
94 username: "username"
95 password: "password"
96 ca_path: "/path/to/ca_cert.pem"
97 fact_subset: "detailed_inventory"
98 system_query_options:
99 device_id:
100 - 11111
101 - 22222
102
103 - name: Retrieve inventory details of specified devices identified by service tags MXL1234 and MXL4567
104 dellemc.openmanage.ome_device_info:
105 hostname: "192.168.0.1"
106 username: "username"
107 password: "password"
108 ca_path: "/path/to/ca_cert.pem"
109 fact_subset: "detailed_inventory"
110 system_query_options:
111 device_service_tag:
112 - MXL1234
113 - MXL4567
114
115 - name: Retrieve details of specified inventory type of specified devices identified by ID and service tags
116 dellemc.openmanage.ome_device_info:
117 hostname: "192.168.0.1"
118 username: "username"
119 password: "password"
120 ca_path: "/path/to/ca_cert.pem"
121 fact_subset: "detailed_inventory"
122 system_query_options:
123 device_id:
124 - 11111
125 device_service_tag:
126 - MXL1234
127 - MXL4567
128 inventory_type: "serverDeviceCards"
129
130 - name: Retrieve subsystem health of specified devices identified by service tags
131 dellemc.openmanage.ome_device_info:
132 hostname: "192.168.0.1"
133 username: "username"
134 password: "password"
135 ca_path: "/path/to/ca_cert.pem"
136 fact_subset: "subsystem_health"
137 system_query_options:
138 device_service_tag:
139 - MXL1234
140 - MXL4567
141 """
142
143 RETURN = '''
144 ---
145 msg:
146 type: str
147 description: Over all device information status.
148 returned: on error
149 sample: "Failed to fetch the device information"
150 device_info:
151 type: dict
152 description: Returns the information collected from the Device.
153 returned: success
154 sample: {
155 "value": [
156 {
157 "Actions": null,
158 "AssetTag": null,
159 "ChassisServiceTag": null,
160 "ConnectionState": true,
161 "DeviceManagement": [
162 {
163 "DnsName": "dnsname.host.com",
164 "InstrumentationName": "MX-12345",
165 "MacAddress": "11:10:11:10:11:10",
166 "ManagementId": 12345,
167 "ManagementProfile": [
168 {
169 "HasCreds": 0,
170 "ManagementId": 12345,
171 "ManagementProfileId": 12345,
172 "ManagementURL": "https://192.168.0.1:443",
173 "Status": 1000,
174 "StatusDateTime": "2019-01-21 06:30:08.501"
175 }
176 ],
177 "ManagementType": 2,
178 "NetworkAddress": "192.168.0.1"
179 }
180 ],
181 "DeviceName": "MX-0003I",
182 "DeviceServiceTag": "MXL1234",
183 "DeviceSubscription": null,
184 "LastInventoryTime": "2019-01-21 06:30:08.501",
185 "LastStatusTime": "2019-01-21 06:30:02.492",
186 "ManagedState": 3000,
187 "Model": "PowerEdge MX7000",
188 "PowerState": 17,
189 "SlotConfiguration": {},
190 "Status": 4000,
191 "SystemId": 2031,
192 "Type": 2000
193 }
194 ]
195 }
196 '''
197
198 from ssl import SSLError
199
200 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
201 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import get_all_data_with_pagination
202 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
203 from ansible.module_utils.urls import ConnectionError, SSLValidationError
204
205 DEVICES_INVENTORY_DETAILS = "detailed_inventory"
206 DEVICES_SUBSYSTEM_HEALTH = "subsystem_health"
207 DEVICES_INVENTORY_TYPE = "inventory_type"
208 DEVICE_LIST = "basic_inventory"
209 DESC_HTTP_ERROR = "HTTP Error 404: Not Found"
210 device_fact_error_report = {}
211
212 DEVICE_RESOURCE_COLLECTION = {
213 DEVICE_LIST: {"resource": "DeviceService/Devices"},
214 DEVICES_INVENTORY_DETAILS: {"resource": "DeviceService/Devices({Id})/InventoryDetails"},
215 DEVICES_INVENTORY_TYPE: {"resource": "DeviceService/Devices({Id})/InventoryDetails('{InventoryType}')"},
216 DEVICES_SUBSYSTEM_HEALTH: {"resource": "DeviceService/Devices({Id})/SubSystemHealth"},
217 }
218
219
220 def update_device_details_with_filtering(missing_service_tags, service_tag_dict, rest_obj):
221 """
222 This is a workaround solutions.
223 Use filtering query, in case fetching all report list fails for some reason.
224 Updates service_tag_dict if filtering request is success.
225 :param missing_service_tags: Service tags which are unable to fetch from pagination request.
226 :param service_tag_dict: this contains device id mapping with tags
227 :param rest_obj: ome connection object
228 :return: None.
229 """
230 try:
231 for tag in missing_service_tags:
232 query = "DeviceServiceTag eq '{0}'".format(tag)
233 query_param = {"$filter": query}
234 resp = rest_obj.invoke_request('GET', DEVICE_RESOURCE_COLLECTION[DEVICE_LIST]["resource"], query_param=query_param)
235 value = resp.json_data["value"]
236 if value and value[0]["DeviceServiceTag"] == tag:
237 service_tag_dict.update({value[0]["Id"]: value[0]["DeviceServiceTag"]})
238 missing_service_tags.remove(tag)
239 except (URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError) as err:
240 raise err
241
242
243 def _get_device_id_from_service_tags(service_tags, rest_obj):
244 """
245 Get device ids from device service tag
246 Returns :dict : device_id to service_tag map
247 :arg service_tags: service tag
248 :arg rest_obj: RestOME class object in case of request with session.
249 :returns: dict eg: {1345:"MXL1245"}
250 """
251 device_list = rest_obj.get_all_report_details(DEVICE_RESOURCE_COLLECTION[DEVICE_LIST]["resource"])["report_list"]
252 service_tag_dict = {}
253 for item in device_list:
254 if item["DeviceServiceTag"] in service_tags:
255 service_tag_dict.update({item["Id"]: item["DeviceServiceTag"]})
256 available_service_tags = service_tag_dict.values()
257 missing_service_tags = list(set(service_tags) - set(available_service_tags))
258 update_device_details_with_filtering(missing_service_tags, service_tag_dict, rest_obj)
259 device_fact_error_report.update(dict((tag, DESC_HTTP_ERROR) for tag in missing_service_tags))
260 return service_tag_dict
261
262
263 def is_int(val):
264 """check when device_id numeric represented value is int"""
265 try:
266 int(val)
267 return True
268 except ValueError:
269 return False
270
271
272 def _check_duplicate_device_id(device_id_list, service_tag_dict):
273 """If service_tag is duplicate of device_id, then updates the message as Duplicate report
274 :arg1: device_id_list : list of device_id
275 :arg2: service_tag_id_dict: dictionary of device_id to service tag map"""
276 if device_id_list:
277 device_id_represents_int = [int(device_id) for device_id in device_id_list if device_id and is_int(device_id)]
278 common_val = list(set(device_id_represents_int) & set(service_tag_dict.keys()))
279 for device_id in common_val:
280 device_fact_error_report.update(
281 {service_tag_dict[device_id]: "Duplicate report of device_id: {0}".format(device_id)})
282 del service_tag_dict[device_id]
283
284
285 def _get_device_identifier_map(module_params, rest_obj):
286 """
287 Builds the identifiers mapping
288 :returns: the dict of device_id to server_tag map
289 eg: {"device_id":{1234: None},"device_service_tag":{1345:"MXL1234"}}"""
290 system_query_options_param = module_params.get("system_query_options")
291 device_id_service_tag_dict = {}
292 if system_query_options_param is not None:
293 device_id_list = system_query_options_param.get("device_id")
294 device_service_tag_list = system_query_options_param.get("device_service_tag")
295 if device_id_list:
296 device_id_dict = dict((device_id, None) for device_id in list(set(device_id_list)))
297 device_id_service_tag_dict["device_id"] = device_id_dict
298 if device_service_tag_list:
299 service_tag_dict = _get_device_id_from_service_tags(device_service_tag_list,
300 rest_obj)
301
302 _check_duplicate_device_id(device_id_list, service_tag_dict)
303 device_id_service_tag_dict["device_service_tag"] = service_tag_dict
304 return device_id_service_tag_dict
305
306
307 def _get_query_parameters(module_params):
308 """
309 Builds query parameter
310 :returns: dictionary, which is applicable builds the query format
311 eg : {"$filter":"Type eq 2000"}
312 """
313 system_query_options_param = module_params.get("system_query_options")
314 query_parameter = None
315 if system_query_options_param:
316 filter_by_val = system_query_options_param.get("filter")
317 if filter_by_val:
318 query_parameter = {"$filter": filter_by_val}
319 return query_parameter
320
321
322 def _get_resource_parameters(module_params, rest_obj):
323 """
324 Identifies the resource path by different states
325 :returns: dictionary containing identifier with respective resource path
326 eg:{"device_id":{1234:""DeviceService/Devices(1234)/InventoryDetails"},
327 "device_service_tag":{"MXL1234":"DeviceService/Devices(1345)/InventoryDetails"}}
328 """
329 fact_subset = module_params["fact_subset"]
330 path_dict = {}
331 if fact_subset != DEVICE_LIST:
332 inventory_type = None
333 device_id_service_tag_dict = _get_device_identifier_map(module_params, rest_obj)
334 if fact_subset == DEVICES_INVENTORY_DETAILS:
335 system_query_options = module_params.get("system_query_options")
336 inventory_type = system_query_options.get(DEVICES_INVENTORY_TYPE)
337 path_identifier = DEVICES_INVENTORY_TYPE if inventory_type else fact_subset
338 for identifier_type, identifier_dict in device_id_service_tag_dict.items():
339 path_dict[identifier_type] = {}
340 for device_id, service_tag in identifier_dict.items():
341 key_identifier = service_tag if identifier_type == "device_service_tag" else device_id
342 path = DEVICE_RESOURCE_COLLECTION[path_identifier]["resource"].format(Id=device_id,
343 InventoryType=inventory_type)
344 path_dict[identifier_type].update({key_identifier: path})
345 else:
346 path_dict.update({DEVICE_LIST: DEVICE_RESOURCE_COLLECTION[DEVICE_LIST]["resource"]})
347 return path_dict
348
349
350 def _check_mutually_inclusive_arguments(val, module_params, required_args):
351 """"
352 Throws error if arguments detailed_inventory, subsystem_health
353 not exists with qualifier device_id or device_service_tag"""
354 system_query_options_param = module_params.get("system_query_options")
355 if system_query_options_param is None or (system_query_options_param is not None and not any(
356 system_query_options_param.get(qualifier) for qualifier in required_args)):
357 raise ValueError("One of the following {0} is required for {1}".format(required_args, val))
358
359
360 def _validate_inputs(module_params):
361 """validates input parameters"""
362 fact_subset = module_params["fact_subset"]
363 if fact_subset != "basic_inventory":
364 _check_mutually_inclusive_arguments(fact_subset, module_params, ["device_id", "device_service_tag"])
365
366
367 def main():
368 system_query_options = {"type": 'dict', "required": False, "options": {
369 "device_id": {"type": 'list', "elements": 'int'},
370 "device_service_tag": {"type": 'list', "elements": 'str'},
371 "inventory_type": {"type": 'str'},
372 "filter": {"type": 'str', "required": False},
373 }}
374
375 specs = {
376 "fact_subset": {"required": False, "default": "basic_inventory",
377 "choices": ['basic_inventory', 'detailed_inventory', 'subsystem_health']},
378 "system_query_options": system_query_options,
379 }
380
381 module = OmeAnsibleModule(
382 argument_spec=specs,
383 required_if=[['fact_subset', 'detailed_inventory', ['system_query_options']],
384 ['fact_subset', 'subsystem_health', ['system_query_options']]],
385 supports_check_mode=True)
386
387 try:
388 _validate_inputs(module.params)
389 with RestOME(module.params, req_session=True) as rest_obj:
390 device_facts = _get_resource_parameters(module.params, rest_obj)
391 resp_status = []
392 if device_facts.get("basic_inventory"):
393 query_param = _get_query_parameters(module.params)
394 if query_param is not None:
395 device_report = get_all_data_with_pagination(rest_obj, device_facts["basic_inventory"], query_param)
396 if not device_report.get("report_list", []):
397 module.exit_json(msg="No devices present.", device_info=[])
398 device_facts = {"@odata.context": device_report["resp_obj"].json_data["@odata.context"],
399 "@odata.count": len(device_report["report_list"]),
400 "value": device_report["report_list"]}
401 resp_status.append(device_report["resp_obj"].status_code)
402 else:
403 device_report = rest_obj.get_all_report_details(DEVICE_RESOURCE_COLLECTION[DEVICE_LIST]["resource"])
404 device_facts = {"@odata.context": device_report["resp_obj"].json_data["@odata.context"],
405 "@odata.count": len(device_report["report_list"]),
406 "value": device_report["report_list"]}
407 resp_status.append(device_report["resp_obj"].status_code)
408 if device_facts["@odata.count"] == 0:
409 module.exit_json(msg="No devices present.", device_info=[])
410 else:
411 for identifier_type, path_dict_map in device_facts.items():
412 for identifier, path in path_dict_map.items():
413 try:
414 resp = rest_obj.invoke_request('GET', path)
415 data = resp.json_data
416 resp_status.append(resp.status_code)
417 except HTTPError as err:
418 data = str(err)
419 path_dict_map[identifier] = data
420 if any(device_fact_error_report):
421 if "device_service_tag" in device_facts:
422 device_facts["device_service_tag"].update(device_fact_error_report)
423 else:
424 device_facts["device_service_tag"] = device_fact_error_report
425 if 200 in resp_status:
426 module.exit_json(device_info=device_facts)
427 else:
428 module.exit_json(msg="Unable to fetch the device information because the requested device id(s) or "
429 "device service tag(s) does not exist.",
430 device_info=[])
431
432 except (URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError, SSLError, OSError) as err:
433 module.exit_json(msg=str(err), failed=True)
434
435
436 if __name__ == '__main__':
437 main()