Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/backup.py

raw
1 # -*- coding: utf-8 -*-
2
3 # This file is part of Ansible
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6
7 try:
8 import botocore
9 except ImportError:
10 pass # Handled by HAS_BOTO3
11
12 from typing import Union
13
14 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
15
16
17 def get_backup_resource_tags(module, backup_client, resource):
18 try:
19 response = backup_client.list_tags(ResourceArn=resource)
20 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
21 module.fail_json_aws(e, msg=f"Failed to list tags on the resource {resource}")
22
23 return response["Tags"]
24
25
26 def _list_backup_plans(client, backup_plan_name):
27 first_iteration_completed = False
28 next_token = None
29
30 # We can not use the paginator at the moment because if was introduced after boto3 version 1.22
31 # paginator = client.get_paginator("list_backup_plans")
32 # result = paginator.paginate(**params).build_full_result()["BackupPlansList"]
33
34 response = client.list_backup_plans()
35 next_token = response.get("NextToken", None)
36
37 if next_token is None:
38 entries = response["BackupPlansList"]
39 for backup_plan in entries:
40 if backup_plan_name == backup_plan["BackupPlanName"]:
41 return backup_plan["BackupPlanId"]
42
43 while next_token is not None:
44 if first_iteration_completed:
45 response = client.list_backup_plans(NextToken=next_token)
46 first_iteration_completed = True
47 entries = response["BackupPlansList"]
48 for backup_plan in entries:
49 if backup_plan_name == backup_plan["BackupPlanName"]:
50 return backup_plan["BackupPlanId"]
51 next_token = response.get("NextToken")
52
53
54 def get_plan_details(module, client, backup_plan_name: str):
55 backup_plan_id = _list_backup_plans(client, backup_plan_name)
56
57 if not backup_plan_id:
58 return []
59
60 try:
61 result = client.get_backup_plan(BackupPlanId=backup_plan_id)
62 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
63 module.fail_json_aws(e, msg=f"Failed to describe plan {backup_plan_id}")
64
65 # Turn the boto3 result in to ansible_friendly_snaked_names
66 snaked_backup_plan = []
67
68 try:
69 resource = result.get("BackupPlanArn", None)
70 tag_dict = get_backup_resource_tags(module, client, resource)
71 result.update({"tags": tag_dict})
72 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
73 module.fail_json_aws(e, msg="Failed to get the backup plan tags")
74
75 snaked_backup_plan.append(camel_dict_to_snake_dict(result, ignore_list="tags"))
76
77 # Remove AWS API response and add top-level plan name
78 for v in snaked_backup_plan:
79 if "response_metadata" in v:
80 del v["response_metadata"]
81 v["backup_plan_name"] = v["backup_plan"]["backup_plan_name"]
82
83 return snaked_backup_plan
84
85
86 def _list_backup_selections(client, module, plan_id):
87 first_iteration_completed = False
88 next_token = None
89 selections = []
90
91 # We can not use the paginator at the moment because if was introduced after boto3 version 1.22
92 # paginator = client.get_paginator("list_backup_selections")
93 # result = paginator.paginate(**params).build_full_result()["BackupSelectionsList"]
94
95 try:
96 response = client.list_backup_selections(BackupPlanId=plan_id)
97 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
98 module.fail_json_aws(e, msg="Failed to list AWS backup selections")
99
100 next_token = response.get("NextToken", None)
101
102 if next_token is None:
103 return response["BackupSelectionsList"]
104
105 while next_token:
106 if first_iteration_completed:
107 try:
108 response = client.list_backup_selections(BackupPlanId=plan_id, NextToken=next_token)
109 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
110 module.fail_json_aws(e, msg="Failed to list AWS backup selections")
111 first_iteration_completed = True
112 selections.append(response["BackupSelectionsList"])
113 next_token = response.get("NextToken")
114
115
116 def _get_backup_selection(client, module, plan_id, selection_id):
117 try:
118 result = client.get_backup_selection(BackupPlanId=plan_id, SelectionId=selection_id)
119 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
120 module.fail_json_aws(e, msg=f"Failed to describe selection {selection_id}")
121 return result or []
122
123
124 def get_selection_details(module, client, plan_name: str, selection_name: Union[str, list]):
125 result = []
126
127 plan = get_plan_details(module, client, plan_name)
128
129 if not plan:
130 module.fail_json(msg=f"The backup plan {plan_name} does not exist. Please create one first.")
131
132 plan_id = plan[0]["backup_plan_id"]
133
134 selection_list = _list_backup_selections(client, module, plan_id)
135
136 if selection_name:
137 for selection in selection_list:
138 if isinstance(selection_name, list):
139 for name in selection_name:
140 if selection["SelectionName"] == name:
141 selection_id = selection["SelectionId"]
142 selection_info = _get_backup_selection(client, module, plan_id, selection_id)
143 result.append(selection_info)
144 if isinstance(selection_name, str):
145 if selection["SelectionName"] == selection_name:
146 selection_id = selection["SelectionId"]
147 result.append(_get_backup_selection(client, module, plan_id, selection_id))
148 break
149 else:
150 for selection in selection_list:
151 selection_id = selection["SelectionId"]
152 result.append(_get_backup_selection(client, module, plan_id, selection_id))
153
154 for v in result:
155 if "ResponseMetadata" in v:
156 del v["ResponseMetadata"]
157 if "BackupSelection" in v:
158 for backup_selection_key in v["BackupSelection"]:
159 v[backup_selection_key] = v["BackupSelection"][backup_selection_key]
160 del v["BackupSelection"]
161
162 return result