Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.1
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
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = """
17 ---
18 module: idrac_virtual_media
19 short_description: Configure the Remote File Share settings.
20 version_added: "6.3.0"
21 description:
22 - This module allows to configure Remote File Share settings.
23 extends_documentation_fragment:
24 - dellemc.openmanage.idrac_x_auth_options
25 options:
26 virtual_media:
27 required: true
28 type: list
29 elements: dict
30 description: Details of the Remote File Share.
31 suboptions:
32 insert:
33 required: true
34 type: bool
35 description:
36 - C(true) connects the remote image file.
37 - C(false) ejects the remote image file if connected.
38 image:
39 type: path
40 description:
41 - The path of the image file. The supported file types are .img and .iso.
42 - The file name with .img extension is redirected as a virtual floppy and a file name with .iso extension is
43 redirected as a virtual CDROM.
44 - This option is required when I(insert) is C(true).
45 - "The following are the examples of the share location:
46 CIFS share: //192.168.0.1/file_path/image_name.iso,
47 NFS share: 192.168.0.2:/file_path/image_name.img,
48 HTTP share: http://192.168.0.3/file_path/image_name.iso,
49 HTTPS share: https://192.168.0.4/file_path/image_name.img"
50 - CIFS share is not supported by iDRAC8.
51 - HTTPS share with credentials is not supported by iDRAC8.
52 index:
53 type: int
54 description:
55 - Index of the Remote File Share. For example, to specify the Remote File Share 1, the value of I(index)
56 should be 1. If I(index) is not specified, the order of I(virtual_media) list will be considered.
57 domain:
58 type: str
59 description: Domain name of network share. This option is applicable for CIFS and HTTPS share.
60 username:
61 type: str
62 description: Network share username. This option is applicable for CIFS and HTTPS share.
63 password:
64 type: str
65 description:
66 - Network share password. This option is applicable for CIFS and HTTPS share.
67 - This module always reports as the changes found when I(password) is provided.
68 media_type:
69 type: str
70 description: Type of the image file. This is applicable when I(insert) is C(true).
71 choices: [CD, DVD, USBStick]
72 force:
73 type: bool
74 description: C(true) ejects the image file if already connected and inserts the file provided in I(image).
75 This is applicable when I(insert) is C(true).
76 default: false
77 resource_id:
78 type: str
79 description: Resource id of the iDRAC, if not specified manager collection id will be used.
80 requirements:
81 - "python >= 3.9.6"
82 author:
83 - "Felix Stephen (@felixs88)"
84 notes:
85 - Run this module from a system that has direct access to Dell iDRAC.
86 - This module supports C(check_mode).
87 """
88
89
90 EXAMPLES = """
91 ---
92 - name: Insert image file to Remote File Share 1 using CIFS share.
93 dellemc.openmanage.idrac_virtual_media:
94 idrac_ip: "192.168.0.1"
95 idrac_user: "user_name"
96 idrac_password: "user_password"
97 ca_path: "/path/to/ca_cert.pem"
98 virtual_media:
99 - insert: true
100 image: "//192.168.0.2/file_path/file.iso"
101 username: "username"
102 password: "password"
103
104 - name: Insert image file to Remote File Share 2 using NFS share.
105 dellemc.openmanage.idrac_virtual_media:
106 idrac_ip: "192.168.0.1"
107 idrac_user: "user_name"
108 idrac_password: "user_password"
109 ca_path: "/path/to/ca_cert.pem"
110 virtual_media:
111 - index: 2
112 insert: true
113 image: "192.168.0.4:/file_path/file.iso"
114
115 - name: Insert image file to Remote File Share 1 and 2 using HTTP.
116 dellemc.openmanage.idrac_virtual_media:
117 idrac_ip: "192.168.0.1"
118 idrac_user: "user_name"
119 idrac_password: "user_password"
120 ca_path: "/path/to/ca_cert.pem"
121 force: true
122 virtual_media:
123 - index: 1
124 insert: true
125 image: "http://192.168.0.4/file_path/file.img"
126 - index: 2
127 insert: true
128 image: "http://192.168.0.4/file_path/file.img"
129
130 - name: Insert image file using HTTPS.
131 dellemc.openmanage.idrac_virtual_media:
132 idrac_ip: "192.168.0.1"
133 idrac_user: "user_name"
134 idrac_password: "user_password"
135 ca_path: "/path/to/ca_cert.pem"
136 force: true
137 virtual_media:
138 - index: 1
139 insert: true
140 image: "https://192.168.0.5/file_path/file.img"
141 username: username
142 password: password
143
144 - name: Eject multiple virtual media.
145 dellemc.openmanage.idrac_virtual_media:
146 idrac_ip: "192.168.0.1"
147 idrac_user: "user_name"
148 idrac_password: "user_password"
149 ca_path: "/path/to/ca_cert.pem"
150 force: true
151 virtual_media:
152 - index: 1
153 insert: false
154 - index: 2
155 insert: false
156
157 - name: Ejection of image file from Remote File Share 1.
158 dellemc.openmanage.idrac_virtual_media:
159 idrac_ip: "192.168.0.1"
160 idrac_user: "user_name"
161 idrac_password: "user_password"
162 ca_path: "/path/to/ca_cert.pem"
163 force: true
164 virtual_media:
165 insert: false
166
167 - name: Insertion and ejection of image file in single task.
168 dellemc.openmanage.idrac_virtual_media:
169 idrac_ip: "192.168.0.1"
170 idrac_user: "user_name"
171 idrac_password: "user_password"
172 ca_path: "/path/to/ca_cert.pem"
173 force: true
174 virtual_media:
175 - index: 1
176 insert: true
177 image: https://192.168.0.5/file/file.iso
178 username: username
179 password: password
180 - index: 2
181 insert: false
182 """
183
184
185 RETURN = r'''
186 ---
187 msg:
188 description: Successfully performed the virtual media operation.
189 returned: success
190 type: str
191 sample: Successfully performed the virtual media operation.
192 error_info:
193 description: Details of the HTTP Error.
194 returned: on HTTP error
195 type: dict
196 sample: {
197 "error": {
198 "code": "Base.1.0.GeneralError",
199 "message": "A general error has occurred. See ExtendedInfo for more information.",
200 "@Message.ExtendedInfo": [
201 {
202 "MessageId": "GEN1234",
203 "RelatedProperties": [],
204 "Message": "Unable to process the request because an error occurred.",
205 "MessageArgs": [],
206 "Severity": "Critical",
207 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
208 }
209 ]
210 }
211 }
212 '''
213
214
215 import json
216 import copy
217 import time
218 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
219 from ansible.module_utils.urls import ConnectionError, SSLValidationError
220 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
221
222
223 MANAGER_BASE = "/redfish/v1/Managers/iDRAC.Embedded.1/VirtualMedia"
224 SYSTEM_BASE = "/redfish/v1/Systems/System.Embedded.1/VirtualMedia"
225
226 EXCEEDED_ERROR = "Unable to complete the operation because the virtual media settings " \
227 "provided exceeded the maximum limit."
228 NO_CHANGES_FOUND = "No changes found to be applied."
229 CHANGES_FOUND = "Changes found to be applied."
230 INVALID_INDEX = "Unable to compete the virtual media operation because the index provided is incorrect or invalid."
231 FAIL_MSG = "Unable to complete the virtual media operation."
232 SUCCESS_MSG = "Successfully performed the virtual media operation."
233 UNSUPPORTED_IMAGE = "Unable to complete the virtual media operation because unsupported image " \
234 "provided. The supported file types are .img and .iso."
235 UNSUPPORTED_MEDIA = "Unable to complete the virtual media operation because unsupported media type " \
236 "provided for index {0}"
237 UNSUPPORTED_MSG = "The system does not support the CIFS network share feature."
238 UNSUPPORTED_MSG_HTTPS = "The system does not support the HTTPS network share feature with credentials."
239
240
241 def get_virtual_media_info(idrac):
242 resp = idrac.invoke_request("/redfish/v1/", "GET")
243 redfish_version = resp.json_data["RedfishVersion"]
244 rd_version = redfish_version.replace(".", "")
245 if 1131 <= int(rd_version):
246 vr_id = "system"
247 member_resp = idrac.invoke_request("{0}?$expand=*($levels=1)".format(SYSTEM_BASE), "GET")
248 else:
249 vr_id = "manager"
250 member_resp = idrac.invoke_request("{0}?$expand=*($levels=1)".format(MANAGER_BASE), "GET")
251 response = member_resp.json_data["Members"]
252 return response, vr_id, rd_version
253
254
255 def get_payload_data(each, vr_members, vr_id):
256 is_change, unsup_media, input_vr_mem = False, None, {}
257 vr_mem = vr_members[each["index"] - 1]
258
259 if each["insert"]:
260 exist_vr_mem = dict((k, vr_mem[k]) for k in ["Inserted", "Image", "UserName", "Password"] if vr_mem.get(k) is not None)
261 input_vr_mem = {"Inserted": each["insert"], "Image": each["image"]}
262 if each["image"].startswith("//") or each["image"].lower().startswith("https://"):
263 username, password, domain = each.get("username"), each.get("password"), each.get("domain")
264 if username is not None:
265 if domain is not None:
266 username = "{0}\\{1}".format(domain, username)
267 input_vr_mem["UserName"] = username
268 if password is not None:
269 input_vr_mem["Password"] = password
270 else:
271 exist_vr_mem.pop("UserName", None)
272 exist_vr_mem.pop("Password", None)
273
274 inp_mt = each.get("media_type")
275 if inp_mt is not None and inp_mt == "CD" and input_vr_mem["Image"][-4:].lower() != ".iso":
276 unsup_media = each["index"]
277 if inp_mt is not None and inp_mt == "DVD" and input_vr_mem["Image"][-4:].lower() != ".iso":
278 unsup_media = each["index"]
279 if inp_mt is not None and inp_mt == "USBStick" and input_vr_mem["Image"][-4:].lower() != ".img":
280 unsup_media = each["index"]
281
282 is_change = bool(set(exist_vr_mem.items()) ^ set(input_vr_mem.items()))
283 else:
284 if vr_id == "manager":
285 for vr_v in vr_members:
286 exist_vr_mem = dict((k, vr_v[k]) for k in ["Inserted"])
287 input_vr_mem = {"Inserted": each.get("insert")}
288 is_change = bool(set(exist_vr_mem.items()) ^ set(input_vr_mem.items()))
289 if is_change:
290 vr_mem = vr_v
291 break
292 else:
293 exist_vr_mem = dict((k, vr_mem[k]) for k in ["Inserted"])
294 input_vr_mem = {"Inserted": each.get("insert")}
295 is_change = bool(set(exist_vr_mem.items()) ^ set(input_vr_mem.items()))
296
297 return is_change, input_vr_mem, vr_mem, unsup_media
298
299
300 def _validate_params(module, vr_members, rd_version):
301 image = vr_members.get("image")
302 if image is not None and (image.startswith("//") or image.startswith("\\\\")):
303 if vr_members.get("username") is None or vr_members.get("password") is None:
304 module.fail_json(msg="CIFS share required username and password.")
305 if image is not None and image.startswith("\\\\"):
306 vr_members["image"] = image.replace("\\", "/")
307 if 140 >= int(rd_version) and image is not None:
308 if (vr_members.get("username") is not None or vr_members.get("password") is not None) and \
309 image.startswith("https://"):
310 module.fail_json(msg=UNSUPPORTED_MSG_HTTPS)
311 elif image.startswith("\\\\") or image.startswith("//"):
312 module.fail_json(msg=UNSUPPORTED_MSG)
313
314
315 def virtual_media_operation(idrac, module, payload, vr_id):
316 err_payload = []
317 force = module.params["force"]
318
319 for i in payload:
320 try:
321 if force and i["vr_mem"]["Inserted"] and i["payload"]["Inserted"]:
322 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.EjectMedia"]["target"],
323 "POST", data="{}", dump=False)
324 time.sleep(5)
325 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.InsertMedia"]["target"],
326 "POST", data=i["payload"])
327 elif not force and i["vr_mem"]["Inserted"] and i["payload"]["Inserted"]:
328 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.EjectMedia"]["target"],
329 "POST", data="{}", dump=False)
330 time.sleep(5)
331 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.InsertMedia"]["target"],
332 "POST", data=i["payload"])
333 elif not i["vr_mem"]["Inserted"] and i["payload"]["Inserted"]:
334 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.InsertMedia"]["target"],
335 "POST", data=i["payload"])
336 elif i["vr_mem"]["Inserted"] and not i["payload"]["Inserted"]:
337 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.EjectMedia"]["target"],
338 "POST", data="{}", dump=False)
339 time.sleep(5)
340 except Exception as err:
341 error = json.load(err).get("error")
342 if vr_id == "manager":
343 msg_id = error["@Message.ExtendedInfo"][0]["MessageId"]
344 if "VRM0021" in msg_id or "VRM0012" in msg_id:
345 uri = i["vr_mem"]["Actions"]["#VirtualMedia.EjectMedia"]["target"]
346 if "RemovableDisk" in uri:
347 uri = uri.replace("RemovableDisk", "CD")
348 elif "CD" in uri:
349 uri = uri.replace("CD", "RemovableDisk")
350 idrac.invoke_request(uri, "POST", data="{}", dump=False)
351 time.sleep(5)
352 idrac.invoke_request(i["vr_mem"]["Actions"]["#VirtualMedia.InsertMedia"]["target"],
353 "POST", data=i["payload"])
354 else:
355 err_payload.append(error)
356 else:
357 err_payload.append(error)
358 return err_payload
359
360
361 def virtual_media(idrac, module, vr_members, vr_id, rd_version):
362 vr_input = module.params["virtual_media"]
363 vr_input_copy = copy.deepcopy(vr_input)
364 vr_index, invalid_idx, manager_idx = [], [], 0
365
366 for idx, value in enumerate(vr_input_copy, start=1):
367 if vr_id == "manager":
368 if value.get("index") is not None:
369 manager_idx = value["index"]
370 if value.get("image") is not None and value.get("image")[-4:] == ".img":
371 value["index"] = 1
372 elif value.get("image") is not None and value.get("image")[-4:] == ".iso":
373 value["index"] = 2
374 elif not value["insert"] and value["index"] is None:
375 value["index"] = idx
376 else:
377 if value.get("index") is None:
378 value["index"] = idx
379 if value["index"] == 0:
380 invalid_idx.append(value["index"])
381 vr_index.append(value["index"])
382
383 _validate_params(module, value, rd_version)
384
385 if ((len(set(vr_index)) != len(vr_index)) or (len(vr_members) < max(vr_index)) or invalid_idx) and vr_id == "system":
386 module.fail_json(msg=INVALID_INDEX)
387 if (vr_id == "manager") and (1 < manager_idx):
388 module.fail_json(msg=INVALID_INDEX)
389 payload, unsupported_media = [], []
390 for each in vr_input_copy:
391
392 is_change, ret_payload, action, unsup_media = get_payload_data(each, vr_members, vr_id)
393 if unsup_media is not None:
394 unsupported_media.append(unsup_media)
395 if module.params["force"] and not is_change and each["insert"]:
396 is_change = True
397 if is_change:
398 payload.append({"payload": ret_payload, "vr_mem": action, "input": each})
399
400 if unsupported_media:
401 if vr_id == "manager":
402 module.fail_json(msg=UNSUPPORTED_MEDIA.format("1"))
403 module.fail_json(msg=UNSUPPORTED_MEDIA.format(", ".join(list(map(str, unsupported_media)))))
404
405 if module.check_mode and payload:
406 module.exit_json(msg=CHANGES_FOUND, changed=True)
407 elif module.check_mode and not payload:
408 module.exit_json(msg=NO_CHANGES_FOUND)
409 elif not module.check_mode and not payload:
410 module.exit_json(msg=NO_CHANGES_FOUND)
411
412 status = virtual_media_operation(idrac, module, payload, vr_id)
413
414 return status
415
416
417 def _validate_image_format(module):
418 unsup_image = False
419 for each in module.params["virtual_media"]:
420 if each["insert"] and each.get("image") is not None and each.get("image")[-4:].lower() not in [".iso", ".img"]:
421 unsup_image = True
422 if unsup_image:
423 module.fail_json(msg=UNSUPPORTED_IMAGE)
424
425
426 def main():
427 specs = {
428 "virtual_media": {
429 "required": True, "type": "list", "elements": "dict",
430 "options": {
431 "insert": {"required": True, "type": "bool"},
432 "image": {"required": False, "type": "path"},
433 "index": {"required": False, "type": "int"},
434 "domain": {"required": False, "type": "str"},
435 "username": {"required": False, "type": "str"},
436 "password": {"required": False, "type": "str", "no_log": True},
437 "media_type": {"required": False, "type": "str", "choices": ["CD", "DVD", "USBStick"]},
438 },
439 "required_if": [["insert", True, ("image", )]],
440 },
441 "force": {"required": False, "type": "bool", "default": False},
442 "resource_id": {"required": False, "type": 'str'},
443 }
444
445 module = IdracAnsibleModule(argument_spec=specs, supports_check_mode=True)
446 try:
447 with iDRACRedfishAPI(module.params, req_session=True) as idrac:
448 vr_media = module.params["virtual_media"]
449 vr_members, vr_id, rd_version = get_virtual_media_info(idrac)
450 if (len(vr_media) > len(vr_members) and vr_id == "system") or \
451 (len(vr_media) > 1 and vr_id == "manager"):
452 module.fail_json(msg=EXCEEDED_ERROR)
453 _validate_image_format(module)
454 resp = virtual_media(idrac, module, vr_members, vr_id, rd_version)
455 if resp:
456 module.fail_json(msg=FAIL_MSG, error_info=resp)
457 module.exit_json(msg=SUCCESS_MSG, changed=True)
458 except HTTPError as err:
459 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
460 except URLError as err:
461 module.exit_json(msg=str(err), unreachable=True)
462 except (RuntimeError, SSLValidationError, ConnectionError, KeyError,
463 ImportError, ValueError, TypeError) as err:
464 module.exit_json(msg=str(err), failed=True)
465
466
467 if __name__ == '__main__':
468 main()