Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_devices.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) 2022-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
14 __metaclass__ = type
15
16 DOCUMENTATION = """
17 ---
18 module: ome_devices
19 short_description: Perform device-specific operations on target devices
20 description: Perform device-specific operations such as refresh inventory, clear iDRAC job queue, and reset iDRAC from OpenManage Enterprise.
21 version_added: 6.1.0
22 extends_documentation_fragment:
23 - dellemc.openmanage.oment_auth_options
24 options:
25 device_service_tags:
26 description:
27 - Service tag of the target devices.
28 - This is mutually exclusive with I(device_ids).
29 type: list
30 elements: str
31 device_ids:
32 description:
33 - IDs of the target devices.
34 - This is mutually exclusive with I(device_service_tags).
35 type: list
36 elements: int
37 state:
38 description:
39 - C(present) Allows to perform the I(device_action) on the target devices.
40 - "C(absent) Removes the device from OpenManage Enterprise. Job is not triggered. I(job_wait), I(job_schedule),
41 I(job_name), and I(job_description) are not applicable to this operation."
42 type: str
43 choices: [present, absent]
44 default: present
45 device_action:
46 description:
47 - C(refresh_inventory) refreshes the inventory on the target devices.
48 - C(reset_idrac) Triggers a reset on the target iDRACs.
49 - C(clear_idrac_job_queue) Clears the job queue on the target iDRACs.
50 - A job is triggered for each action.
51 type: str
52 choices: [refresh_inventory, reset_idrac, clear_idrac_job_queue]
53 default: refresh_inventory
54 job_wait:
55 description:
56 - Provides an option to wait for the job completion.
57 - This option is applicable when I(state) is C(present).
58 - This is applicable when I(job_schedule) is C(startnow).
59 type: bool
60 default: true
61 job_wait_timeout:
62 description:
63 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
64 - This option is applicable when I(job_wait) is C(true).
65 type: int
66 default: 1200
67 job_schedule:
68 description: Provide the cron string to schedule the job.
69 type: str
70 default: startnow
71 job_name:
72 description: Optional name for the job.
73 type: str
74 job_description:
75 description: Optional description for the job.
76 type: str
77 requirements:
78 - "python >= 3.9.6"
79 author:
80 - Jagadeesh N V(@jagadeeshnv)
81 - ShivamSh3(@ShivamSh3)
82 notes:
83 - For C(idrac_reset), the job triggers only the iDRAC reset operation and does not track the complete reset cycle.
84 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
85 - This module supports C(check_mode).
86 """
87
88 EXAMPLES = """
89 ---
90 - name: Refresh Inventory
91 dellemc.openmanage.ome_devices:
92 hostname: "192.168.0.1"
93 username: "username"
94 password: "password"
95 ca_path: "/path/to/ca_cert.pem"
96 device_action: refresh_inventory
97 device_service_tags:
98 - SVCTAG1
99
100 - name: Clear iDRAC job queue
101 dellemc.openmanage.ome_devices:
102 hostname: "192.168.0.1"
103 username: "username"
104 password: "password"
105 ca_path: "/path/to/ca_cert.pem"
106 device_action: clear_idrac_job_queue
107 device_service_tags:
108 - SVCTAG1
109
110 - name: Reset iDRAC using the service tag
111 dellemc.openmanage.ome_devices:
112 hostname: "192.168.0.1"
113 username: "username"
114 password: "password"
115 ca_path: "/path/to/ca_cert.pem"
116 device_action: reset_idrac
117 device_service_tags:
118 - SVCTAG1
119
120 - name: Remove devices using servicetags
121 dellemc.openmanage.ome_devices:
122 hostname: "192.168.0.1"
123 username: "username"
124 password: "password"
125 ca_path: "/path/to/ca_cert.pem"
126 state: absent
127 device_service_tags:
128 - SVCTAG1
129 - SVCTAF2
130
131 - name: Remove devices using IDs
132 dellemc.openmanage.ome_devices:
133 hostname: "192.168.0.1"
134 username: "username"
135 password: "password"
136 ca_path: "/path/to/ca_cert.pem"
137 state: absent
138 device_ids:
139 - 10235
140 """
141
142 RETURN = """
143 ---
144 msg:
145 type: str
146 description: Overall status of the devices operation.
147 returned: always
148 sample: "Successfully removed the device(s)."
149 job:
150 type: dict
151 description: Job details of the devices operation.
152 returned: success
153 sample: {
154 "Id": 14874,
155 "JobName": "Refresh inventory",
156 "JobDescription": "The Refresh inventory task initiated from OpenManage Ansible Modules for devices with the ids '13216'.",
157 "Schedule": "startnow",
158 "State": "Enabled",
159 "CreatedBy": "admin",
160 "UpdatedBy": null,
161 "Visible": true,
162 "Editable": true,
163 "Builtin": false,
164 "UserGenerated": true,
165 "Targets": [
166 {
167 "JobId": 14874,
168 "Id": 13216,
169 "Data": "",
170 "TargetType": {
171 "Id": 1000,
172 "Name": "DEVICE"
173 }
174 }
175 ],
176 "Params": [
177 {
178 "JobId": 14874,
179 "Key": "action",
180 "Value": "CONFIG_INVENTORY"
181 },
182 {
183 "JobId": 14874,
184 "Key": "isCollectDriverInventory",
185 "Value": "true"
186 }
187 ],
188 "LastRunStatus": {
189 "@odata.type": "#JobService.JobStatus",
190 "Id": 2060,
191 "Name": "Completed"
192 },
193 "JobType": {
194 "@odata.type": "#JobService.JobType",
195 "Id": 8,
196 "Name": "Inventory_Task",
197 "Internal": false
198 },
199 "JobStatus": {
200 "@odata.type": "#JobService.JobStatus",
201 "Id": 2020,
202 "Name": "Scheduled"
203 },
204 "[email protected]": "/api/JobService/Jobs(14874)/ExecutionHistories",
205 "LastExecutionDetail": {
206 "@odata.id": "/api/JobService/Jobs(14874)/LastExecutionDetail"
207 }
208 }
209 error_info:
210 description: Details of the HTTP Error.
211 returned: on HTTP error
212 type: dict
213 sample: {
214 "error": {
215 "code": "Base.1.0.GeneralError",
216 "message": "A general error has occurred. See ExtendedInfo for more information.",
217 "@Message.ExtendedInfo": [
218 {
219 "MessageId": "CGEN1002",
220 "RelatedProperties": [],
221 "Message": "Unable to complete the operation because the requested URI is invalid.",
222 "MessageArgs": [],
223 "Severity": "Critical",
224 "Resolution": "Enter a valid URI and retry the operation."
225 }
226 ]
227 }
228 }
229 """
230
231 import json
232 from ssl import SSLError
233 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
234 from ansible.module_utils.urls import ConnectionError
235 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
236 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import strip_substr_dict, job_tracking
237 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import CHANGES_MSG, NO_CHANGES_MSG
238
239 DEVICE_URI = "DeviceService/Devices"
240 JOBS_URI = "JobService/Jobs"
241 JOB_URI = "JobService/Jobs({job_id})"
242 RUN_JOB_URI = "JobService/Actions/JobService.RunJobs"
243 LAST_EXEC = "JobService/Jobs({job_id})/LastExecutionDetail"
244 DELETE_DEVICES_URI = "DeviceService/Actions/DeviceService.RemoveDevices"
245 DELETE_SUCCESS = "The devices(s) are removed successfully."
246 INVALID_DEV_ST = "Unable to complete the operation because the entered target device(s) '{0}' are invalid."
247 JOB_DESC = "The {0} task initiated from OpenManage Ansible Modules for devices with the ids '{1}'."
248 APPLY_TRIGGERED = "Successfully initiated the device action job."
249 JOB_SCHEDULED = "The job is scheduled successfully."
250 SUCCESS_MSG = "The device operation is performed successfully."
251 TIMEOUT_NEGATIVE_MSG = "The parameter `job_wait_timeout` value cannot be negative or zero."
252
253 all_device_types = [1000, 2000, 4000, 5000, 7000, 8000, 9001]
254 device_type_map = {"refresh_inventory": all_device_types, "reset_idrac": [1000], "clear_idrac_job_queue": [1000]}
255 job_type_map = {"refresh_inventory": 8, "reset_idrac": 3, "clear_idrac_job_queue": 3}
256 jtype_map = {3: "DeviceAction_Task", 8: "Inventory_Task"}
257 job_params_map = {"refresh_inventory": {"action": "CONFIG_INVENTORY",
258 "isCollectDriverInventory": "true"},
259 "reset_idrac": {"operationName": "RESET_IDRAC"},
260 "clear_idrac_job_queue": {"operationName": "REMOTE_RACADM_EXEC",
261 "Command": "jobqueue delete -i JID_CLEARALL_FORCE",
262 "CommandTimeout": "60", "deviceTypes": "1000"}}
263 jobname_map = {"refresh_inventory": "Refresh inventory", "reset_idrac": "Reset iDRAC",
264 "clear_idrac_job_queue": "Clear iDRAC job queue"}
265
266
267 def get_dev_ids(module, rest_obj, types):
268 invalids = set()
269 sts = module.params.get('device_ids')
270 param = "{0} eq {1}"
271 srch = 'Id'
272 if not sts:
273 sts = module.params.get('device_service_tags')
274 param = "{0} eq '{1}'"
275 srch = 'Identifier'
276 devs = []
277 for st in sts:
278 resp = rest_obj.invoke_request("GET", DEVICE_URI, query_param={"$filter": param.format(srch, st)})
279 val = resp.json_data.get('value')
280 if not val:
281 invalids.add(st)
282 for v in val:
283 if v[srch] == st:
284 if v["Type"] in types:
285 devs.extend(val)
286 else:
287 invalids.add(st)
288 break
289 else:
290 invalids.add(st)
291 valids = [(dv.get('Id')) for dv in devs]
292 return valids, invalids
293
294
295 def delete_devices(module, rest_obj, valid_ids):
296 if module.check_mode:
297 module.exit_json(msg=CHANGES_MSG, changed=True)
298 payload = {"DeviceIds": list(valid_ids)}
299 rest_obj.invoke_request('POST', DELETE_DEVICES_URI, data=payload)
300 module.exit_json(msg=DELETE_SUCCESS, changed=True)
301
302
303 def update_common_job(module, payload, task, valid_ids):
304 payload["Schedule"] = module.params.get('job_schedule')
305 if module.params.get('job_name'):
306 payload["JobName"] = module.params.get('job_name')
307 else:
308 payload["JobName"] = jobname_map.get(task)
309 if module.params.get('job_description'):
310 payload["JobDescription"] = module.params.get('job_description')
311 else:
312 payload["JobDescription"] = JOB_DESC.format(jobname_map.get(task), ",".join(map(str, valid_ids)))
313
314
315 def check_similar_job(rest_obj, payload):
316 query_param = {"$filter": "JobType/Id eq {0}".format(payload['JobType'])}
317 job_resp = rest_obj.invoke_request("GET", JOBS_URI, query_param=query_param)
318 job_list = job_resp.json_data.get('value', [])
319 for jb in job_list:
320 if jb['JobName'] == payload['JobName'] and jb['JobDescription'] == payload['JobDescription'] and \
321 jb['Schedule'] == payload['Schedule']:
322 jb_prm = dict((k.get('Key'), k.get('Value')) for k in jb.get('Params'))
323 if not jb_prm == payload.get('Params'):
324 continue
325 trgts = dict((t.get('Id'), t.get('TargetType').get('Name')) for t in jb.get('Targets'))
326 if not trgts == payload.get('Targets'):
327 continue
328 return jb
329 return {}
330
331
332 def job_wait(module, rest_obj, job):
333 mparams = module.params
334 if mparams.get('job_schedule') != 'startnow':
335 module.exit_json(changed=True, msg=JOB_SCHEDULED, job=strip_substr_dict(job))
336 if not module.params.get("job_wait"):
337 module.exit_json(changed=True, msg=APPLY_TRIGGERED, job=strip_substr_dict(job))
338 else:
339 job_msg = SUCCESS_MSG
340 job_failed, msg, job_dict, wait_time = job_tracking(
341 rest_obj, JOB_URI.format(job_id=job['Id']), max_job_wait_sec=module.params.get('job_wait_timeout'),
342 initial_wait=3)
343 if job_failed:
344 try:
345 job_resp = rest_obj.invoke_request('GET', LAST_EXEC.format(job_id=job['Id']))
346 msg = job_resp.json_data.get("Value")
347 job_msg = msg.replace('\n', ' ')
348 except Exception:
349 job_msg = msg
350 module.exit_json(failed=job_failed, msg=job_msg, job=strip_substr_dict(job), changed=True)
351
352
353 def get_task_payload(task):
354 taskload = {}
355 taskload.update({"JobType": job_type_map.get(task, 8)})
356 taskload.update({"Params": job_params_map.get(task, {})})
357 return taskload
358
359
360 def get_payload_method(task, valid_ids):
361 payload = get_task_payload(task)
362 targets = dict((dv, "DEVICE") for dv in valid_ids)
363 payload["Targets"] = targets
364 return payload, "POST", JOBS_URI
365
366
367 def formalize_job_payload(payload):
368 payload["Id"] = 0
369 payload["State"] = "Enabled"
370 prms = payload['Params']
371 payload['Params'] = [({"Key": k, "Value": v}) for k, v in prms.items()]
372 trgts = payload['Targets']
373 payload['Targets'] = [({"Id": k, "Data": "", "TargetType": {"Id": 1000, "Name": v}}) for k, v in trgts.items()]
374 jtype = payload["JobType"]
375 payload["JobType"] = {"Id": jtype, "Name": jtype_map.get(jtype)}
376
377
378 def perform_device_tasks(module, rest_obj, valid_ids):
379 task = module.params.get("device_action")
380 payload, method, uri = get_payload_method(task, valid_ids)
381 update_common_job(module, payload, task, valid_ids)
382 job = check_similar_job(rest_obj, payload)
383 if not job:
384 formalize_job_payload(payload)
385 if module.check_mode:
386 module.exit_json(msg=CHANGES_MSG, changed=True)
387 resp = rest_obj.invoke_request("POST", JOBS_URI, data=payload, api_timeout=60)
388 job_wait(module, rest_obj, resp.json_data)
389 else:
390 if module.params.get('job_schedule') == 'startnow' and job["LastRunStatus"]['Id'] != 2050:
391 if module.check_mode:
392 module.exit_json(msg=CHANGES_MSG, changed=True)
393 resp = rest_obj.invoke_request("POST", RUN_JOB_URI, data={"JobIds": [job['Id']]})
394 job_wait(module, rest_obj, job)
395 module.exit_json(msg=NO_CHANGES_MSG, job=strip_substr_dict(job))
396
397
398 def main():
399 specs = {
400 "device_service_tags": {"type": "list", "elements": 'str'},
401 "device_ids": {"type": "list", "elements": 'int'},
402 "state": {"type": "str", "choices": ["present", "absent"], "default": "present"},
403 "device_action": {"type": "str", "choices": ["refresh_inventory", "reset_idrac", "clear_idrac_job_queue"],
404 "default": 'refresh_inventory'},
405 "job_wait": {"type": "bool", "default": True},
406 "job_wait_timeout": {"type": "int", "default": 1200},
407 "job_schedule": {"type": "str", "default": 'startnow'},
408 "job_name": {"type": "str"},
409 "job_description": {"type": "str"},
410 # "job_params": {"type": "dict"}
411 }
412
413 module = OmeAnsibleModule(
414 argument_spec=specs,
415 required_if=[],
416 mutually_exclusive=[
417 ("device_service_tags", "device_ids"),
418 ],
419 required_one_of=[("device_service_tags", "device_ids")],
420 supports_check_mode=True
421 )
422 try:
423 if module.params.get("job_wait") and module.params.get("job_wait_timeout") <= 0:
424 module.exit_json(msg=TIMEOUT_NEGATIVE_MSG, failed=True)
425 with RestOME(module.params, req_session=True) as rest_obj:
426 if module.params.get("state") == 'present':
427 valids, invalids = get_dev_ids(module, rest_obj,
428 device_type_map.get(module.params.get("device_action")))
429 if invalids:
430 module.exit_json(failed=True, msg=INVALID_DEV_ST.format(",".join(map(str, invalids))))
431 perform_device_tasks(module, rest_obj, valids)
432 else:
433 valids, invalids = get_dev_ids(module, rest_obj, all_device_types)
434 if not valids:
435 module.exit_json(msg=NO_CHANGES_MSG)
436 delete_devices(module, rest_obj, valids)
437 except HTTPError as err:
438 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
439 except URLError as err:
440 module.exit_json(msg=str(err), unreachable=True)
441 except (IOError, ValueError, SSLError, TypeError, ConnectionError, AttributeError, IndexError, KeyError,
442 OSError) as err:
443 module.exit_json(msg=str(err), failed=True)
444
445
446 if __name__ == '__main__':
447 main()