Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.1
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: omevv_firmware_repository_profile
20 short_description: Create, modify, or delete OMEVV firmware repository profile
21 version_added: "9.8.0"
22 description: This module allows you to create, modify, or delete an OpenManage Enterprise Integration for VMware Center (OMEVV) firmware repository profile.
23 extends_documentation_fragment:
24 - dellemc.openmanage.omevv_auth_options
25 options:
26 state:
27 description:
28 - C(present) creates an OMEVV firmware repository profile or modifies an existing profile if the profile with the same name exists.
29 - C(absent) deletes the OMEVV firmware repository profile.
30 - Either I(profile_name) or I(profile_id) is required when I(state) is C(absent).
31 type: str
32 choices: [present, absent]
33 default: present
34 name:
35 description:
36 - Name of the OMEVV firmware repository profile.
37 - This parameter is required for modification operation when I(state) is C(absent).
38 type: str
39 description:
40 description:
41 - Description of OMEVV firmware repository profile.
42 type: str
43 new_name:
44 description: Name of the new OMEVV profile name when modify operation is performed.
45 type: str
46 protocol_type:
47 description:
48 - C(NFS) represents the NFS share path.
49 - C(CIFS) represents the NFS share path.
50 - C(HTTP) represents the HTTP share path.
51 - C(HTTPS) represents the HTTPS share path.
52 - This parameter is required when I(state) is C(present) and a new profile is created.
53 type: str
54 choices: [NFS, CIFS, HTTP, HTTPS]
55 catalog_path:
56 description:
57 - Absolute path of the catalog.
58 - HTTP, HTTPS, NFS, and CIFS paths are supported.
59 - This parameter is required when I(state) is C(present).
60 type: str
61 share_username:
62 description:
63 - Username of the share.
64 - This parameter is required when I(catalog_path) is HTTPS or CIFS.
65 type: str
66 share_password:
67 description:
68 - Password of the share.
69 - This parameter is required when I(catalog_path) is HTTPS or CIFS.
70 type: str
71 share_domain:
72 description: Domain of the share.
73 type: str
74 resync:
75 description: Sync the repository profile from the UMP plugin.
76 type: bool
77 default: false
78 username:
79 description:
80 - OpenManage Enterprise or OpenManage Enterprise Modular username.
81 - If I(resync) is true, then I(username) is required.
82 type: str
83 required: false
84 password:
85 description:
86 - OpenManage Enterprise or OpenManage Enterprise Modular password.
87 - If I(resync) is true, then I(password) is required.
88 type: str
89 required: false
90 requirements:
91 - "python >= 3.9.6"
92 author:
93 - "Shivam Sharma(@ShivamSh3)"
94 - "Meenakshi Dembi(@meenakshidembi691)"
95 attributes:
96 check_mode:
97 description: Runs task to validate without performing action on the target machine.
98 support: full
99 diff_mode:
100 description: Runs the task to report the changes that are made or the changes that must be applied.
101 support: full
102 notes:
103 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
104 """
105
106 EXAMPLES = r"""
107 ---
108 - name: Create an OMEVV firmware repository profile
109 dellemc.openmanage.omevv_firmware_repository_profile:
110 hostname: "192.168.0.1"
111 vcenter_uuid: "xxxxx"
112 vcenter_username: "username"
113 vcenter_password: "password"
114 ca_path: "path/to/ca_file"
115 state: present
116 name: profile-1
117 catalog_path: http://xx.xx.xx.xx/share/Catalog/Catalog.xml
118
119 - name: Modify an OMEVV firmware repository profile
120 dellemc.openmanage.omevv_firmware_repository_profile:
121 hostname: "192.168.0.1"
122 vcenter_uuid: "xxxxx"
123 vcenter_username: "username"
124 vcenter_password: "password"
125 ca_path: "path/to/ca_file"
126 state: present
127 name: profile-1
128 new_name: profile-2
129 catalog_path: http://xx.xx.xx.xx/new_share/Catalog/Catalog.xml
130
131 - name: Delete an OMEVV firmware repository profile
132 dellemc.openmanage.omevv_firmware_repository_profile:
133 hostname: "192.168.0.1"
134 vcenter_uuid: "xxxxx"
135 vcenter_username: "username"
136 vcenter_password: "password"
137 ca_path: "path/to/ca_file"
138 state: absent
139 name: profile-1
140 """
141
142 RETURN = r'''
143 ---
144 msg:
145 type: str
146 description: Status of the profile operation.
147 returned: always
148 sample: "Successfully created the OMEVV firmware repository profile."
149 error_info:
150 description: Details of the HTTP Error.
151 returned: on HTTP error
152 type: dict
153 sample:
154 {
155 "errorCode": "18001",
156 "message": "Repository profile with name Test already exists."
157 }
158 '''
159 import json
160 import time
161 import re
162 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
163 from ansible.module_utils.urls import ConnectionError
164 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv import RestOMEVV, OMEVVAnsibleModule
165 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv_utils.omevv_firmware_utils import OMEVVFirmwareProfile
166 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
167 from ansible.module_utils.common.dict_transformations import recursive_diff
168
169 ODATA_REGEX = "(.*?)@odata"
170 ODATA = "@odata.id"
171 XML_EXT = ".xml"
172 GZ_EXT = ".gz"
173 PLUGINS_URI = "PluginService/Plugins"
174 UMP_URI = "UpdateManagementService/Repositories"
175 MESSAGE_EXTENDED_INFO = "@Message.ExtendedInfo"
176 SUCCESS_CREATION_MSG = "Successfully created the OMEVV firmware repository profile."
177 SUCCESS_CREATION_RESYNC_MSG = "Successfully resynced and created the OMEVV firmware repository profile."
178 FAILED_CREATION_MSG = "Unable to create the OMEVV firmware repository profile."
179 SUCCESS_MODIFY_MSG = "Successfully modified the OMEVV firmware repository profile."
180 SUCCESS_MODIFY_RESYNC_MSG = "Successfully resynced and modified the OMEVV firmware repository profile."
181 FAILED_MODIFY_MSG = "Unable to modify the OMEVV firmware repository profile"
182 SUCCESS_DELETION_MSG = "Successfully deleted the OMEVV firmware repository profile."
183 SUCCESS_DELETION_RESYNC_MSG = "Successfully resynced and deleted the OMEVV firmware repository profile."
184 FAILED_DELETION_MSG = "Unable to delete the OMEVV firmware repository profile."
185 PROFILE_NOT_FOUND_MSG = "Unable to delete the profile {profile_name} because the profile name is invalid. Enter a valid profile name and retry the operation."
186 FAILED_CONN_MSG = "Unable to complete the operation. Please check the connection details."
187 CHANGES_FOUND_MSG = "Changes found to be applied."
188 CHANGES_NOT_FOUND_MSG = "No changes found to be applied."
189 UMP_PLUGIN_NOT_FOUND_MSG = "Update Manager Plug-in (UMP) is not installed. Please install the UMP plugin and retry the operation."
190 SUCCESS_RESYNC_MSG = "Successfully resynced the OMEVV firmware repository profile."
191 FAILED_RESYNC_MSG = "Unable to resync the OMEVV firmware repository profile."
192 NO_OPERATION_SKIP_MSG = "The operation is skipped."
193
194
195 class FirmwareRepositoryProfile:
196 diff_dict = {
197 'before': {},
198 'after': {}
199 }
200
201 def __init__(self, module, rest_obj):
202 self.module = module
203 self.obj = rest_obj
204 self.omevv_profile_obj = OMEVVFirmwareProfile(self.obj)
205
206 def get_payload_details(self):
207 payload = {}
208 payload["profileName"] = self.module.params.get('name')
209 payload["protocolType"] = self.module.params.get('protocol_type')
210 payload["sharePath"] = self.module.params.get('catalog_path')
211 if self.module.params.get('description') is not None:
212 payload["description"] = self.module.params.get('description')
213 payload["profileType"] = "Firmware"
214 payload["shareCredential"] = {
215 "username": self.module.params.get('share_username'),
216 "password": self.module.params.get('share_password'),
217 "domain": self.module.params.get('share_domain')
218 }
219 return payload
220
221 def test_connection(self, protocol_type, catalog_path):
222 resp = self.omevv_profile_obj.test_connection(
223 protocol_type=self.module.params.get('protocol_type') if protocol_type is None else protocol_type,
224 catalog_path=self.module.params.get('catalog_path') if catalog_path is None else catalog_path,
225 share_username=self.module.params.get('share_username'),
226 share_password=self.module.params.get('share_password'),
227 share_domain=self.module.params.get('share_domain')
228 )
229 if resp:
230 return True
231 else:
232 self.module.exit_json(msg=FAILED_CONN_MSG, failed=True)
233
234 def trim_api_response(self, api_response):
235 trimmed_resp = {}
236 if api_response["description"] is not None:
237 trimmed_resp["description"] = api_response["description"]
238 file_name = api_response["fileName"].replace('\\', '/').rsplit('/', 1)[-1] if api_response.get("fileName") else api_response.get("fileName", "")
239 if api_response["protocolType"] == "CIFS" and not (api_response["sharePath"].endswith(XML_EXT) or api_response["sharePath"].endswith(GZ_EXT)):
240 api_response["sharePath"] = api_response["sharePath"].rstrip('\\') + '\\' + file_name
241 elif not (api_response["sharePath"].endswith(XML_EXT) or api_response["sharePath"].endswith(GZ_EXT)):
242 api_response["sharePath"] = api_response["sharePath"].rstrip('/') + '/' + file_name
243 trimmed_resp["profileName"] = api_response["profileName"]
244 trimmed_resp["sharePath"] = api_response["sharePath"]
245 return trimmed_resp
246
247 def execute(self):
248 # To be overridden by the subclasses
249 pass
250
251
252 class CreateFirmwareRepositoryProfile(FirmwareRepositoryProfile):
253
254 def __init__(self, module, rest_obj):
255 self.module = module
256 self.obj = rest_obj
257 super().__init__(module, rest_obj)
258
259 def diff_mode_check(self, payload):
260 if "shareCredential" in payload:
261 payload.pop("shareCredential")
262 self.diff_dict['before'].update({})
263 self.diff_dict['after'].update(payload)
264
265 def create_firmware_repository_profile(self):
266 payload = self.get_payload_details()
267 res = FirmwareRepositoryProfile.test_connection(self, None, None)
268 if res:
269 self.diff_mode_check(payload)
270 resp, _err_msg = self.omevv_profile_obj.create_firmware_repository_profile(
271 name=self.module.params.get('name'),
272 catalog_path=self.module.params.get('catalog_path'),
273 description=self.module.params.get('description'),
274 protocol_type=self.module.params.get('protocol_type'),
275 share_username=self.module.params.get('share_username'),
276 share_password=self.module.params.get('share_password'),
277 share_domain=self.module.params.get('share_domain')
278 )
279 if resp.success:
280 self.diff_mode_behaviour(resp)
281 else:
282 self.module.exit_json(msg=FAILED_CREATION_MSG, failed=True)
283
284 def diff_mode_behaviour(self, resp):
285 profile_resp = self.omevv_profile_obj.get_firmware_repository_profile_by_id(resp.json_data)
286 while profile_resp.json_data["status"] != "Success" and profile_resp.json_data["status"] != "Failed":
287 time.sleep(3)
288 profile_resp = self.omevv_profile_obj.get_firmware_repository_profile_by_id(resp.json_data)
289 if self.module._diff and profile_resp.json_data["status"] == "Success" and self.module.params.get('resync'):
290 self.module.exit_json(msg=SUCCESS_CREATION_RESYNC_MSG, profile_info=profile_resp.json_data, diff=self.diff_dict, changed=True)
291 if self.module._diff and profile_resp.json_data["status"] == "Success":
292 self.module.exit_json(msg=SUCCESS_CREATION_MSG, profile_info=profile_resp.json_data, diff=self.diff_dict, changed=True)
293 if profile_resp.json_data["status"] == "Success" and self.module.params.get('resync'):
294 self.module.exit_json(msg=SUCCESS_CREATION_RESYNC_MSG, profile_info=profile_resp.json_data, changed=True)
295 if profile_resp.json_data["status"] == "Success":
296 self.module.exit_json(msg=SUCCESS_CREATION_MSG, profile_info=profile_resp.json_data, changed=True)
297 else:
298 self.module.exit_json(msg=FAILED_CREATION_MSG, profile_info=profile_resp.json_data, failed=True)
299
300 def _prepare_modified_payload(self, payload):
301 modified_payload = payload.copy()
302 del modified_payload["protocolType"]
303 del modified_payload["profileType"]
304 del modified_payload["shareCredential"]
305 return modified_payload
306
307 def _normalize_cifs_paths(self, payload, profile_data):
308 if profile_data.get("protocolType") == "CIFS":
309 if payload.get("sharePath"):
310 payload["sharePath"] = payload["sharePath"].replace('/', '\\')
311 if profile_data.get("sharePath"):
312 profile_data["sharePath"] = profile_data["sharePath"].replace('/', '\\')
313
314 def _check_profile_changes(self, modified_payload, profile_exists):
315 if not profile_exists:
316 return False
317
318 trimmed_resp = FirmwareRepositoryProfile.trim_api_response(self, profile_exists)
319 self._normalize_cifs_paths(modified_payload, profile_exists)
320 self._normalize_cifs_paths(modified_payload, trimmed_resp)
321
322 diff = recursive_diff(modified_payload, trimmed_resp)
323 return diff and (diff[0] != diff[1])
324
325 def _handle_new_profile_creation(self, payload):
326 if self.module.check_mode and self.module._diff:
327 FirmwareRepositoryProfile.test_connection(self, None, None)
328 self.diff_mode_check(payload)
329 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=self.diff_dict, changed=True)
330 elif self.module.check_mode:
331 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
332 else:
333 self.create_firmware_repository_profile()
334
335 def _handle_existing_profile_no_changes(self):
336 if self.module._diff:
337 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False, diff={"before": {}, "after": {}})
338 else:
339 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
340
341 def _handle_existing_profile_with_changes(self):
342 omevv_obj = ModifyFirmwareRepositoryProfile(self.module, self.obj)
343 omevv_obj.execute()
344
345 def execute(self):
346 payload = self.get_payload_details()
347 result = self.omevv_profile_obj.get_firmware_repository_profile()
348 profile = self.module.params.get('name')
349 profile_exists = self.omevv_profile_obj.search_profile_name(result, profile)
350
351 if not profile_exists:
352 self._handle_new_profile_creation(payload)
353 else:
354 modified_payload = self._prepare_modified_payload(payload)
355 new_profile = self._check_profile_changes(modified_payload, profile_exists)
356
357 if new_profile:
358 self._handle_existing_profile_with_changes()
359 else:
360 self._handle_existing_profile_no_changes()
361
362
363 class ModifyFirmwareRepositoryProfile(FirmwareRepositoryProfile):
364
365 def __init__(self, module, rest_obj):
366 self.module = module
367 self.obj = rest_obj
368 super().__init__(module, rest_obj)
369
370 def _extract_file_name(self, api_response):
371 return api_response["fileName"].replace('\\', '/').rsplit('/', 1)[-1] if api_response.get("fileName") else api_response.get("fileName", "")
372
373 def _append_file_name_to_path(self, api_response, file_name):
374 if api_response["protocolType"] == "CIFS" and not (api_response["sharePath"].endswith(XML_EXT) or api_response["sharePath"].endswith(GZ_EXT)):
375 api_response["sharePath"] = api_response["sharePath"].rstrip('\\') + '\\' + file_name
376 elif not (api_response["sharePath"].endswith(XML_EXT) or api_response["sharePath"].endswith(GZ_EXT)):
377 api_response["sharePath"] = api_response["sharePath"].rstrip('/') + '/' + file_name
378
379 def _normalize_share_paths(self, api_response, module_response):
380 if api_response["protocolType"] == "CIFS":
381 if api_response.get("sharePath"):
382 api_response["sharePath"] = api_response["sharePath"].replace('/', '\\')
383 if module_response.get("sharePath"):
384 module_response["sharePath"] = module_response["sharePath"].replace('/', '\\')
385 elif api_response["protocolType"] in ("HTTP", "HTTPS"):
386 api_response["sharePath"] = re.sub(r'(?<!:)//+', '/', api_response["sharePath"])
387 module_response["sharePath"] = re.sub(r'(?<!:)//+', '/', module_response["sharePath"])
388
389 def _calculate_field_differences(self, api_response, module_response):
390 diff = {}
391 for key in module_response.keys():
392 if key not in api_response or api_response[key] != module_response[key]:
393 diff[key] = module_response[key]
394 return diff
395
396 def diff_check(self, api_response, module_response):
397 file_name = self._extract_file_name(api_response)
398 self._append_file_name_to_path(api_response, file_name)
399
400 if module_response["sharePath"] is None:
401 module_response["sharePath"] = api_response["sharePath"]
402
403 self._normalize_share_paths(api_response, module_response)
404
405 return self._calculate_field_differences(api_response, module_response)
406
407 def trim_api_response(self, api_response, payload=None):
408 trimmed_resp = {}
409 trimmed_resp["profileName"] = api_response["profileName"]
410 trimmed_resp["sharePath"] = api_response["sharePath"]
411 if payload.get("description") is not None:
412 trimmed_resp["description"] = api_response["description"]
413 return trimmed_resp
414
415 def rec_diff(self, api_response, payload):
416 self.diff_dict = {'before': {}, 'after': {}}
417 trim = self.trim_api_response(api_response, payload)
418 if payload.get("shareCredential") is not None:
419 del payload["shareCredential"]
420 output = recursive_diff(trim, payload)
421 self.diff_dict['before'].update(output[0])
422 self.diff_dict['after'].update(output[1])
423 return self.diff_dict
424
425 def modify_firmware_repository_profile(self, api_response, module_response):
426 protocol_type = api_response["protocolType"]
427 catalog_path = api_response["sharePath"]
428 res = FirmwareRepositoryProfile.test_connection(self, protocol_type, catalog_path)
429 name = self.module.params.get('new_name') if self.module.params.get('new_name') is not None else self.module.params.get('name')
430 if res:
431 self.rec_diff(api_response, module_response)
432 resp, _err_msg = self.omevv_profile_obj.modify_firmware_repository_profile(
433 api_response["id"],
434 name=name,
435 catalog_path=self.module.params.get('catalog_path') if self.module.params.get('catalog_path') is not None else api_response["sharePath"],
436 description=self.module.params.get('description') if self.module.params.get('description') is not None else api_response["description"],
437 share_username=self.module.params.get('share_username'),
438 share_password=self.module.params.get('share_password'),
439 share_domain=self.module.params.get('share_domain')
440 )
441 if resp.success:
442 self.output_modify_response(api_response)
443 else:
444 self.module.exit_json(msg=FAILED_MODIFY_MSG, failed=True)
445
446 def output_modify_response(self, api_response):
447 profile_resp = self.omevv_profile_obj.get_firmware_repository_profile_by_id(api_response["id"])
448 while profile_resp.json_data["status"] != "Success" and profile_resp.json_data["status"] != "Failed":
449 time.sleep(3)
450 profile_resp = self.omevv_profile_obj.get_firmware_repository_profile_by_id(api_response["id"])
451 if self.module._diff and profile_resp.json_data["status"] == "Success" and self.module.params.get('resync'):
452 self.module.exit_json(msg=SUCCESS_MODIFY_RESYNC_MSG, profile_info=profile_resp.json_data, diff=self.diff_dict, changed=True)
453 if self.module._diff and profile_resp.json_data["status"] == "Success":
454 self.module.exit_json(msg=SUCCESS_MODIFY_MSG, profile_info=profile_resp.json_data, diff=self.diff_dict, changed=True)
455 if profile_resp.json_data["status"] == "Success" and self.module.params.get('resync'):
456 self.module.exit_json(msg=SUCCESS_MODIFY_RESYNC_MSG, profile_info=profile_resp.json_data, changed=True)
457 if profile_resp.json_data["status"] == "Success":
458 self.module.exit_json(msg=SUCCESS_MODIFY_MSG, profile_info=profile_resp.json_data, changed=True)
459 else:
460 self.module.exit_json(msg=FAILED_MODIFY_MSG, profile_info=profile_resp.json_data, failed=True)
461
462 def execute(self):
463 module_response = {}
464 payload = self.get_payload_details()
465 del payload["profileType"]
466 del payload["protocolType"]
467 result = self.omevv_profile_obj.get_firmware_repository_profile()
468 profile = self.module.params.get('name')
469 api_response = self.omevv_profile_obj.search_profile_name(result, profile)
470 module_response.update(payload)
471 new_name = self.module.params.get('new_name')
472 profile_name = self.module.params.get('name')
473 module_response["profileName"] = (
474 new_name if new_name is not None else profile_name
475 )
476 del module_response["shareCredential"]
477 diff = self.diff_check(api_response, module_response)
478 if diff and self.module.check_mode and self.module._diff:
479 diff = self.rec_diff(api_response, module_response)
480 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=diff, changed=True)
481 if diff and self.module.check_mode:
482 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
483 if diff and not self.module.check_mode:
484 self.modify_firmware_repository_profile(api_response, module_response)
485 else:
486 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, diff={"before": {}, "after": {}}, changed=False)
487
488
489 class ResyncFirmwareRepositoryProfile(FirmwareRepositoryProfile):
490
491 def __init__(self, module, rest_obj, rest_ome_obj):
492 self.module = module
493 super().__init__(module, rest_obj)
494 self.rest_obj = rest_obj
495 self.ome_obj = rest_ome_obj
496
497 def check_plugin_availability(self):
498 ump_plugin = 0
499 details = self.ome_obj.invoke_request("GET", PLUGINS_URI)
500 resp = details.json_data["value"]
501 for item in resp:
502 if item.get("Name") == "Update Manager":
503 ump_plugin = 1
504 break
505 if not ump_plugin:
506 self.module.exit_json(msg=UMP_PLUGIN_NOT_FOUND_MSG, failed=True)
507
508 def check_mode_support(self):
509 omevv_profiles = self.omevv_profile_obj.get_firmware_repository_profile()
510 res = self.ome_obj.invoke_request("GET", UMP_URI)
511 ump_profiles = res.json_data["value"]
512 relevant_catalog_types = {"ESXi Catalog for Enterprise Servers", "vSAN Catalog for Enterprise Servers"}
513 filtered_ump_profiles = [p for p in ump_profiles if p["CatalogType"] in relevant_catalog_types]
514 not_avail = []
515 omevv_profile_names = {p["profileName"] for p in omevv_profiles}
516 for profile in filtered_ump_profiles:
517 if profile["Name"] not in omevv_profile_names:
518 not_avail.append(profile)
519 self.remove_keys(filtered_ump_profiles, not_avail)
520 if len(not_avail) > 0 and self.module._diff:
521 self.diff_dict['after'].update({"ump_profiles": not_avail})
522 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=self.diff_dict, changed=True)
523 if len(not_avail) > 0:
524 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
525 if len(not_avail) == 0 and self.module._diff:
526 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, diff={"before": {}, "after": {}}, changed=False)
527 if len(not_avail) == 0:
528 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
529
530 def remove_keys(self, filtered_ump_profiles, not_avail):
531 keys_to_remove = {"@odata.type", "@odata.id", "BaseCatalogID", "BaseCatalogName", "AvailableVersions", "DevicesRepo", "UrgentComponentsCount",
532 "RecommendedComponentsCount", "OptionalComponentsCount", "BaselineId", "BaselineName", "BaselineDescription", "BaselineVersion",
533 "RefreshedVersion", "[email protected]", "Size", "Label", "ComponentsCount", "AvailableCatalog", "CatalogType",
534 "Owner", "LastModifiedBy", "DateModified", "Id"}
535 for profile in not_avail:
536 for key in keys_to_remove:
537 if key in profile:
538 del profile[key]
539 for profile in filtered_ump_profiles:
540 for key in keys_to_remove:
541 if key in profile:
542 del profile[key]
543 for item in not_avail:
544 name = item.get('Name', '')
545 version = item.get('Version', '')
546 profilename = name
547 sharepath = "//shared/dell/omc/cifs/idrac/RepositoryStore"
548 profiletype = "Firmware"
549 filename = f"{name}_{version}_Catalog.xml"
550 del item['Name']
551 del item['Version']
552 item['profileName'] = profilename
553 item['sharePath'] = sharepath
554 item['profileType'] = profiletype
555 item['fileName'] = filename
556 item['factoryCreated'] = False
557 item['factoryType'] = "Custom"
558 item['checkCertificate'] = None
559 item['protocolType'] = "Not Applicable"
560 item['createdBy'] = "Not Available"
561 item['modifiedBy'] = "Not Available"
562 item['owner'] = "UMP"
563
564 def sort_profiles(self, profiles):
565 return sorted(profiles, key=lambda x: x["id"])
566
567 def get_not_avail_profiles(self):
568 omevv_profiles = self.omevv_profile_obj.get_firmware_repository_profile()
569 res = self.ome_obj.invoke_request("GET", UMP_URI)
570 ump_profiles = res.json_data["value"]
571 relevant_catalog_types = {"ESXi Catalog for Enterprise Servers", "vSAN Catalog for Enterprise Servers"}
572 filtered_ump_profiles = [p for p in ump_profiles if p["CatalogType"] in relevant_catalog_types]
573 not_avail = []
574 omevv_profile_names = {p["profileName"] for p in omevv_profiles}
575 for profile in filtered_ump_profiles:
576 if profile["Name"] not in omevv_profile_names:
577 not_avail.append(profile)
578 self.remove_keys(filtered_ump_profiles, not_avail)
579 return not_avail
580
581 def execute(self):
582 self.check_plugin_availability()
583 if self.module.check_mode:
584 self.check_mode_support()
585 not_avail = self.get_not_avail_profiles()
586 has_changes = len(not_avail) > 0
587 if not has_changes:
588 if self.module._diff:
589 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG,
590 diff={"before": {"ump_profiles": []}, "after": {"ump_profiles": []}},
591 changed=False)
592 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
593 presync_result = self.omevv_profile_obj.get_firmware_repository_profile()
594 resp = self.omevv_profile_obj.resync_repository_profiles_from_ump()
595 if resp.success:
596 time.sleep(14)
597 postsync_result = self.omevv_profile_obj.get_firmware_repository_profile()
598 presync_ump_profiles = [profile for profile in presync_result if profile.get("owner") == "UMP"]
599 postsync_ump_profiles = [profile for profile in postsync_result if profile.get("owner") == "UMP"]
600 presync_ump_profiles = self.sort_profiles(presync_ump_profiles)
601 postsync_ump_profiles = self.sort_profiles(postsync_ump_profiles)
602 difference = [item for item in postsync_ump_profiles if item not in presync_ump_profiles]
603 diff = has_changes or presync_ump_profiles != postsync_ump_profiles
604 self.diff_mode_behaviour(presync_ump_profiles, postsync_ump_profiles, difference, diff, not_avail)
605 else:
606 self.module.exit_json(msg=FAILED_RESYNC_MSG, failed=True)
607
608 def diff_mode_behaviour(self, presync_ump_profiles, postsync_ump_profiles, difference, diff, not_avail):
609 diff_profiles = difference if difference else not_avail
610 if diff and self.module._diff and self.module.params.get('name') is None:
611 self.diff_dict['after'].update({"ump_profiles": diff_profiles})
612 self.module.exit_json(msg=SUCCESS_RESYNC_MSG, diff=self.diff_dict, firmware_repository_profile=diff_profiles, changed=True)
613 if diff and self.module.params.get('name') is None:
614 self.module.exit_json(msg=SUCCESS_RESYNC_MSG, firmware_repository_profile=postsync_ump_profiles, changed=True)
615 if diff and self.module._diff:
616 self.diff_dict['after'].update({"ump_profiles": diff_profiles})
617 if not diff and self.module.params.get('name') is None and self.module._diff:
618 self.diff_dict['before'].update({"ump_profiles": presync_ump_profiles})
619 self.diff_dict['after'].update({"ump_profiles": postsync_ump_profiles})
620 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, diff=self.diff_dict, changed=False)
621 if not diff and self.module.params.get('name') is None:
622 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
623
624
625 class DeleteFirmwareRepositoryProfile(FirmwareRepositoryProfile):
626
627 def __init__(self, module, rest_obj):
628 self.module = module
629 self.obj = rest_obj
630 super().__init__(module, rest_obj)
631
632 def diff_mode_check(self, payload):
633 diff_dict = {}
634 diff_dict["profileName"] = payload["profileName"]
635 diff_dict["description"] = payload["description"]
636 diff_dict["profileType"] = payload["profileType"]
637 diff_dict["sharePath"] = payload["sharePath"]
638 diff_dict["protocolType"] = payload["protocolType"]
639 self.diff_dict['before'].update(diff_dict)
640 return self.diff_dict
641
642 def delete_firmware_repository_profile(self, api_response):
643 self.diff_mode_check(api_response)
644 resp = self.omevv_profile_obj.delete_firmware_repository_profile(api_response["id"])
645 if resp.success:
646 if self.module._diff and self.module.params.get('resync'):
647 self.module.exit_json(msg=SUCCESS_DELETION_RESYNC_MSG, diff=self.diff_dict, changed=True)
648 if self.module._diff and self.module.params.get('resync'):
649 self.module.exit_json(msg=SUCCESS_DELETION_RESYNC_MSG, diff=self.diff_dict, changed=True)
650 if self.module._diff:
651 self.module.exit_json(msg=SUCCESS_DELETION_MSG, diff=self.diff_dict, changed=True)
652 self.module.exit_json(msg=SUCCESS_DELETION_MSG, changed=True)
653 else:
654 self.module.exit_json(msg=FAILED_DELETION_MSG, failed=True)
655
656 def execute(self):
657 profile = self.module.params.get('name')
658 if profile is None:
659 self.module.exit_json(msg=NO_OPERATION_SKIP_MSG, skipped=True)
660 result = self.omevv_profile_obj.get_firmware_repository_profile()
661 api_response = self.omevv_profile_obj.search_profile_name(result, profile)
662 profile_exists = self.omevv_profile_obj.search_profile_name(result, profile)
663 if profile_exists and self.module.check_mode and self.module._diff:
664 diff = self.diff_mode_check(api_response)
665 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=diff, changed=True)
666 if not profile_exists and self.module.check_mode:
667 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
668 if not profile_exists and not self.module.check_mode and self.module._diff:
669 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, diff={"before": {}, "after": {}}, changed=False)
670 if not profile_exists and not self.module.check_mode:
671 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
672 if profile_exists and not self.module.check_mode:
673 self.delete_firmware_repository_profile(api_response)
674 if profile_exists and self.module.check_mode:
675 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
676
677
678 def main():
679 argument_spec = {
680 "username": {"type": 'str'},
681 "password": {"type": 'str', "no_log": True},
682 "state": {"type": 'str', "choices": ['present', 'absent'], "default": 'present'},
683 "share_username": {"type": 'str'},
684 "share_password": {"type": 'str', "no_log": True},
685 "name": {"type": 'str'},
686 "new_name": {"type": 'str'},
687 "catalog_path": {"type": 'str'},
688 "description": {"type": 'str'},
689 "protocol_type": {"type": 'str', "choices": ['NFS', 'CIFS', 'HTTP', 'HTTPS']},
690 "share_domain": {"type": 'str'},
691 "resync": {"type": 'bool', "default": False}
692 }
693 module = OMEVVAnsibleModule(
694 argument_spec=argument_spec,
695 required_if=[
696 ["protocol_type", "NFS", ("catalog_path",)],
697 ["protocol_type", "CIFS", ("catalog_path", "share_username", "share_password")],
698 ["protocol_type", "HTTP", ("catalog_path",)],
699 ["protocol_type", "HTTPS", ("catalog_path",)],
700 ],
701 supports_check_mode=True)
702 try:
703 with RestOMEVV(module.params) as rest_obj:
704 if module.params.get('resync'):
705 ome_module = OmeAnsibleModule(argument_spec, supports_check_mode=True)
706 with RestOME(ome_module.params, req_session=True) as rest_ome_obj:
707 omevv_obj = ResyncFirmwareRepositoryProfile(module, rest_obj, rest_ome_obj)
708 omevv_obj.execute()
709 if module.params.get('state') == 'present':
710 if module.params.get('name') is None:
711 module.exit_json(msg=NO_OPERATION_SKIP_MSG, skipped=True)
712 omevv_obj = CreateFirmwareRepositoryProfile(module, rest_obj)
713 if module.params.get('state') == 'absent':
714 omevv_obj = DeleteFirmwareRepositoryProfile(module, rest_obj)
715 omevv_obj.execute()
716 except HTTPError as err:
717 if err.code == 500:
718 module.exit_json(msg=json.load(err), failed=True)
719 error_info = json.load(err)
720 code = error_info.get('errorCode')
721 message = error_info.get('message')
722 if '18001' in code and module.check_mode:
723 module.exit_json(msg=CHANGES_NOT_FOUND_MSG)
724 if '500' in code:
725 module.exit_json(msg=message, skipped=True)
726 module.exit_json(msg=message, error_info=error_info, failed=True)
727 except URLError as err:
728 module.exit_json(msg=str(err), unreachable=True)
729 except (IOError, ValueError, TypeError, ConnectionError,
730 AttributeError, IndexError, KeyError, OSError) as err:
731 module.exit_json(msg=str(err), failed=True)
732
733
734 if __name__ == '__main__':
735 main()