Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.2
7 # Copyright (C) 2024-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
15 __metaclass__ = type
16
17 DOCUMENTATION = r"""
18 ---
19 module: idrac_license
20 short_description: Configure iDRAC licenses
21 version_added: "8.7.0"
22 description:
23 - This module allows to import, export and delete licenses on iDRAC.
24 extends_documentation_fragment:
25 - dellemc.openmanage.idrac_x_auth_options
26 options:
27 license_id:
28 description:
29 - Entitlement ID of the license that is to be imported, exported or deleted.
30 - I(license_id) is required when I(delete) is C(true) or I(export) is C(true).
31 type: str
32 aliases: ['entitlement_id']
33 delete:
34 description:
35 - Delete the license from the iDRAC.
36 - When I(delete) is C(true), then I(license_id) is required.
37 - I(delete) is mutually exclusive with I(export) and I(import).
38 type: bool
39 default: false
40 export:
41 description:
42 - Export the license from the iDRAC.
43 - When I(export) is C(true), I(license_id) and I(share_parameters) is required.
44 - I(export) is mutually exclusive with I(delete) and I(import).
45 type: bool
46 default: false
47 import:
48 description:
49 - Import the license from the iDRAC.
50 - When I(import) is C(true), I(share_parameters) is required.
51 - I(import) is mutually exclusive with I(delete) and I(export).
52 type: bool
53 default: false
54 share_parameters:
55 description:
56 - Parameters that are required for the import and export operation of a license.
57 - I(share_parameters) is required when I(export) or I(import) is C(true).
58 type: dict
59 suboptions:
60 share_type:
61 description:
62 - Share type of the network share.
63 - C(local) uses local path for I(import) and I(export) operation.
64 - C(nfs) uses NFS share for I(import) and I(export) operation.
65 - C(cifs) uses CIFS share for I(import) and I(export) operation.
66 - C(http) uses HTTP share for I(import) and I(export) operation.
67 - C(https) uses HTTPS share for I(import) and I(export) operation.
68 type: str
69 choices: [local, nfs, cifs, http, https]
70 default: local
71 file_name:
72 description:
73 - License file name for I(import) and I(export) operation.
74 - I(file_name) is required when I(import) is C(true).
75 - For the I(import) operation, when I(share_type) is C(local), the supported extensions for I(file_name) are '.txt' and '.xml'.
76 For other share types, the supported extension is '.xml'
77 type: str
78 ip_address:
79 description:
80 - IP address of the network share.
81 - I(ip_address) is required when I(share_type) is C(nfs), C(cifs), C(http) or C(https).
82 type: str
83 share_name:
84 description:
85 - Network share or local path of the license file.
86 type: str
87 workgroup:
88 description:
89 - Workgroup of the network share.
90 - I(workgroup) is applicable only when I(share_type) is C(cifs).
91 type: str
92 username:
93 description:
94 - Username of the network share.
95 - I(username) is required when I(share_type) is C(cifs).
96 type: str
97 password:
98 description:
99 - Password of the network share.
100 - I(password) is required when I(share_type) is C(cifs).
101 type: str
102 ignore_certificate_warning:
103 description:
104 - Ignores the certificate warning while connecting to Share and is only applicable when I(share_type) is C(https).
105 - C(on) ignores the certificate warning.
106 - C(off) does not ignore the certificate warning.
107 type: str
108 choices: ["off", "on"]
109 default: "off"
110 proxy_support:
111 description:
112 - Specifies if proxy is to be used or not.
113 - C(off) does not use proxy settings.
114 - C(default_proxy) uses the default proxy settings.
115 - C(parameters_proxy) uses the specified proxy settings. I(proxy_server) is required when I(proxy_support) is C(parameters_proxy).
116 - I(proxy_support) is only applicable when I(share_type) is C(https) or C(https).
117 type: str
118 choices: ["off", "default_proxy", "parameters_proxy"]
119 default: "off"
120 proxy_type:
121 description:
122 - The proxy type of the proxy server.
123 - C(http) to select HTTP proxy.
124 - C(socks) to select SOCKS proxy.
125 - I(proxy_type) is only applicable when I(share_type) is C(https) or C(https) and when I(proxy_support) is C(parameters_proxy).
126 type: str
127 choices: [http, socks]
128 default: http
129 proxy_server:
130 description:
131 - The IP address of the proxy server.
132 - I(proxy_server) is required when I(proxy_support) is C(parameters_proxy).
133 - I(proxy_server) is only applicable when I(share_type) is C(https) or C(https) and when I(proxy_support) is C(parameters_proxy).
134 type: str
135 proxy_port:
136 description:
137 - The port of the proxy server.
138 - I(proxy_port) is only applicable when I(share_type) is C(https) or C(https) and when I(proxy_support) is C(parameters_proxy).
139 type: int
140 default: 80
141 proxy_username:
142 description:
143 - The username of the proxy server.
144 - I(proxy_username) is only applicable when I(share_type) is C(https) or C(https) and when I(proxy_support) is C(parameters_proxy).
145 type: str
146 proxy_password:
147 description:
148 - The password of the proxy server.
149 - I(proxy_password) is only applicable when I(share_type) is C(https) or C(https) and when I(proxy_support) is C(parameters_proxy).
150 type: str
151 resource_id:
152 type: str
153 description:
154 - Id of the resource.
155 - If the value for resource ID is not provided, the module picks the first resource ID available from the list of system resources returned by the iDRAC.
156 requirements:
157 - "python >= 3.9.6"
158 author:
159 - "Rajshekar P(@rajshekarp87)"
160 - "Akash Shendge(@shenda1)"
161 notes:
162 - Run this module from a system that has direct access to Dell iDRAC.
163 - This module supports only iDRAC9 and above.
164 - This module supports IPv4 and IPv6 addresses.
165 - This module does not support C(check_mode).
166 - When I(share_type) is C(local) for I(import) and I(export) operations, job_details are not displayed.
167 - Due to API limitation, proxy parameters are ignored during the I(import) operation.
168 """
169
170 EXAMPLES = r"""
171 ---
172 - name: Export a license from iDRAC to local
173 dellemc.openmanage.idrac_license:
174 idrac_ip: "192.168.0.1"
175 idrac_user: "username"
176 idrac_password: "password"
177 ca_path: "/path/to/ca_cert.pem"
178 license_id: "LICENSE_123"
179 export: true
180 share_parameters:
181 share_type: "local"
182 share_name: "/path/to/share"
183 file_name: "license_file"
184
185 - name: Export a license from iDRAC to NFS share
186 dellemc.openmanage.idrac_license:
187 idrac_ip: "192.168.0.1"
188 idrac_user: "username"
189 idrac_password: "password"
190 ca_path: "/path/to/ca_cert.pem"
191 license_id: "LICENSE_123"
192 export: true
193 share_parameters:
194 share_type: "nfs"
195 share_name: "/path/to/share"
196 file_name: "license_file"
197 ip_address: "192.168.0.1"
198
199 - name: Export a license from iDRAC to CIFS share
200 dellemc.openmanage.idrac_license:
201 idrac_ip: "192.168.0.1"
202 idrac_user: "username"
203 idrac_password: "password"
204 ca_path: "/path/to/ca_cert.pem"
205 license_id: "LICENSE_123"
206 export: true
207 share_parameters:
208 share_type: "cifs"
209 share_name: "/path/to/share"
210 file_name: "license_file"
211 ip_address: "192.168.0.1"
212 username: "username"
213 password: "password"
214 workgroup: "workgroup"
215
216 - name: Export a license from iDRAC to HTTP share via proxy
217 dellemc.openmanage.idrac_license:
218 idrac_ip: "192.168.0.1"
219 idrac_user: "username"
220 idrac_password: "password"
221 ca_path: "/path/to/ca_cert.pem"
222 license_id: "LICENSE_123"
223 export: true
224 share_parameters:
225 share_type: "http"
226 share_name: "/path/to/share"
227 file_name: "license_file"
228 ip_address: "192.168.0.1"
229 username: "username"
230 password: "password"
231 proxy_support: "parameters_proxy"
232 proxy_type: socks
233 proxy_server: "192.168.0.2"
234 proxy_port: 1080
235 proxy_username: "proxy_username"
236 proxy_password: "proxy_password"
237
238 - name: Export a license from iDRAC to HTTPS share
239 dellemc.openmanage.idrac_license:
240 idrac_ip: "192.168.0.1"
241 idrac_user: "username"
242 idrac_password: "password"
243 ca_path: "/path/to/ca_cert.pem"
244 license_id: "LICENSE_123"
245 export: true
246 share_parameters:
247 share_type: "https"
248 share_name: "/path/to/share"
249 file_name: "license_file"
250 ip_address: "192.168.0.1"
251 username: "username"
252 password: "password"
253 ignore_certificate_warning: "on"
254
255 - name: Import a license to iDRAC from local
256 dellemc.openmanage.idrac_license:
257 idrac_ip: 198.162.0.1
258 idrac_user: "username"
259 idrac_password: "password"
260 ca_path: "/path/to/ca_cert.pem"
261 import: true
262 share_parameters:
263 file_name: "license_file_name.xml"
264 share_type: local
265 share_name: "/path/to/share"
266
267 - name: Import a license to iDRAC from NFS share
268 dellemc.openmanage.idrac_license:
269 idrac_ip: 198.162.0.1
270 idrac_user: "username"
271 idrac_password: "password"
272 ca_path: "/path/to/ca_cert.pem"
273 import: true
274 share_parameters:
275 file_name: "license_file_name.xml"
276 share_type: nfs
277 ip_address: "192.168.0.1"
278 share_name: "/path/to/share"
279
280 - name: Import a license to iDRAC from CIFS share
281 dellemc.openmanage.idrac_license:
282 idrac_ip: 198.162.0.1
283 idrac_user: "username"
284 idrac_password: "password"
285 ca_path: "/path/to/ca_cert.pem"
286 import: true
287 share_parameters:
288 file_name: "license_file_name.xml"
289 share_type: cifs
290 ip_address: "192.168.0.1"
291 share_name: "/path/to/share"
292 username: "username"
293 password: "password"
294
295 - name: Import a license to iDRAC from HTTP share
296 dellemc.openmanage.idrac_license:
297 idrac_ip: 198.162.0.1
298 idrac_user: "username"
299 idrac_password: "password"
300 ca_path: "/path/to/ca_cert.pem"
301 import: true
302 share_parameters:
303 file_name: "license_file_name.xml"
304 share_type: http
305 ip_address: "192.168.0.1"
306 share_name: "/path/to/share"
307 username: "username"
308 password: "password"
309
310 - name: Delete a License from iDRAC
311 dellemc.openmanage.idrac_license:
312 idrac_ip: 198.162.0.1
313 idrac_user: "username"
314 idrac_password: "password"
315 ca_path: "/path/to/ca_cert.pem"
316 license_id: "LICENCE_123"
317 delete: true
318 """
319
320 RETURN = r'''
321 ---
322 msg:
323 type: str
324 description: Status of the license operation.
325 returned: always
326 sample: "Successfully exported the license."
327 job_details:
328 description: Returns the output for status of the job.
329 returned: For import and export operations
330 type: dict
331 sample: {
332 "ActualRunningStartTime": "2024-01-09T05:16:19",
333 "ActualRunningStopTime": "2024-01-09T05:16:19",
334 "CompletionTime": "2024-01-09T05:16:19",
335 "Description": "Job Instance",
336 "EndTime": null,
337 "Id": "JID_XXXXXXXXX",
338 "JobState": "Completed",
339 "JobType": "LicenseExport",
340 "Message": "The command was successful.",
341 "MessageArgs": [],
342 "MessageId": "LIC900",
343 "Name": "Export: License",
344 "PercentComplete": 100,
345 "StartTime": "2024-01-09T05:16:19",
346 "TargetSettingsURI": null
347 }
348 error_info:
349 description: Details of the HTTP Error.
350 returned: on HTTP error
351 type: dict
352 sample: {
353 "error": {
354 "code": "Base.1.8.GeneralError",
355 "message": "A general error has occurred. See ExtendedInfo for more information.",
356 "@Message.ExtendedInfo": [
357 {
358 "MessageId": "Base.1.8.AccessDenied",
359 "Message": "The authentication credentials included with this request are missing or invalid.",
360 "MessageArgs": [],
361 "RelatedProperties": [],
362 "Severity": "Critical",
363 "Resolution": "Attempt to ensure that the URI is correct and that the service has the appropriate credentials."
364 }
365 ]
366 }
367 }
368 '''
369
370
371 import json
372 import os
373 import base64
374 from urllib.error import HTTPError, URLError
375 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
376 from ansible.module_utils.urls import ConnectionError, SSLValidationError
377 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import (
378 get_dynamic_uri, get_manager_res_id,
379 validate_and_get_first_resource_id_uri, remove_key, idrac_redfish_job_tracking)
380
381 REDFISH = "/redfish/v1"
382 MANAGERS_URI = "/redfish/v1/Managers"
383 IDRAC_JOB_URI = "{res_uri}/Oem/Dell/Jobs/{job_id}"
384
385 OEM = "Oem"
386 MANUFACTURER = "Dell"
387 LICENSE_MANAGEMENT_SERVICE = "DellLicenseManagementService"
388 ACTIONS = "Actions"
389 EXPORT_NETWORK_SHARE = "#DellLicenseManagementService.ExportLicenseToNetworkShare"
390 IMPORT_LOCAL = "#DellLicenseManagementService.ImportLicense"
391 IMPORT_NETWORK_SHARE = "#LicenseService.Install"
392 ODATA = "@odata.id"
393 ODATA_REGEX = "(.*?)@odata"
394
395 AUTH_ERROR_MSG = "Unable to communicate with iDRAC {ip} with error: {error}. This may be due to one of the following: " \
396 "Incorrect username or password, unreachable iDRAC IP or a failure in TLS/SSL handshake."
397 INVALID_LICENSE_MSG = "License with ID '{license_id}' does not exist on the iDRAC."
398 SUCCESS_EXPORT_MSG = "Successfully exported the license."
399 SUCCESS_DELETE_MSG = "Successfully deleted the license."
400 SUCCESS_IMPORT_MSG = "Successfully imported the license."
401 FAILURE_MSG = "Unable to '{operation}' the license with id '{license_id}' as it does not exist."
402 FAILURE_IMPORT_MSG = "Unable to import the license."
403 NO_FILE_MSG = "License file not found."
404 UNSUPPORTED_IDRAC_MSG = "iDRAC version is not supported."
405 NO_OPERATION_SKIP_MSG = "Task is skipped as none of import, export or delete is specified."
406 INVALID_FILE_MSG = "File extension is invalid. Supported extensions for local 'share_type' " \
407 "are: .txt and .xml, and for network 'share_type' is: .xml."
408 INVALID_DIRECTORY_MSG = "Provided directory path '{path}' is not valid."
409 INSUFFICIENT_DIRECTORY_PERMISSION_MSG = "Provided directory path '{path}' is not writable. " \
410 "Please check if the directory has appropriate permissions"
411 MISSING_FILE_NAME_PARAMETER_MSG = "Missing required parameter 'file_name'."
412
413 PROXY_SUPPORT = {"off": "Off", "default_proxy": "DefaultProxy", "parameters_proxy": "ParametersProxy"}
414
415
416 class License():
417 def __init__(self, idrac, module):
418 """
419 Initializes the class instance with the provided idrac and module parameters.
420
421 :param idrac: The idrac parameter.
422 :type idrac: Any
423 :param module: The module parameter.
424 :type module: Any
425 """
426 self.idrac = idrac
427 self.module = module
428
429 def execute(self):
430 """
431 Executes the function with the given module.
432
433 :param module: The module to execute.
434 :type module: Any
435 :return: None
436 """
437
438 def check_license_id(self, license_id):
439 """
440 Check the license ID for a given operation.
441
442 :param self: The object instance.
443 :param module: The Ansible module.
444 :param license_id: The ID of the license to check.
445 :param operation: The operation to perform.
446 :return: The response from the license URL.
447 """
448 license_uri = self.get_license_url()
449 license_url = license_uri + f"/{license_id}"
450 try:
451 response = self.idrac.invoke_request(license_url, 'GET')
452 return response
453 except Exception:
454 self.module.exit_json(msg=INVALID_LICENSE_MSG.format(license_id=license_id), skipped=True)
455
456 def get_license_url(self):
457 """
458 Retrieves the license URL for the current user.
459
460 :return: The license URL as a string.
461 """
462 v1_resp = get_dynamic_uri(self.idrac, REDFISH)
463 license_service_url = v1_resp.get('LicenseService', {}).get(ODATA, {})
464 license_service_resp = get_dynamic_uri(self.idrac, license_service_url)
465 license_url = license_service_resp.get('Licenses', {}).get(ODATA, {})
466 return license_url
467
468 def get_job_status(self, license_job_response):
469 """
470 Get the status of a job.
471
472 Args:
473 module (object): The module object.
474 license_job_response (object): The response object for the license job.
475
476 Returns:
477 dict: The job details.
478 """
479 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
480 job_tracking_uri = license_job_response.headers.get("Location")
481 job_id = job_tracking_uri.split("/")[-1]
482 job_uri = IDRAC_JOB_URI.format(job_id=job_id, res_uri=res_uri[0])
483 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(self.idrac, job_uri)
484 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
485 if job_failed:
486 self.module.exit_json(
487 msg=job_dict.get('Message'),
488 failed=True,
489 job_details=job_dict)
490 return job_dict
491
492 def get_share_details(self):
493 """
494 Retrieves the share details from the given module.
495
496 Args:
497 module (object): The module object containing the share parameters.
498
499 Returns:
500 dict: A dictionary containing the share details with the following keys:
501 - IPAddress (str): The IP address of the share.
502 - ShareName (str): The name of the share.
503 - UserName (str): The username for accessing the share.
504 - Password (str): The password for accessing the share.
505 """
506 share_details = {}
507 share_details["IPAddress"] = self.module.params.get('share_parameters').get('ip_address')
508 share_details["ShareName"] = self.module.params.get('share_parameters').get('share_name')
509 if self.module.params.get('share_parameters').get('username'):
510 share_details["UserName"] = self.module.params.get('share_parameters').get('username')
511 if self.module.params.get('share_parameters').get('password'):
512 share_details["Password"] = self.module.params.get('share_parameters').get('password')
513 return share_details
514
515 def get_proxy_details(self):
516 """
517 Retrieves the proxy details based on the provided module parameters.
518
519 Args:
520 self: The instance of the class.
521 module: The module object containing the parameters.
522
523 Returns:
524 dict: A dictionary containing the proxy details.
525 """
526 proxy_details = {}
527 proxy_details["ShareType"] = self.module.params.get('share_parameters').get('share_type').upper()
528 proxy_details["IgnoreCertWarning"] = self.module.params.get('share_parameters').get('ignore_certificate_warning').capitalize()
529 if self.module.params.get('share_parameters').get('proxy_support') == "parameters_proxy":
530 proxy_details["ProxySupport"] = PROXY_SUPPORT[self.module.params.get('share_parameters').get('proxy_support')]
531 proxy_details["ProxyType"] = self.module.params.get('share_parameters').get('proxy_type').upper()
532 proxy_details["ProxyServer"] = self.module.params.get('share_parameters').get('proxy_server')
533 proxy_details["ProxyPort"] = str(self.module.params.get('share_parameters').get('proxy_port'))
534 if self.module.params.get('share_parameters').get('proxy_username') and self.module.params.get('share_parameters').get('proxy_password'):
535 proxy_details["ProxyUname"] = self.module.params.get('share_parameters').get('proxy_username')
536 proxy_details["ProxyPasswd"] = self.module.params.get('share_parameters').get('proxy_password')
537 return proxy_details
538
539
540 class DeleteLicense(License):
541 def execute(self):
542 """
543 Executes the delete operation for a given license ID.
544
545 Args:
546 module (object): The Ansible module object.
547
548 Returns:
549 object: The response object from the delete operation.
550 """
551 license_id = self.module.params.get('license_id')
552 self.check_license_id(license_id)
553 license_url = self.get_license_url()
554 delete_license_url = license_url + f"/{license_id}"
555 delete_license_response = self.idrac.invoke_request(delete_license_url, 'DELETE')
556 status = delete_license_response.status_code
557 if status == 204:
558 self.module.exit_json(msg=SUCCESS_DELETE_MSG, changed=True)
559 else:
560 self.module.exit_json(msg=FAILURE_MSG.format(operation="delete", license_id=license_id), failed=True)
561
562
563 class ExportLicense(License):
564 STATUS_SUCCESS = [200, 202]
565
566 def execute(self):
567 """
568 Executes the export operation for a given license ID.
569
570 :param module: The Ansible module object.
571 :type module: AnsibleModule
572
573 :return: The response from the export operation.
574 :rtype: Response
575 """
576 share_type = self.module.params.get('share_parameters').get('share_type')
577 license_id = self.module.params.get('license_id')
578 self.check_license_id(license_id)
579 export_license_url = self.__get_export_license_url()
580 job_status = {}
581 if share_type == "local":
582 export_license_response = self.__export_license_local(export_license_url)
583 elif share_type in ["http", "https"]:
584 export_license_response = self.__export_license_http(export_license_url)
585 job_status = self.get_job_status(export_license_response)
586 elif share_type == "cifs":
587 export_license_response = self.__export_license_cifs(export_license_url)
588 job_status = self.get_job_status(export_license_response)
589 elif share_type == "nfs":
590 export_license_response = self.__export_license_nfs(export_license_url)
591 job_status = self.get_job_status(export_license_response)
592 status = export_license_response.status_code
593 if status in self.STATUS_SUCCESS:
594 self.module.exit_json(msg=SUCCESS_EXPORT_MSG, changed=True, job_details=job_status)
595 else:
596 self.module.exit_json(msg=FAILURE_MSG.format(operation="export", license_id=license_id), failed=True, job_details=job_status)
597
598 def __export_license_local(self, export_license_url):
599 """
600 Export the license to a local directory.
601
602 Args:
603 module (object): The Ansible module object.
604 export_license_url (str): The URL for exporting the license.
605
606 Returns:
607 object: The license status after exporting.
608 """
609 payload = {}
610 payload["EntitlementID"] = self.module.params.get('license_id')
611 path = self.module.params.get('share_parameters').get('share_name')
612 if not (os.path.exists(path) or os.path.isdir(path)):
613 self.module.exit_json(msg=INVALID_DIRECTORY_MSG.format(path=path), failed=True)
614 if not os.access(path, os.W_OK):
615 self.module.exit_json(msg=INSUFFICIENT_DIRECTORY_PERMISSION_MSG.format(path=path), failed=True)
616 license_name = self.module.params.get('share_parameters').get('file_name')
617 if license_name:
618 license_file_name = f"{license_name}"
619 else:
620 license_file_name = f"{self.module.params['license_id']}_iDRAC_license.xml"
621 license_status = self.idrac.invoke_request(export_license_url, "GET")
622 license_data = license_status.body
623 license_file = license_data.decode("utf-8")
624 file_name = os.path.join(path, license_file_name)
625 with open(file_name, "w") as fp:
626 fp.write(license_file)
627 return license_status
628
629 def __export_license_http(self, export_license_url):
630 """
631 Export the license using the HTTP protocol.
632
633 Args:
634 module (object): The module object.
635 export_license_url (str): The URL for exporting the license.
636
637 Returns:
638 str: The export status.
639 """
640 payload = {}
641 payload["EntitlementID"] = self.module.params.get('license_id')
642 payload["ShareType"] = self.module.params.get('share_parameters').get('share_type')
643 proxy_details = self.get_proxy_details()
644 share_details = self.get_share_details()
645 payload.update(proxy_details)
646 payload.update(share_details)
647 export_status = self.__export_license(payload, export_license_url)
648 return export_status
649
650 def __export_license_cifs(self, export_license_url):
651 """
652 Export the license using CIFS share type.
653
654 Args:
655 module (object): The Ansible module object.
656 export_license_url (str): The URL for exporting the license.
657
658 Returns:
659 str: The export status.
660 """
661 payload = {}
662 payload["EntitlementID"] = self.module.params.get('license_id')
663 payload["ShareType"] = "CIFS"
664 share_details = self.get_share_details()
665 payload.update(share_details)
666 if self.module.params.get('share_parameters').get('workgroup'):
667 payload["Workgroup"] = self.module.params.get('share_parameters').get('workgroup')
668 export_status = self.__export_license(payload, export_license_url)
669 return export_status
670
671 def __export_license_nfs(self, export_license_url):
672 """
673 Export the license using NFS share type.
674
675 Args:
676 module (object): The Ansible module object.
677 export_license_url (str): The URL for exporting the license.
678
679 Returns:
680 dict: The export status of the license.
681 """
682 payload = {}
683 payload["EntitlementID"] = self.module.params.get('license_id')
684 payload["ShareType"] = "NFS"
685 payload["IPAddress"] = self.module.params.get('share_parameters').get('ip_address')
686 payload["ShareName"] = self.module.params.get('share_parameters').get('share_name')
687 export_status = self.__export_license(payload, export_license_url)
688 return export_status
689
690 def __get_export_license_url(self):
691 """
692 Get the export license URL.
693
694 :param module: The module object.
695 :type module: object
696 :return: The export license URL.
697 :rtype: str
698 """
699 if self.module.params.get('share_parameters').get('share_type') != "local":
700 uri, error_msg = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
701 if error_msg:
702 self.module.exit_json(msg=error_msg, failed=True)
703 resp = get_dynamic_uri(self.idrac, uri)
704 url = resp.get('Links', {}).get(OEM, {}).get(MANUFACTURER, {}).get(LICENSE_MANAGEMENT_SERVICE, {}).get(ODATA, {})
705 action_resp = get_dynamic_uri(self.idrac, url)
706 export_url = action_resp.get(ACTIONS, {}).get(EXPORT_NETWORK_SHARE, {}).get('target', {})
707 else:
708 response = self.check_license_id(self.module.params.get('license_id'))
709 export_url = response.json_data.get("DownloadURI", {})
710 return export_url
711
712 def __export_license(self, payload, export_license_url):
713 """
714 Export the license to a file.
715
716 Args:
717 module (object): The Ansible module object.
718 payload (dict): The payload containing the license information.
719 export_license_url (str): The URL for exporting the license.
720
721 Returns:
722 dict: The license status after exporting.
723 """
724 license_name = self.module.params.get('share_parameters').get('file_name')
725 if license_name:
726 license_file_name = f"{license_name}"
727 else:
728 license_file_name = f"{self.module.params['license_id']}_iDRAC_license.xml"
729 payload["FileName"] = license_file_name
730 license_status = self.idrac.invoke_request(export_license_url, "POST", data=payload)
731 return license_status
732
733
734 class ImportLicense(License):
735 STATUS_SUCCESS = [200, 202]
736
737 def execute(self):
738 """
739 Executes the import license process based on the given module parameters.
740
741 Args:
742 module (object): The Ansible module object.
743
744 Returns:
745 object: The response object from the import license API call.
746 """
747 if not self.module.params.get('share_parameters').get('file_name'):
748 self.module.exit_json(msg=MISSING_FILE_NAME_PARAMETER_MSG, failed=True)
749 share_type = self.module.params.get('share_parameters').get('share_type')
750 self.__check_file_extension()
751 import_license_url = self.__get_import_license_url()
752 resource_id = get_manager_res_id(self.idrac)
753 job_status = {}
754 if share_type == "local":
755 import_license_response = self.__import_license_local(import_license_url, resource_id)
756 elif share_type in ["http", "https"]:
757 import_license_response = self.__import_license_http(import_license_url)
758 job_status = self.get_job_status(import_license_response)
759 elif share_type == "cifs":
760 import_license_response = self.__import_license_cifs(import_license_url)
761 job_status = self.get_job_status(import_license_response)
762 elif share_type == "nfs":
763 import_license_response = self.__import_license_nfs(import_license_url)
764 job_status = self.get_job_status(import_license_response)
765 status = import_license_response.status_code
766 if status in self.STATUS_SUCCESS:
767 self.module.exit_json(msg=SUCCESS_IMPORT_MSG, changed=True, job_details=job_status)
768 else:
769 self.module.exit_json(msg=FAILURE_IMPORT_MSG, failed=True, job_details=job_status)
770
771 def __import_license_local(self, import_license_url, resource_id):
772 """
773 Import a license locally.
774
775 Args:
776 module (object): The Ansible module object.
777 import_license_url (str): The URL for importing the license.
778 resource_id (str): The ID of the resource.
779
780 Returns:
781 dict: The import status of the license.
782 """
783 payload = {}
784 path = self.module.params.get('share_parameters').get('share_name')
785 if not (os.path.exists(path) or os.path.isdir(path)):
786 self.module.exit_json(msg=INVALID_DIRECTORY_MSG.format(path=path), failed=True)
787 file_path = self.module.params.get('share_parameters').get('share_name') + "/" + self.module.params.get('share_parameters').get('file_name')
788 file_exits = os.path.exists(file_path)
789 if file_exits:
790 with open(file_path, "rb") as cert:
791 cert_content = cert.read()
792 read_file = base64.encodebytes(cert_content).decode('ascii')
793 else:
794 self.module.exit_json(msg=NO_FILE_MSG, failed=True)
795 payload["LicenseFile"] = read_file
796 payload["FQDD"] = resource_id
797 payload["ImportOptions"] = "Force"
798 try:
799 import_status = self.idrac.invoke_request(import_license_url, "POST", data=payload)
800 except HTTPError as err:
801 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
802 message_details = filter_err.get('error').get('@Message.ExtendedInfo')[0]
803 message_id = message_details.get('MessageId')
804 if 'LIC018' in message_id:
805 self.module.exit_json(msg=message_details.get('Message'), skipped=True)
806 else:
807 self.module.exit_json(msg=message_details.get('Message'), error_info=filter_err, failed=True)
808 return import_status
809
810 def __import_license_http(self, import_license_url):
811 """
812 Imports a license using HTTP.
813
814 Args:
815 module (object): The Ansible module object.
816 import_license_url (str): The URL for importing the license.
817
818 Returns:
819 object: The import status.
820 """
821 payload = {}
822 if self.module.params.get('share_parameters').get('username'):
823 payload["Username"] = self.module.params.get('share_parameters').get('username')
824 if self.module.params.get('share_parameters').get('password'):
825 payload["Password"] = self.module.params.get('share_parameters').get('password')
826
827 payload["TransferProtocol"] = "HTTP" if self.module.params.get('share_parameters').get('share_type') == "http" else "HTTPS"
828 payload["LicenseFileURI"] = (
829 self.module.params.get('share_parameters').get('share_type') +
830 "://" + self.module.params.get('share_parameters').get('ip_address') +
831 self.module.params.get('share_parameters').get('share_name') + "/" +
832 self.module.params.get('share_parameters').get('file_name')
833 )
834 import_status = self.idrac.invoke_request(import_license_url, "POST", data=payload)
835 return import_status
836
837 def __import_license_cifs(self, import_license_url):
838 """
839 Imports a license using CIFS share type.
840
841 Args:
842 self (object): The instance of the class.
843 module (object): The Ansible module object.
844 import_license_url (str): The URL for importing the license.
845
846 Returns:
847 object: The import status of the license.
848 """
849 payload = {}
850 if self.module.params.get('share_parameters').get('workgroup'):
851 payload["Workgroup"] = self.module.params.get('share_parameters').get('workgroup')
852 if self.module.params.get('share_parameters').get('username'):
853 payload["Username"] = self.module.params.get('share_parameters').get('username')
854 if self.module.params.get('share_parameters').get('password'):
855 payload["Password"] = self.module.params.get('share_parameters').get('password')
856 payload["LicenseFileURI"] = (
857 "//" + self.module.params.get('share_parameters').get('ip_address') +
858 self.module.params.get('share_parameters').get('share_name') +
859 "/" + self.module.params.get('share_parameters').get('file_name')
860 )
861 payload["TransferProtocol"] = "CIFS"
862 import_status = self.idrac.invoke_request(import_license_url, "POST", data=payload)
863 return import_status
864
865 def __import_license_nfs(self, import_license_url):
866 """
867 Import a license from an NFS share.
868
869 Args:
870 module (object): The Ansible module object.
871 import_license_url (str): The URL for importing the license.
872
873 Returns:
874 dict: The import status of the license.
875 """
876 payload = {}
877 payload["TransferProtocol"] = "NFS"
878 payload["LicenseFileURI"] = (
879 self.module.params.get('share_parameters').get('ip_address') +
880 self.module.params.get('share_parameters').get('share_name') +
881 "/" + self.module.params.get('share_parameters').get('file_name')
882 )
883 import_status = self.idrac.invoke_request(import_license_url, "POST", data=payload)
884 return import_status
885
886 def __check_file_extension(self):
887 """
888 Check if the file extension of the given file name is valid.
889
890 :param module: The Ansible module object.
891 :type module: AnsibleModule
892
893 :return: None
894 """
895 share_type = self.module.params.get('share_parameters').get('share_type')
896 file_name = self.module.params.get('share_parameters').get('file_name')
897 valid_extensions = {".txt", ".xml"} if share_type == "local" else {".xml"}
898 file_extension = any(file_name.lower().endswith(ext) for ext in valid_extensions)
899 if not file_extension:
900 self.module.exit_json(msg=INVALID_FILE_MSG, failed=True)
901
902 def __get_import_license_url(self):
903 """
904 Get the import license URL.
905
906 :param module: The module object.
907 :type module: object
908 :return: The import license URL.
909 :rtype: str
910 """
911 if self.module.params.get('share_parameters').get('share_type') == "local":
912 uri, error_msg = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
913 if error_msg:
914 self.module.exit_json(msg=error_msg, failed=True)
915 resp = get_dynamic_uri(self.idrac, uri)
916 url = resp.get('Links', {}).get(OEM, {}).get(MANUFACTURER, {}).get(LICENSE_MANAGEMENT_SERVICE, {}).get(ODATA, {})
917 action_resp = get_dynamic_uri(self.idrac, url)
918 import_url = action_resp.get(ACTIONS, {}).get(IMPORT_LOCAL, {}).get('target', {})
919 else:
920 v1_resp = get_dynamic_uri(self.idrac, REDFISH)
921 license_service_url = v1_resp.get('LicenseService', {}).get(ODATA, {})
922 license_service_resp = get_dynamic_uri(self.idrac, license_service_url)
923 import_url = license_service_resp.get(ACTIONS, {}).get(IMPORT_NETWORK_SHARE, {}).get('target', {})
924 return import_url
925
926 def get_job_status(self, license_job_response):
927 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
928 job_tracking_uri = license_job_response.headers.get("Location")
929 job_id = job_tracking_uri.split("/")[-1]
930 job_uri = IDRAC_JOB_URI.format(job_id=job_id, res_uri=res_uri[0])
931 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(self.idrac, job_uri)
932 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
933 if job_failed:
934 if job_dict.get('MessageId') == 'LIC018':
935 self.module.exit_json(msg=job_dict.get('Message'), skipped=True, job_details=job_dict)
936 else:
937 self.module.exit_json(
938 msg=job_dict.get('Message'),
939 failed=True,
940 job_details=job_dict)
941 return job_dict
942
943
944 class LicenseType:
945 _license_classes = {
946 "import": ImportLicense,
947 "export": ExportLicense,
948 "delete": DeleteLicense,
949 }
950
951 @staticmethod
952 def license_operation(idrac, module):
953 """
954 Perform a license operation based on the given parameters.
955
956 :param idrac: The IDRAC object.
957 :type idrac: IDRAC
958 :param module: The Ansible module object.
959 :type module: AnsibleModule
960 :return: The license class object based on the license type.
961 :rtype: LicenseType
962 """
963 license_type = next((param for param in ["import", "export", "delete"] if module.params[param]), None)
964 if not license_type:
965 module.exit_json(msg=NO_OPERATION_SKIP_MSG, skipped=True)
966 license_class = LicenseType._license_classes.get(license_type)
967 return license_class(idrac, module)
968
969
970 def main():
971 """
972 Main function that serves as the entry point for the program.
973
974 This function retrieves the argument specification using the `get_argument_spec` function and updates it with the `idrac_auth_params`.
975 It then creates an `AnsibleModule` object with the updated argument specification, specifying the mutually exclusive arguments,
976 required arguments if conditions are met, and setting `supports_check_mode` to `False`.
977
978 The function then attempts to establish a connection with the iDRAC Redfish API using the `iDRACRedfishAPI` class.
979 If the iDRAC version is supported, the function creates a `LicenseType` object using the `license_operation` method of the
980 `LicenseType` class and calls the `execute` method on the `license_obj` object, passing in the `module` object.
981
982 If an `HTTPError` occurs, the function loads the error response as JSON, removes a specific key using a regular expression pattern,
983 and exits with the error message, the filtered error information, and sets `failed` to `True`.
984
985 If a `URLError` occurs, the function exits with the error message and sets `unreachable` to `True`.
986
987 If any of the following errors occur: `SSLValidationError`, `ConnectionError`, `TypeError`, `ValueError`, or `OSError`, the function
988 exits with the error message and sets `failed` to `True`.
989
990 Parameters:
991 None
992
993 Returns:
994 None
995 """
996 specs = get_argument_spec()
997
998 module = IdracAnsibleModule(
999 argument_spec=specs,
1000 mutually_exclusive=[("import", "export", "delete")],
1001 required_if=[
1002 ["import", True, ("share_parameters",)],
1003 ["export", True, ("license_id", "share_parameters",)],
1004 ["delete", True, ("license_id",)]
1005 ],
1006 supports_check_mode=False
1007 )
1008
1009 try:
1010 with iDRACRedfishAPI(module.params) as idrac:
1011 license_obj = LicenseType.license_operation(idrac, module)
1012 if license_obj:
1013 license_obj.execute()
1014 except HTTPError as err:
1015 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
1016 module.exit_json(msg=str(err), error_info=filter_err, failed=True)
1017 except URLError as err:
1018 module.exit_json(msg=AUTH_ERROR_MSG.format(ip=module.params.get("idrac_ip"), error=str(err)), unreachable=True)
1019 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
1020 module.exit_json(msg=str(err), failed=True)
1021
1022
1023 def get_argument_spec():
1024 """
1025 Returns a dictionary containing the argument spec for the get_argument_spec function.
1026 The argument spec is a dictionary that defines the parameters and their types and options for the function.
1027 The dictionary has the following keys:
1028 - "license_id": A string representing the license ID.
1029 - "delete": A boolean representing whether to delete the license.
1030 - "export": A boolean representing whether to export the license.
1031 - "import": A boolean representing whether to import the license.
1032 - "share_parameters": A dictionary representing the share parameters.
1033 - "type": A string representing the share type.
1034 - "options": A dictionary representing the options for the share parameters.
1035 - "share_type": A string representing the share type.
1036 - "file_name": A string representing the file name.
1037 - "ip_address": A string representing the IP address.
1038 - "share_name": A string representing the share name.
1039 - "workgroup": A string representing the workgroup.
1040 - "username": A string representing the username.
1041 - "password": A string representing the password.
1042 - "ignore_certificate_warning": A string representing whether to ignore certificate warnings.
1043 - "proxy_support": A string representing the proxy support.
1044 - "proxy_type": A string representing the proxy type.
1045 - "proxy_server": A string representing the proxy server.
1046 - "proxy_port": A integer representing the proxy port.
1047 - "proxy_username": A string representing the proxy username.
1048 - "proxy_password": A string representing the proxy password.
1049 - "required_if": A list of lists representing the required conditions for the share parameters.
1050 - "required_together": A list of lists representing the required conditions for the share parameters.
1051 - "resource_id": A string representing the resource ID.
1052 """
1053 return {
1054 "license_id": {"type": 'str', "aliases": ['entitlement_id']},
1055 "delete": {"type": 'bool', "default": False},
1056 "export": {"type": 'bool', "default": False},
1057 "import": {"type": 'bool', "default": False},
1058 "share_parameters": {
1059 "type": 'dict',
1060 "options": {
1061 "share_type": {
1062 "type": 'str',
1063 "default": 'local',
1064 "choices": ['local', 'nfs', 'cifs', 'http', 'https']
1065 },
1066 "file_name": {"type": 'str'},
1067 "ip_address": {"type": 'str'},
1068 "share_name": {"type": 'str'},
1069 "workgroup": {"type": 'str'},
1070 "username": {"type": 'str'},
1071 "password": {"type": 'str', "no_log": True},
1072 "ignore_certificate_warning": {
1073 "type": 'str',
1074 "default": "off",
1075 "choices": ["off", "on"]
1076 },
1077 "proxy_support": {
1078 "type": 'str',
1079 "default": "off",
1080 "choices": ["off", "default_proxy", "parameters_proxy"]
1081 },
1082 "proxy_type": {
1083 "type": 'str',
1084 "default": 'http',
1085 "choices": ['http', 'socks']
1086 },
1087 "proxy_server": {"type": 'str'},
1088 "proxy_port": {"type": 'int', "default": 80},
1089 "proxy_username": {"type": 'str'},
1090 "proxy_password": {"type": 'str', "no_log": True}
1091 },
1092 "required_if": [
1093 ["share_type", "local", ["share_name"]],
1094 ["share_type", "nfs", ["ip_address", "share_name"]],
1095 ["share_type", "cifs", ["ip_address", "share_name", "username", "password"]],
1096 ["share_type", "http", ["ip_address", "share_name"]],
1097 ["share_type", "https", ["ip_address", "share_name"]],
1098 ["proxy_support", "parameters_proxy", ["proxy_server"]]
1099 ],
1100 "required_together": [
1101 ("username", "password"),
1102 ("proxy_username", "proxy_password")
1103 ]
1104 },
1105 "resource_id": {"type": 'str'}
1106 }
1107
1108
1109 if __name__ == '__main__':
1110 main()