Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.9.0
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_baseline_profile
20 short_description: Create, modify, or delete baseline profile
21 version_added: "9.9.0"
22 description: This module allows you to create, modify, or delete an OpenManage Enterprise Integration for VMware Center (OMEVV) baseline profile.
23 extends_documentation_fragment:
24 - dellemc.openmanage.omevv_auth_options
25 options:
26 state:
27 description:
28 - C(present) creates a baseline profile or modifies an existing profile if the profile with the same name already exists.
29 - C(absent) deletes the baseline profile.
30 - I(repository_profile), I(cluster), I(days) and I(time) is required when creating a new baseline profile.
31 - Either I(profile_name) or I(profile_id) is required when I(state) is C(absent).
32 type: str
33 choices: [present, absent]
34 default: present
35 name:
36 description:
37 - Name of the baseline profile.
38 type: str
39 required: true
40 description:
41 description:
42 - Description of the baseline profile.
43 type: str
44 cluster:
45 description:
46 - List of cluster(s) for baseline profile creation.
47 - This parameter is required when I(state) is C(present) and while creating a new profile.
48 type: list
49 elements: str
50 repository_profile:
51 description:
52 - Repository profile for baseline creation.
53 - This is required when I(state) is C(present) and while creating a new profile.
54 type: str
55 days:
56 description:
57 - Required days of a week on when the job must run.
58 - This is required when I(state) is C(present) and while creating a new profile.
59 type: list
60 elements: str
61 choices: [sunday, monday, tuesday, wednesday, thursday, friday, saturday, all]
62 time:
63 description:
64 - Time at when the job must run, and is 24 hours format.
65 - The format must be HH:MM.
66 - This is required when I(state) is C(present) and while creating a new profile.
67 type: str
68 job_wait:
69 description: Whether to wait till completion of the job.
70 type: bool
71 default: true
72 job_wait_timeout:
73 description:
74 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
75 - This is applicable when I(job_wait) is C(true).
76 type: int
77 default: 1200
78 requirements:
79 - "python >= 3.9.6"
80 author:
81 - "Saksham Nautiyal (@Saksham-Nautiyal)"
82 attributes:
83 check_mode:
84 description: Runs task to validate without performing action on the target machine.
85 support: full
86 diff_mode:
87 description: Runs the task to report the changes that are made or the changes that must be applied.
88 support: full
89 notes:
90 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
91 """
92
93 EXAMPLES = r"""
94 ---
95 - name: Create a baseline profile for multiple cluster
96 dellemc.openmanage.omevv_baseline_profile:
97 hostname: "192.168.0.1"
98 vcenter_uuid: "xxxxx"
99 vcenter_username: "username"
100 vcenter_password: "password"
101 ca_path: "path/to/ca_file"
102 state: "present"
103 name: "profile-1"
104 repository_profile: "repository-profile"
105 cluster:
106 - "cluster-1"
107 - "cluster-2"
108 days:
109 - "sunday"
110 - "wednesday"
111 time: "22:10"
112
113 - name: Modify a baseline profile
114 dellemc.openmanage.omevv_baseline_profile:
115 hostname: "192.168.0.1"
116 vcenter_uuid: "xxxxx"
117 vcenter_username: "username"
118 vcenter_password: "password"
119 ca_path: "path/to/ca_file"
120 state: "present"
121 name: "profile-1"
122 new_name: "profile-newname"
123 repository_profile: "repository-profile"
124 cluster:
125 - "cluster-1"
126 - "cluster-2"
127 days:
128 - "sunday"
129 time: "05:00"
130
131 - name: Delete a specific baseline profile
132 dellemc.openmanage.omevv_baseline_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 baseline profile."
149 error_info:
150 description: Details of the module HTTP Error.
151 returned: on HTTP error
152 type: dict
153 sample:
154 {
155 "errorCode": "18001",
156 "message": "Baseline profile with name Test already exists."
157 }
158 '''
159 import json
160 import time
161 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
162 from ansible.module_utils.urls import ConnectionError
163 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv import RestOMEVV, OMEVVAnsibleModule
164 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import validate_job_wait, validate_time
165 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv_utils.omevv_firmware_utils import OMEVVFirmwareProfile, OMEVVBaselineProfile
166 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv_utils.omevv_info_utils import OMEVVInfo
167
168
169 SUCCESS_CREATION_MSG = "Successfully created the baseline profile."
170 FAILED_CREATION_MSG = "Unable to create the baseline profile."
171 SUCCESS_MODIFY_MSG = "Successfully modified the baseline profile."
172 FAILED_MODIFY_MSG = "Unable to modify the baseline profile."
173 SUCCESS_DELETION_MSG = "Successfully deleted the baseline profile."
174 FAILED_DELETION_MSG = "Unable to delete the baseline profile."
175 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."
176 CHANGES_FOUND_MSG = "Changes found to be applied."
177 CHANGES_NOT_FOUND_MSG = "No changes found to be applied."
178 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The value for the 'job_wait_timeout' parameter cannot be negative or zero."
179 UNREACHABLE_MSG = "The URL with the {ip}:{port} cannot be reached."
180 SOURCE_NOT_FOUND_MSG = "The Requested resource cannot be found."
181 JOB_WAIT_CREATION_MSG = "Successfully submitted the baseline profile creation job."
182 JOB_WAIT_MODIFICATION_MSG = "Successfully submitted the baseline profile modification job."
183
184
185 class BaselineProfile:
186
187 def __init__(self, module, rest_obj):
188 self.module = module
189 self.obj = rest_obj
190 self.omevv_baseline_obj = OMEVVBaselineProfile(self.obj)
191 self.omevv_profile_obj = OMEVVFirmwareProfile(self.obj)
192 self.omevv_info_obj = OMEVVInfo(self.obj)
193
194 def validate_common_params(self):
195 """
196 Validates the common parameters required for baseline profile operations.
197
198 Returns:
199 None: Exits the module with a failure message if validation fails.
200 """
201 # Validate the job wait parameter
202 if validate_job_wait(self.module):
203 self.module.exit_json(msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
204
205 # Validate the time parameter
206 validate_time(self.module.params.get('time'), self.module)
207
208 # Validate the repository profile
209 repository_profile = self.module.params.get('repository_profile')
210 is_valid_repo, err_msg_repo = self.omevv_baseline_obj.validate_repository_profile(repository_profile)
211 if not is_valid_repo:
212 self.module.exit_json(msg=err_msg_repo, failed=True)
213
214 # Validate the cluster names
215 cluster_names = self.module.params.get('cluster')
216 vcenter_uuid = self.module.params.get('vcenter_uuid')
217 is_valid_cluster, err_msg_cluster = self.omevv_baseline_obj.validate_cluster_names(cluster_names, vcenter_uuid)
218 if not is_valid_cluster:
219 self.module.exit_json(msg=err_msg_cluster, failed=True)
220
221 def execute(self):
222 """To be overridden by subclasses to implement specific profile creation or deletion logic."""
223 pass
224
225
226 class CreateBaselineProfile(BaselineProfile):
227
228 def __init__(self, module, rest_obj, existing_profile=None):
229 super().__init__(module, rest_obj)
230 self.existing_profile = existing_profile
231
232 def diff_mode_check(self, payload):
233 cluster_names = self.module.params.get('cluster', [])
234 vcenter_uuid = self.module.params.get('vcenter_uuid')
235 description = self.module.params.get('description')
236 cluster_ids = self.omevv_baseline_obj.get_cluster_id(cluster_names, vcenter_uuid)
237 group_ids = self.omevv_baseline_obj.get_group_ids_for_clusters(vcenter_uuid, cluster_names)
238
239 cluster_groups = [
240 {
241 "clusterID": cluster_id,
242 "clusterName": cluster_name,
243 "omevv_groupID": group_id
244 }
245 for cluster_name, cluster_id, group_id in zip(cluster_names, cluster_ids, group_ids)
246 ]
247
248 filtered_payload = {
249 "name": payload.get("name"),
250 # "firmwareRepoId": payload.get("firmwareRepoId"),
251 "repository_profile": self.module.params.get('repository_profile'),
252 "clusterGroups": cluster_groups,
253 "description": description,
254 "jobSchedule": payload.get('jobSchedule')
255 }
256
257 diff = {
258 "before": {},
259 "after": {k: v for k, v in filtered_payload.items() if v is not None}
260 }
261 return diff
262
263 def perform_create_baseline_profile(self, payload):
264 diff = {}
265 vcenter_uuid = self.module.params.get('vcenter_uuid')
266 response, err_msg = self.omevv_baseline_obj.create_baseline_profile(
267 name=payload.get('name'),
268 firmware_repo_id=payload.get('firmwareRepoId'),
269 group_ids=payload.get('groupIds'),
270 job_schedule=payload.get('jobSchedule'),
271 vcenter_uuid=vcenter_uuid,
272 description=payload.get('description') if 'description' in payload else None
273 )
274 profile_resp = None
275 if response.success:
276 profile_resp = self.omevv_baseline_obj.get_baseline_profile_by_id(response.json_data, vcenter_uuid)
277 job_wait = self.module.params.get('job_wait')
278 if job_wait:
279 while profile_resp["status"] not in ["SUCCESSFUL", "FAILED"]:
280 time.sleep(3)
281 profile_resp = self.omevv_baseline_obj.get_baseline_profile_by_id(response.json_data, vcenter_uuid)
282
283 diff = self.diff_mode_check(payload)
284 if self.module._diff and profile_resp["status"] == "SUCCESSFUL":
285 self.module.exit_json(msg=SUCCESS_CREATION_MSG, baseline_profile_info=profile_resp, diff=diff, changed=True)
286 elif profile_resp["status"] == "SUCCESSFUL":
287 self.module.exit_json(msg=SUCCESS_CREATION_MSG, baseline_profile_info=profile_resp, changed=True)
288 else:
289 self.module.exit_json(msg=FAILED_CREATION_MSG, baseline_profile_info=profile_resp, failed=True)
290 else:
291 self.module.exit_json(msg=JOB_WAIT_CREATION_MSG, baseline_profile_info=profile_resp, changed=True)
292 else:
293 self.module.exit_json(msg=FAILED_CREATION_MSG, baseline_profile_info=profile_resp, failed=True)
294
295 def execute(self):
296 self.validate_common_params()
297 firmware_repo_id = self.omevv_baseline_obj.get_repo_id_by_name(self.module.params.get('repository_profile'))
298 group_ids = self.omevv_baseline_obj.get_group_ids_for_clusters(
299 vcenter_uuid=self.module.params.get('vcenter_uuid'),
300 cluster_names=self.module.params.get('cluster')
301 )
302 job_schedule = self.omevv_baseline_obj.create_job_schedule(self.module.params.get('days'), self.module.params.get('time'))
303 payload = {
304 "name": self.module.params.get('name'),
305 "firmwareRepoId": firmware_repo_id,
306 "groupIds": group_ids
307 }
308 payload["repository_profile"] = self.module.params.get('repository_profile')
309 description = self.module.params.get('description')
310 if description is not None:
311 payload["description"] = description
312 if job_schedule:
313 payload["jobSchedule"] = job_schedule
314
315 if self.module.check_mode and self.module._diff:
316 diff = self.diff_mode_check(payload)
317 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=diff, changed=True)
318
319 if self.module.check_mode:
320 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
321
322 self.perform_create_baseline_profile(payload)
323
324
325 class ModifyBaselineProfile(BaselineProfile):
326
327 def __init__(self, module, rest_obj, existing_profile):
328 super().__init__(module, rest_obj)
329 self.existing_profile = existing_profile
330
331 def diff_mode_check(self, payload):
332 cluster_names = self.module.params.get('cluster', [])
333 vcenter_uuid = self.module.params.get('vcenter_uuid')
334 description = self.module.params.get('description', self.existing_profile.get("description"))
335
336 cluster_groups = []
337
338 for name in cluster_names:
339 cluster_info = self.omevv_info_obj.get_cluster_info(uuid=vcenter_uuid, cluster_name=name)
340
341 if cluster_info:
342 group_id = self.omevv_info_obj.get_group_id_of_cluster(vcenter_uuid, name)
343 cluster_groups.append({
344 "omevv_groupID": group_id,
345 "clusterName": name,
346 "clusterID": cluster_info["entityId"]
347 })
348
349 # Retrieve job_schedule from drift API call
350 old_job_schedule_resp = self.omevv_baseline_obj.get_current_job_schedule(
351 self.existing_profile.get("driftJobId"), vcenter_uuid
352 )
353 old_job_schedule = old_job_schedule_resp.get("schedule")
354 new_job_schedule = payload['jobSchedule']
355
356 # Construct the 'after' payload for comparison
357 modified_payload = {
358 "name": self.module.params.get("name"),
359 "firmwareRepoId": payload.get("firmwareRepoId"),
360 "firmwareRepoName": self.module.params.get('repository_profile'),
361 "clusterGroups": sorted(
362 [dict(sorted(group.items())) for group in cluster_groups],
363 key=lambda x: x['clusterID']
364 ),
365 "description": description,
366 "jobSchedule": new_job_schedule
367 }
368 filtered_existing_profile = {
369 k: v for k, v in self.existing_profile.items() if k in modified_payload
370 }
371 filtered_existing_profile["jobSchedule"] = old_job_schedule
372 filtered_existing_profile["clusterGroups"] = sorted(
373 [dict(sorted(group.items())) for group in filtered_existing_profile["clusterGroups"]],
374 key=lambda x: x['clusterID']
375 )
376
377 if filtered_existing_profile == modified_payload:
378 return {"before": {}, "after": {}}
379 else:
380 return {
381 "before": {k: v for k, v in filtered_existing_profile.items() if v is not None},
382 "after": {k: v for k, v in modified_payload.items() if v is not None}
383 }
384
385 def perform_modify_baseline_profile(self, payload, diff_before_modify):
386 diff = diff_before_modify
387 profile_id = self.existing_profile.get('id')
388 vcenter_uuid = self.module.params.get('vcenter_uuid')
389
390 response, err_msg = self.omevv_baseline_obj.modify_baseline_profile(
391 add_group_ids=payload.get('addgroupIds'),
392 remove_group_ids=payload.get('removeGroupIds'),
393 profile_id=profile_id,
394 vcenter_uuid=vcenter_uuid,
395 firmware_repo_id=payload.get('firmwareRepoId'),
396 job_schedule=payload.get('jobSchedule'),
397 description=payload.get('description') if 'description' in payload else None
398 )
399 job_wait = self.module.params.get('job_wait')
400 profile_resp = None
401 if response.success:
402 profile_resp = self.omevv_baseline_obj.get_baseline_profile_by_id(profile_id, vcenter_uuid)
403 if job_wait:
404 while profile_resp["status"] not in ["SUCCESSFUL", "FAILED"]:
405 time.sleep(3)
406 profile_resp = self.omevv_baseline_obj.get_baseline_profile_by_id(profile_id, vcenter_uuid)
407
408 if self.module._diff and profile_resp["status"] == "SUCCESSFUL":
409 self.module.exit_json(msg=SUCCESS_MODIFY_MSG, baseline_profile_info=profile_resp, diff=diff, changed=True)
410 elif profile_resp["status"] == "SUCCESSFUL":
411 self.module.exit_json(msg=SUCCESS_MODIFY_MSG, baseline_profile_info=profile_resp, changed=True)
412 else:
413 self.module.exit_json(msg=FAILED_MODIFY_MSG, baseline_profile_info=profile_resp, failed=True)
414 else:
415 self.module.exit_json(msg=JOB_WAIT_MODIFICATION_MSG, baseline_profile_info=profile_resp, changed=True)
416 else:
417 self.module.exit_json(msg=FAILED_MODIFY_MSG, failed=True)
418
419 def execute(self):
420 self.validate_common_params()
421 add_group_ids, remove_group_ids = self.omevv_baseline_obj.get_add_remove_group_ids(
422 self.existing_profile,
423 self.module.params.get('vcenter_uuid'),
424 self.module.params.get('cluster')
425 )
426
427 job_schedule = self.omevv_baseline_obj.create_job_schedule(
428 self.module.params.get('days'),
429 self.module.params.get('time')
430 )
431
432 repository_name = self.module.params.get("repository_profile")
433 firmware_repo_id = self.omevv_baseline_obj.get_repo_id_by_name(repository_name)
434
435 # Prepare the new payload
436 new_payload = {
437 "addgroupIds": add_group_ids,
438 "removeGroupIds": remove_group_ids,
439 "jobSchedule": job_schedule,
440 "description": self.module.params.get("description", self.existing_profile.get("description")),
441 "firmwareRepoId": firmware_repo_id,
442 "modifiedBy": "[email protected]"
443 }
444
445 diff = self.diff_mode_check(new_payload)
446 if not diff["before"] and not diff["after"]:
447 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
448
449 if self.module.check_mode and self.module._diff:
450 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=diff, changed=True)
451
452 if self.module.check_mode:
453 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
454
455 self.perform_modify_baseline_profile(new_payload, diff)
456
457
458 class DeleteBaselineProfile(BaselineProfile):
459
460 def __init__(self, module, rest_obj, profile_name):
461 super().__init__(module, rest_obj)
462 self.profile_name = profile_name
463
464 def diff_mode_check(self, payload):
465 diff = {}
466 diff_dict = {}
467 diff_dict["name"] = payload["name"]
468 diff_dict["description"] = payload["description"]
469 diff_dict["firmwareRepoId"] = payload["firmwareRepoId"]
470 diff_dict["firmwareRepoName"] = payload["firmwareRepoName"]
471 diff_dict["clusterGroups"] = payload["clusterGroups"]
472 if self.module._diff:
473 diff = dict(
474 before=diff_dict,
475 after={}
476 )
477 return diff
478
479 def perform_delete_baseline_profile(self, profile_resp):
480 diff = {}
481 diff = self.diff_mode_check(profile_resp)
482 vcenter_uuid = self.module.params.get('vcenter_uuid')
483 resp = self.omevv_baseline_obj.delete_baseline_profile(profile_resp["id"], vcenter_uuid)
484 if resp.success:
485 if self.module._diff:
486 self.module.exit_json(msg=SUCCESS_DELETION_MSG, baseline_profile_info={}, diff=diff, changed=True)
487 self.module.exit_json(msg=SUCCESS_DELETION_MSG, baseline_profile_info={}, changed=True)
488 else:
489 self.module.exit_json(msg=FAILED_DELETION_MSG, failed=True)
490
491 def execute(self):
492 vcenter_uuid = self.module.params.get('vcenter_uuid')
493 profile_exists = self.omevv_baseline_obj.get_baseline_profile_by_name(self.profile_name, vcenter_uuid)
494
495 if profile_exists and self.module.check_mode and self.module._diff:
496 diff = self.diff_mode_check(profile_exists)
497 self.module.exit_json(msg=CHANGES_FOUND_MSG, diff=diff, changed=True)
498 if not profile_exists and self.module.check_mode:
499 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
500 if not profile_exists and not self.module.check_mode and self.module._diff:
501 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, diff={"before": {}, "after": {}}, changed=False)
502 if not profile_exists and not self.module.check_mode:
503 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
504 if profile_exists and not self.module.check_mode:
505 self.perform_delete_baseline_profile(profile_exists)
506 if profile_exists and self.module.check_mode:
507 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
508
509
510 def main():
511 argument_spec = {
512 "state": {"type": 'str', "choices": ['present', 'absent'], "default": 'present'},
513 "name": {"required": True, "type": 'str'},
514 "cluster": {"type": 'list', "elements": 'str'},
515 "description": {"type": 'str'},
516 "days": {
517 "type": 'list', "elements": 'str',
518 "choices": ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'all']
519 },
520 "time": {"type": 'str', "required": False},
521 "repository_profile": {"type": 'str'},
522 "job_wait": {"type": 'bool', "default": True},
523 "job_wait_timeout": {"type": 'int', "default": 1200}
524 }
525
526 module = OMEVVAnsibleModule(
527 argument_spec=argument_spec,
528 required_if=[
529 ["state", "present", ["repository_profile", "cluster", "days", "time"]],
530 ["state", "absent", ["name"]]
531 ],
532 supports_check_mode=True
533 )
534
535 try:
536 with RestOMEVV(module.params) as rest_obj:
537 profile_name = module.params.get('name')
538 vcenter_uuid = module.params.get('vcenter_uuid')
539 omevv_baseline_profile = OMEVVBaselineProfile(rest_obj)
540
541 omevv_obj = None
542 if module.params.get('state') == 'present':
543 existing_profile = omevv_baseline_profile.get_baseline_profile_by_name(
544 profile_name, vcenter_uuid)
545 omevv_obj = (
546 ModifyBaselineProfile(module, rest_obj, existing_profile)
547 if existing_profile
548 else CreateBaselineProfile(module, rest_obj, existing_profile)
549 )
550
551 elif module.params.get('state') == 'absent':
552 omevv_obj = DeleteBaselineProfile(
553 module, rest_obj, profile_name)
554
555 omevv_obj.execute()
556
557 except HTTPError as err:
558 """Handle HTTPError responses and structure the response data."""
559 response_data = {"msg": str(err), "failed": True}
560 error_info = {}
561
562 try:
563 error_info = json.load(err)
564 except ValueError:
565 # If the error can't be loaded as JSON, capture it as a plain string
566 error_info["message"] = str(err)
567 error_info["type"] = "HTTPError"
568
569 if err.code == 500:
570 response_data["msg"] = error_info.get("message", str(error_info))
571 elif err.code == 404:
572 response_data["msg"] = SOURCE_NOT_FOUND_MSG
573 else:
574 response_data.update({
575 "msg": error_info.get("message", str(error_info)),
576 "error_info": error_info
577 })
578 module.exit_json(**response_data)
579 except URLError as err:
580 """Handle URLError responses and provide structured error info."""
581 response_data = {
582 "msg": f"The URL with IP {module.params.get('hostname')} and port {module.params.get('port')} cannot be reached.",
583 "unreachable": True,
584 "error_info": {"message": str(err), "type": "URLError"}
585 }
586 module.exit_json(**response_data)
587 except (IOError, ValueError, TypeError, ConnectionError,
588 AttributeError, IndexError, KeyError, OSError) as err:
589 module.exit_json(msg=str(err), failed=True)
590
591
592 if __name__ == '__main__':
593 main()