Debian Codegraph @

ansible_collections/dellemc/powerflex/plugins/modules/resource_group.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # Copyright: (c) 2024, Dell Technologies
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """ Ansible module for managing resource group deployments on Dell Technologies (Dell) PowerFlex"""
7 from __future__ import (absolute_import, division, print_function)
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 module: resource_group
13 version_added: '2.3.0'
14 short_description: Manage resource group deployments on Dell PowerFlex.
15 description:
16 - Managing resource group deployments on PowerFlex storage system includes deploying,
17 editing, adding nodes and deleting a resource group deployment.
18 author:
19 - Jennifer John (@johnj9) <[email protected]>
20 - Trisha Datta (@trisha-dell) <[email protected]>
21 extends_documentation_fragment:
22 - dellemc.powerflex.powerflex
23 options:
24 resource_group_name:
25 description:
26 - The name of the resource group.
27 - This is a required field to deploy a resource group.
28 - Either I(resource_group_id) or I(resource_group_name) must be specified to perform resource group operations.
29 - Mutually exclusive with I(resource_group_id).
30 type: str
31 resource_group_id:
32 description:
33 - The ID of the resource group.
34 - Either I(resource_group_id) or I(resource_group_name) must be specified to perform resource group operations.
35 - Mutually exclusive with I(resource_group_name).
36 type: str
37 template_name:
38 description:
39 - The name of the published template.
40 - Either I(template_id) or I(template_name) must be specified to deploy a resource group.
41 - Mutually exclusive with I(template_id).
42 type: str
43 template_id:
44 description:
45 - The ID of the published template.
46 - Either I(template_id) or I(template_name) must be specified to deploy a resource group.
47 - Mutually exclusive with I(template_name).
48 type: str
49 firmware_repository_id:
50 description:
51 - The ID of the firmware repository if not using the appliance default catalog.
52 - Mutually exclusive with I(firmware_repository_name).
53 type: str
54 firmware_repository_name:
55 description:
56 - The name of the firmware repository if not using the appliance default catalog.
57 - Mutually exclusive with I(firmware_repository_id).
58 type: str
59 new_resource_group_name:
60 description:
61 - New name of the resource group to rename to.
62 type: str
63 description:
64 description:
65 - The description of the resource group.
66 type: str
67 scaleup:
68 description:
69 - Whether to scale up the resource group. Specify as true to add nodes to the resource group.
70 type: bool
71 default: false
72 clone_node:
73 description:
74 - Resource to duplicate during scaleup, if more than one nodes are available in the resource group.
75 type: str
76 node_count:
77 description:
78 - Number of nodes to clone during scaleup.
79 type: int
80 default: 1
81 validate:
82 description:
83 - Specify as true to validate the deployment of resource group.
84 type: bool
85 default: false
86 schedule_date:
87 description:
88 - Scheduled date for the resource group deployment.
89 - Specify in YYYY-MM-DD HH:MM:SS.sss or YYYY-MM-DD format.
90 type: str
91 state:
92 description:
93 - The state of the resource group.
94 type: str
95 choices: ['absent', 'present']
96 default: 'present'
97 notes:
98 - The I(check_mode) is supported.
99 - Resource group scale up can be done only when deployment is complete.
100 '''
101
102 EXAMPLES = r'''
103 - name: Validate deployment of a resource group
104 dellemc.powerflex.resource_group:
105 hostname: "{{ hostname }}"
106 username: "{{ username }}"
107 password: "{{ password }}"
108 validate_certs: "{{ validate_certs }}"
109 port: "{{ port }}"
110 resource_group_name: "{{ resource_group_name_1 }}"
111 description: ans_rg
112 template_id: c65d0172-8666-48ab-935e-9a0bf69ed66d
113 firmware_repository_id: 8aaa80788b5755d1018b576126d51ba3
114 validate: true
115
116 - name: Deploy a resource group
117 dellemc.powerflex.resource_group:
118 hostname: "{{ hostname }}"
119 username: "{{ username }}"
120 password: "{{ password }}"
121 validate_certs: "{{ validate_certs }}"
122 port: "{{ port }}"
123 resource_group_name: "{{ resource_group_name_1 }}"
124 description: ans_rg
125 template_id: c65d0172-8666-48ab-935e-9a0bf69ed66d
126 firmware_repository_id: 8aaa80788b5755d1018b576126d51ba3
127
128 - name: Add a node to a resource group
129 dellemc.powerflex.resource_group:
130 hostname: "{{ hostname }}"
131 username: "{{ username }}"
132 password: "{{ password }}"
133 validate_certs: "{{ validate_certs }}"
134 resource_group_name: "{{ resource_group_name_1 }}"
135 scaleup: true
136 clone_node: "{{ node_1 }}"
137 node_count: "{{ node_count }}"
138
139 - name: Modify a resource group
140 dellemc.powerflex.resource_group:
141 hostname: "{{ hostname }}"
142 username: "{{ username }}"
143 password: "{{ password }}"
144 validate_certs: "{{ validate_certs }}"
145 resource_group_name: "{{ resource_group_name_1 }}"
146 new_resource_group_name: "{{ new_resource_group_name }}"
147 description: "description new"
148
149 - name: Delete a resource group
150 dellemc.powerflex.resource_group:
151 hostname: "{{ hostname }}"
152 username: "{{ username }}"
153 password: "{{ password }}"
154 validate_certs: "{{ validate_certs }}"
155 port: "{{ port }}"
156 resource_group_name: ans_rg
157 state: "absent"
158 '''
159
160 RETURN = r'''
161 changed:
162 description: Whether or not the resource has changed.
163 returned: always
164 type: bool
165 sample: 'false'
166 resource_group_details:
167 description: Details of the resource group deployment.
168 returned: When resource group exists.
169 type: dict
170 contains:
171 id:
172 description: The ID of the deployed resource group.
173 type: str
174 deploymentName:
175 description: The name of the resource group deployment.
176 type: str
177 deploymentDescription:
178 description: The description of the resource group deployment.
179 type: str
180 serviceTemplate:
181 description: The service template of the resource group.
182 type: dict
183 contains:
184 id:
185 description: The ID of the service template.
186 type: str
187 templateName:
188 description: The name of the service template.
189 type: str
190 status:
191 description: The status of the deployment of the resource group.
192 type: str
193 firmwareRepositoryId:
194 description: The ID of the firmware repository of the resource group.
195 type: str
196 sample: {
197 "id": "8aaa03a88de961fa018de96a88d80008",
198 "deploymentName": "dep-ans-test-rg1",
199 "deploymentDescription": "ans test rg",
200 "retry": true,
201 "teardown": false,
202 "serviceTemplate": {
203 "id": "8aaa03a88de961fa018de96a88d80008",
204 "templateName": "update-template (8aaa03a88de961fa018de96a88d80008)"
205 },
206 "scheduleDate": null,
207 "status": "error",
208 "compliant": true,
209 "deploymentDevice": [
210 {
211 "refId": "scaleio-block-legacy-gateway",
212 "refType": "SCALEIO",
213 "deviceHealth": "GREEN",
214 "compliantState": "COMPLIANT",
215 "deviceType": "scaleio",
216 "currentIpAddress": "1.3.9.2",
217 "componentId": "910bf934-d45a-4fe3-8ea2-dc481e063a81",
218 "statusMessage": "The processing of PowerFlex is unsuccessful.",
219 "model": "PowerFlex Gateway",
220 "brownfield": false
221 }
222 ],
223 "updateServerFirmware": true,
224 "useDefaultCatalog": true,
225 "firmwareRepository": {
226 "id": "8aaa80788b5755d1018b576126d51ba3",
227 "name": "PowerFlex 4.5.0.0",
228 "rcmapproved": false
229 },
230 "firmwareRepositoryId": "8aaa80788b5755d1018b576126d51ba3",
231 "deploymentHealthStatusType": "red",
232 "allUsersAllowed": false,
233 "owner": "admin",
234 "numberOfDeployments": 0,
235 "lifecycleMode": false,
236 "vds": false,
237 "scaleUp": false,
238 "brownfield": false,
239 "templateValid": true,
240 "configurationChange": false
241 }
242 '''
243
244
245 from ansible.module_utils.basic import AnsibleModule
246 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell \
247 import utils
248 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \
249 import powerflex_compatibility
250 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \
251 import PowerFlexBase
252 import json
253 import copy
254
255 LOG = utils.get_logger('resource_group')
256
257
258 @powerflex_compatibility(min_ver='3.6', max_ver='5.0')
259 class PowerFlexResourceGroup(PowerFlexBase):
260 def __init__(self):
261 """ Define all parameters required by this module"""
262 argument_spec = get_powerflex_resource_group_parameters()
263 mut_ex_args = [['resource_group_name', 'resource_group_id'],
264 ['template_name', 'template_id'],
265 ['firmware_repository_id', 'firmware_repository_name']]
266
267 required_one_of_args = [['resource_group_name', 'resource_group_id']]
268
269 ansible_module_params = {
270 'argument_spec': argument_spec,
271 'supports_check_mode': True,
272 'mutually_exclusive': mut_ex_args,
273 'required_one_of': required_one_of_args
274 }
275 super().__init__(AnsibleModule, ansible_module_params)
276 super().check_module_compatibility()
277
278 def get_service_template(self, template_id=None, template_name=None, for_deployment=True):
279 """
280 Retrieves a service template based on the provided parameters.
281
282 Args:
283 template_id (str, optional): The ID of the service template. Defaults to None.
284 template_name (str, optional): The name of the service template. Defaults to None.
285 for_deployment (bool, optional): Indicates whether the template is for deployment. Defaults to True.
286
287 Returns:
288 ServiceTemplate: The retrieved service template.
289
290 Raises:
291 AnsibleFailJson: If either `template_id` or `template_name` is not specified for resource group deployment.
292 AnsibleFailJson: If the service template with the specified `template_name` is not found.
293 AnsibleFailJson: If the service template with the specified `template_id` is not found.
294 """
295 if not (template_id or template_name):
296 self.module.fail_json(msg="Either template_id or template_name must be specified for resource group deployment")
297 if template_name:
298 filter_query = utils.get_filter(template_name)
299 template = self.powerflex_conn.service_template.get(filters=[filter_query])
300 if not template:
301 error_msg = f"Service template {template_name} is not found"
302 self.module.fail_json(msg=error_msg)
303
304 template_id = template_id or template[0]['id']
305 return self.powerflex_conn.service_template.get_by_id(template_id, for_deployment)
306
307 def get_firmware_repo(self, firmware_repo_id=None, firmware_repo_name=None):
308 """
309 Retrieves the firmware repository ID based on the provided firmware repository name or ID.
310
311 Args:
312 firmware_repo_id (str, optional): The ID of the firmware repository. Defaults to None.
313 firmware_repo_name (str, optional): The name of the firmware repository. Defaults to None.
314
315 Returns:
316 str: The ID of the firmware repository.
317
318 Raises:
319 ValueError: If the firmware repository is not found.
320 """
321 firmware_repos = self.powerflex_conn.firmware_repository.get()
322 if firmware_repo_id:
323 firmware_repo = next((repo for repo in firmware_repos if repo.get('id') == firmware_repo_id), None)
324 else:
325 firmware_repo = next((repo for repo in firmware_repos if repo.get('name') == firmware_repo_name), None)
326 if not firmware_repo:
327 self.module.fail_json(msg=f"Firmware repository {firmware_repo_id or firmware_repo_name} is not found")
328 return firmware_repo['id']
329
330 def get_resource_group_name(self):
331 """ Retrieves the name of the resource group. """
332 resource_group_name = self.module.params['resource_group_name']
333 if not resource_group_name:
334 self.module.fail_json(msg="Specify resource_group_name for resource group deployment.")
335 return resource_group_name
336
337 def is_modify_needed(self, deployment_data):
338
339 modify_dict = False
340 if self.module.params["new_resource_group_name"] is not None and \
341 deployment_data["deploymentName"] != self.module.params["new_resource_group_name"]:
342 modify_dict = True
343 if self.module.params["description"] is not None and \
344 deployment_data["deploymentDescription"] != self.module.params["description"]:
345 modify_dict = True
346 if self.module.params["scaleup"]:
347 modify_dict = True
348
349 return modify_dict
350
351 def clone_component(self, deploy_data):
352 new_component = None
353 count_server = 0
354 server_name = []
355 for component in range(len(deploy_data["serviceTemplate"]["components"])):
356 if deploy_data["serviceTemplate"]["components"][component]["type"] == "SERVER":
357 count_server = count_server + 1
358 server_name.append(deploy_data["serviceTemplate"]["components"][component]["name"])
359 for component in range(len(deploy_data["serviceTemplate"]["components"])):
360 if self.module.params["clone_node"] is None:
361 if count_server == 1 and deploy_data["serviceTemplate"]["components"][component]["name"] == server_name[0]:
362 new_component = deploy_data["serviceTemplate"]["components"][component]
363 elif count_server != 1:
364 self.module.fail_json(msg="More than 1 server components exist. Provide the clone_node.")
365 else:
366 if deploy_data["serviceTemplate"]["components"][component]["name"] == self.module.params["clone_node"]:
367 new_component = deploy_data["serviceTemplate"]["components"][component]
368
369 return new_component
370
371 def prepare_add_node_payload(self, deploy_data):
372
373 new_component = self.clone_component(deploy_data=deploy_data)
374 if new_component is not None:
375 uuid = utils.random_uuid_generation()
376 new_component.update({
377 "identifier": None,
378 "asmGUID": None,
379 "puppetCertName": None,
380 "osPuppetCertName": None,
381 "managementIpAddress": None,
382 "brownfield": False,
383 "id": uuid,
384 "name": uuid})
385 resource_params = ["razor_image", "scaleio_enabled", "scaleio_role",
386 "compression_enabled", "replication_enabled"]
387
388 for resource in range(len(new_component["resources"])):
389 if new_component["resources"][resource]["id"] == "asm::server":
390 for param in range(len(new_component["resources"][resource]["parameters"])):
391 if new_component["resources"][resource]["parameters"][param]["id"] \
392 not in resource_params:
393 new_component["resources"][resource]["parameters"][param]["guid"] = None
394 new_component["resources"][resource]["parameters"][param]["value"] = None
395 return new_component
396
397 def modify_resource_group_details(self, deployment_data):
398 new_deployment_data = copy.deepcopy(deployment_data)
399
400 # edit resource group
401
402 if self.module.params["new_resource_group_name"]:
403 new_deployment_data["deploymentName"] = self.module.params["new_resource_group_name"]
404 if self.module.params["description"]:
405 new_deployment_data["deploymentDescription"] = self.module.params["description"]
406
407 # Add nodes
408
409 if self.module.params["scaleup"]:
410 new_deployment_data["scaleup"] = True
411 new_deployment_data["retry"] = True
412 node = 0
413 while node < self.module.params["node_count"]:
414 new_deployment_data1 = copy.deepcopy(deployment_data)
415 new_component = self.prepare_add_node_payload(deploy_data=new_deployment_data1)
416 if new_component:
417 new_deployment_data["serviceTemplate"]["components"].append(new_component)
418 node = node + 1
419
420 try:
421 if not self.module.check_mode:
422 self.powerflex_conn.deployment.edit(deployment_id=deployment_data["id"],
423 rg_data=new_deployment_data)
424
425 except Exception as e:
426 errmsg = f'Modifying a resource group deployment failed with error {utils.get_display_message(str(e))}'
427 self.module.fail_json(msg=errmsg)
428
429 def get_deployment_data(self):
430 """
431 Retrieves deployment data based on the provided parameters.
432
433 :return: A JSON string representing the deployment data.
434 """
435 template_id = self.module.params['template_id']
436 template_name = self.module.params['template_name']
437 resource_group_name = self.get_resource_group_name()
438 description = self.module.params['description']
439 firmware_repo_id = self.module.params['firmware_repository_id']
440 firmware_repo_name = self.module.params['firmware_repository_name']
441 schedule_date = self.module.params['schedule_date']
442 service_template = self.get_service_template(template_id, template_name, for_deployment=True)
443 deployment_data = {
444 "deploymentName": resource_group_name,
445 "deploymentDescription": description,
446 "serviceTemplate": service_template,
447 "updateServerFirmware": True,
448 "useDefaultCatalog": True
449 }
450
451 if firmware_repo_id or firmware_repo_name:
452 firmware_repository_id = self.get_firmware_repo(firmware_repo_id, firmware_repo_name)
453 deployment_data["firmwareRepositoryId"] = firmware_repository_id
454 deployment_data["useDefaultCatalog"] = False
455 if schedule_date:
456 if not utils.validate_date(schedule_date):
457 self.module.fail_json(msg="Invalid schedule_date format. Specify the date in the format 'YYYY-MM-DDTHH:MM:SS.sss'")
458 deployment_data["scheduleDate"] = schedule_date
459
460 return json.dumps(deployment_data)
461
462 def get_deployment_details(self, deployment_name=None, deployment_id=None):
463 """
464 Retrieves deployment details based on the provided deployment name or deployment ID.
465
466 Args:
467 deployment_name (str, optional): The name of the deployment. Defaults to None.
468 deployment_id (str, optional): The ID of the deployment. Defaults to None.
469
470 Returns:
471 list: A list of deployment details if the deployment name is provided and a matching deployment is found.
472 None: if the deployment ID is provided and no deployment is found with that ID.
473 """
474 try:
475 if deployment_name:
476 filter_query = utils.get_filter(deployment_name)
477 resp = self.powerflex_conn.deployment.get(filters=[filter_query])
478 if len(resp) > 0:
479 deployment_id = resp[0]["id"]
480 else:
481 return None
482 return self.powerflex_conn.deployment.get_by_id(deployment_id)
483
484 except Exception as e:
485 if hasattr(e, 'status') and str(e.status) == '404':
486 return None
487 else:
488 self.module.fail_json(msg=utils.get_display_message(str(e)))
489
490 def get_operation_mapping(self):
491 """
492 Get the operation mapping based on the deployment details and module parameters.
493
494 :return: The operation mapping for the given state, validate, and check_mode.
495 """
496 if not self.deployment_details:
497 operation_mapping = {
498 ('present', True, True): ValidateDeploy,
499 ('present', True, False): ValidateDeploy,
500 ('present', False, True): ValidateDeploy,
501 ('present', False, False): Deploy
502 }
503 else:
504 operation_mapping = {
505 ('absent', True, True): DeleteDeploy,
506 ('absent', True, False): DeleteDeploy,
507 ('absent', False, True): DeleteDeploy,
508 ('absent', False, False): DeleteDeploy,
509 ('present', True, True): ModifyResourceGroup,
510 ('present', True, False): ModifyResourceGroup,
511 ('present', False, True): ModifyResourceGroup,
512 ('present', False, False): ModifyResourceGroup
513 }
514
515 state = self.module.params['state']
516 validate = self.module.params['validate']
517 check_mode = self.module.check_mode
518
519 return operation_mapping.get((state, validate, check_mode))
520
521 def perform_module_operation(self):
522 """
523 Perform the module operation.
524
525 :return: A dictionary containing the result of the module operation.
526 """
527 result = dict(
528 changed=False,
529 resource_group_details=[]
530 )
531
532 self.deployment_details = self.get_deployment_details(
533 deployment_name=self.module.params['resource_group_name'],
534 deployment_id=self.module.params['resource_group_id'])
535 resource_group_operation = self.get_operation_mapping()
536 if resource_group_operation:
537 changed, resource_group_details = resource_group_operation.execute(self)
538 result['resource_group_details'] = resource_group_details
539 result['changed'] = changed
540
541 self.module.exit_json(**result)
542
543
544 class Deploy:
545 def execute(self):
546 try:
547 rg_data = self.get_deployment_data()
548 response = self.powerflex_conn.deployment.create(rg_data)
549 return True, response
550 except Exception as e:
551 errmsg = f'Deploying a resource group failed with error {utils.get_display_message(str(e))}'
552 self.module.fail_json(msg=errmsg)
553
554
555 class ValidateDeploy:
556 def execute(self):
557 try:
558 rg_data = self.get_deployment_data()
559 response = self.powerflex_conn.deployment.validate(rg_data)
560 return False, response
561 except Exception as e:
562 errmsg = f'Validating a resource group deployment failed with error {utils.get_display_message(str(e))}'
563 self.module.fail_json(msg=errmsg)
564
565
566 class ModifyResourceGroup:
567 def execute(self):
568 try:
569 changed = False
570 rg_data = self.deployment_details
571 if self.is_modify_needed(deployment_data=rg_data):
572 self.modify_resource_group_details(deployment_data=rg_data)
573 changed = True
574
575 response = self.get_deployment_details(deployment_id=rg_data['id'])
576 return changed, response
577 except Exception as e:
578 errmsg = f'Editing a resource group failed with error {utils.get_display_message(str(e))}'
579 self.module.fail_json(msg=errmsg)
580
581
582 class DeleteDeploy:
583 def execute(self):
584 try:
585 changed = False
586 if self.deployment_details:
587 if not self.module.check_mode:
588 self.powerflex_conn.deployment.delete(self.deployment_details['id'])
589 self.deployment_details = \
590 self.get_deployment_details(deployment_name=self.deployment_details['deploymentName'])
591 changed = True
592 return changed, self.deployment_details
593 except Exception as e:
594 errmsg = f'Deleting a resource group deployment failed with error {utils.get_display_message(str(e))}'
595 self.module.fail_json(msg=errmsg)
596
597
598 def main():
599 """ Create PowerFlex resource group object and perform actions on it
600 based on user input from playbook"""
601 obj = PowerFlexResourceGroup()
602 obj.perform_module_operation()
603
604
605 def get_powerflex_resource_group_parameters():
606 """This method provides parameters required for the resource group
607 module on PowerFlex"""
608 return dict(
609 resource_group_name=dict(),
610 resource_group_id=dict(),
611 template_name=dict(),
612 template_id=dict(),
613 firmware_repository_id=dict(),
614 firmware_repository_name=dict(),
615 new_resource_group_name=dict(),
616 description=dict(),
617 scaleup=dict(type='bool', default=False),
618 clone_node=dict(),
619 node_count=dict(type='int', default=1),
620 validate=dict(type='bool', default=False),
621 schedule_date=dict(),
622 state=dict(choices=['present', 'absent'], default='present')
623 )
624
625
626 if __name__ == '__main__':
627 main()