Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Dell OpenManage Ansible Modules
4 # Version 10.0.0
5 # Copyright (C) 2018-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
6 # GNU General Public License v3.0+
7 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import (absolute_import, division, print_function)
10 __metaclass__ = type
11
12 DOCUMENTATION = r'''
13 ---
14 module: idrac_os_deployment
15 short_description: Boot to a network ISO image
16 version_added: "2.1.0"
17 description: Boot to a network ISO image.
18 extends_documentation_fragment:
19 - dellemc.openmanage.idrac_x_auth_options
20 options:
21 share_name:
22 required: true
23 description: CIFS or NFS Network share.
24 type: str
25 share_user:
26 description:
27 - Network share user in the format 'user@domain' or 'domain\\user'
28 if user is part of a domain else 'user'. This option is mandatory
29 for CIFS Network Share.
30 type: str
31 share_password:
32 description:
33 - Network share user password. This option is mandatory for CIFS
34 Network Share.
35 type: str
36 aliases: ['share_pwd']
37 iso_image:
38 required: true
39 description: Network ISO name.
40 type: str
41 expose_duration:
42 description:
43 - It is the time taken in minutes for the ISO image file to be exposed
44 as a local CD-ROM device to the host server. When the time expires,
45 the ISO image gets automatically detached.
46 type: int
47 default: 1080
48 requirements:
49 - "python >= 3.9.6"
50 author:
51 - "Felix Stephen (@felixs88)"
52 - "Jagadeesh N V (@jagadeeshnv)"
53 - "Abhishek Sinha (@ABHISHEK-SINHA10)"
54 - "Bhavneet Sharma (@Bhavneet-Sharma)"
55 notes:
56 - Run this module from a system that has direct access to Dell iDRAC.
57 - This module supports both IPv4 and IPv6 address for I(idrac_ip).
58 - This module does not support C(check_mode).
59 '''
60
61 EXAMPLES = r'''
62 ---
63 - name: Boot to Network ISO
64 dellemc.openmanage.idrac_os_deployment:
65 idrac_ip: "192.168.0.1"
66 idrac_user: "user_name"
67 idrac_password: "user_password"
68 ca_path: "/path/to/ca_cert.pem"
69 share_name: "192.168.0.0:/nfsfileshare"
70 iso_image: "unattended_os_image.iso"
71 expose_duration: 180
72 '''
73
74 RETURN = r'''
75 ---
76 msg:
77 type: str
78 description: Over all device information status.
79 returned: on error
80 sample: "Failed to boot to network iso"
81 boot_status:
82 description: Details of the boot to network ISO image operation.
83 returned: always
84 type: dict
85 sample: {
86 "DeleteOnCompletion": "false",
87 "InstanceID": "DCIM_OSDConcreteJob:1",
88 "JobName": "BootToNetworkISO",
89 "JobStatus": "Success",
90 "Message": "The command was successful.",
91 "MessageID": "OSD1",
92 "Name": "BootToNetworkISO",
93 "Status": "Success",
94 "file": "192.168.0.0:/nfsfileshare/unattended_os_image.iso",
95 "retval": true
96 }
97 '''
98
99
100 import json
101 import time
102 from ansible.module_utils.six.moves.urllib.parse import urlparse
103 from urllib.error import HTTPError, URLError
104 from ansible.module_utils.urls import ConnectionError, SSLValidationError
105 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import idrac_auth_params, \
106 iDRACRedfishAPI, IdracAnsibleModule
107 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import \
108 remove_key, wait_for_idrac_job_completion
109
110 MANAGER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1"
111 JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs"
112 SINGLE_JOB_URI = JOB_URI + "/{jobId}"
113 BootTONetworkISOURI = "/redfish/v1/Systems/System.Embedded.1/Oem/Dell/DellOSDeploymentService/Actions/DellOSDeploymentService.BootToNetworkISO"
114 ODATA_ID = "(.*?)@odata"
115 JOB_NOT_FOUND = "No matching job found following the BootToNetworkISO operation."
116 INVALID_EXPOSEDURATION = "Invalid value for ExposeDuration."
117
118
119 def minutes_to_iso_format(module, dur_minutes):
120 """Convert minutes to iso format"""
121 if dur_minutes < 0:
122 module.exit_json(msg=INVALID_EXPOSEDURATION, failed=True)
123 sample_time_str = '0000-00-00T00:00:00-00:00'
124 time_part = sample_time_str.split('T')[1].split('-')[0]
125 h, m, s = map(int, time_part.split(':'))
126 # Add minutes
127 m += dur_minutes
128 h += m // 60
129 m = m % 60
130 h = h % 24
131
132 new_time = f"{h:02}:{m:02}:{s:02}"
133 formatted_time = sample_time_str.replace(time_part, new_time)
134 return formatted_time
135
136
137 def get_current_time_from_idrac(idrac):
138 """Get current time from iDRAC"""
139 resp = idrac.invoke_request(MANAGER_URI, "GET")
140 date_time = resp.json_data.get("DateTime")
141 return date_time
142
143
144 def construct_payload(module):
145 """Construct payload"""
146 shr_name = module.params.get('share_name')
147 ip_addr, share_name, share_type = '', '', ''
148 if shr_name.startswith('\\\\'):
149 cifs = shr_name.split('\\')
150 ip_addr = cifs[2]
151 share_name = '\\'.join(cifs[3:])
152 share_type = 'CIFS'
153 else:
154 nfs = urlparse("nfs://" + shr_name)
155 ip_addr = nfs.netloc.strip(':')
156 share_name = nfs.path.strip('/')
157 share_type = 'NFS'
158 payload = {
159 "ExposeDuration": minutes_to_iso_format(
160 module, module.params.get('expose_duration')),
161 "IPAddress": ip_addr,
162 "ShareName": share_name,
163 "ShareType": share_type,
164 "ImageName": module.params.get('iso_image'),
165 }
166
167 if module.params.get('share_user'):
168 payload["UserName"] = module.params['share_user']
169 if module.params.get('share_password'):
170 payload["Password"] = module.params['share_password']
171 return payload
172
173
174 def filter_job_from_members(idrac, members, idrac_time):
175 job_type = 'OSD: BootTONetworkISO'
176 jid_list = []
177 for membr in members:
178 split_job_oid = membr.get("@odata.id").split("/")
179 jid_list.append(split_job_oid[-1])
180
181 for jid in jid_list:
182 job_uri = SINGLE_JOB_URI.format(jobId=jid)
183 resp = idrac.invoke_request(job_uri, "GET")
184 job = resp.json_data
185 art_time = job.get('StartTime')
186 if job.get("Name") == job_type and art_time > idrac_time:
187 return job
188 return None
189
190
191 def getting_top_osd_job_and_tracking(idrac, module, idrac_time_str):
192 job_id = None
193 _out = {'msg': JOB_NOT_FOUND, 'failed': True}
194 time.sleep(20)
195
196 resp = idrac.invoke_request(JOB_URI, "GET")
197 filtered_job = filter_job_from_members(
198 idrac, resp.json_data.get("Members", []), idrac_time_str)
199 if filtered_job:
200 job_id = filtered_job.get("Id")
201 if job_id:
202 job_uri = SINGLE_JOB_URI.format(jobId=job_id)
203 job_details, msg = wait_for_idrac_job_completion(
204 idrac, job_uri, wait_timeout=1800)
205 if job_details:
206 return remove_key(job_details.json_data, regex_pattern=ODATA_ID)
207 _out = {'msg': msg}
208 module.exit_json(**_out)
209
210
211 def main():
212 specs = {
213 "share_name": {"required": True, "type": 'str'},
214 "share_user": {"required": False, "type": 'str'},
215 "share_password": {
216 "required": False, "type": 'str', "aliases": ['share_pwd'],
217 "no_log": True},
218 "iso_image": {"required": True, "type": 'str'},
219 "expose_duration": {"required": False, "type": 'int', "default": 1080}
220 }
221 specs.update(idrac_auth_params)
222 module = IdracAnsibleModule(
223 argument_spec=specs,
224 supports_check_mode=False)
225
226 try:
227 with iDRACRedfishAPI(module.params) as idrac:
228 idrac_time_str = get_current_time_from_idrac(idrac)
229 payload = construct_payload(module)
230 idrac.invoke_request(BootTONetworkISOURI, "POST", data=payload)
231 resp = getting_top_osd_job_and_tracking(idrac, module,
232 idrac_time_str)
233 boot_status = {'Message': resp.get("Message"),
234 'Status': resp.get("JobState")}
235 if resp.get("JobState") == "Failed":
236 module.exit_json(msg=boot_status, failed=True)
237 module.exit_json(boot_status=boot_status, changed=True)
238 except HTTPError as err:
239 filter_err = remove_key(json.load(err), regex_pattern=ODATA_ID)
240 module.exit_json(msg=str(err), error_info=filter_err, failed=True)
241 except URLError as err:
242 module.exit_json(msg=str(err), unreachable=True)
243 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
244 module.exit_json(msg=str(err), failed=True)
245
246
247 if __name__ == '__main__':
248 main()