Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_snapshot_info.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: ec2_snapshot_info
10 version_added: 1.0.0
11 short_description: Gathers information about EC2 volume snapshots in AWS
12 description:
13 - Gathers information about EC2 volume snapshots in AWS.
14 author:
15 - Rob White (@wimnat)
16 - Aubin Bikouo (@abikouo)
17 options:
18 snapshot_ids:
19 description:
20 - If you specify one or more snapshot IDs, only snapshots that have the specified IDs are returned.
21 required: false
22 default: []
23 type: list
24 elements: str
25 owner_ids:
26 description:
27 - If you specify one or more snapshot owners, only snapshots from the specified owners and for which you have
28 access are returned.
29 required: false
30 default: []
31 type: list
32 elements: str
33 restorable_by_user_ids:
34 description:
35 - If you specify a list of restorable users, only snapshots with create snapshot permissions for those users are
36 returned.
37 required: false
38 default: []
39 type: list
40 elements: str
41 filters:
42 description:
43 - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See
44 U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSnapshots.html) for possible filters. Filter
45 names and values are case sensitive.
46 required: false
47 type: dict
48 default: {}
49 max_results:
50 description:
51 - The maximum number of snapshot results returned in paginated output.
52 - When used only a single page along with a O(next_token_id) response element will be returned.
53 - The remaining results of the initial request can be seen by sending another request with the returned O(next_token_id) value.
54 - This value can be between 5 and 1000; if O(next_token_id) is given a value larger than 1000, only 1000 results are returned.
55 - If this parameter is not used, then DescribeSnapshots returns all results.
56 - This parameter is mutually exclusive with O(snapshot_ids).
57 required: False
58 type: int
59 next_token_id:
60 description:
61 - Contains the value returned from a previous paginated request where O(max_results) was used and the results exceeded the value of that parameter.
62 - Pagination continues from the end of the previous results that returned the O(next_token_id) value.
63 - This parameter is mutually exclusive with O(snapshot_ids)
64 required: false
65 type: str
66 notes:
67 - By default, the module will return all snapshots, including public ones. To limit results to snapshots owned by
68 the account use the filter V(owner-id).
69
70 extends_documentation_fragment:
71 - amazon.aws.region.modules
72 - amazon.aws.common.modules
73 - amazon.aws.boto3
74 """
75
76 EXAMPLES = r"""
77 # Note: These examples do not set authentication details, see the AWS Guide for details.
78
79 # Gather information about all snapshots, including public ones
80 - amazon.aws.ec2_snapshot_info:
81
82 # Gather information about all snapshots owned by the account 123456789012
83 - amazon.aws.ec2_snapshot_info:
84 filters:
85 owner-id: 123456789012
86
87 # Or alternatively...
88 - amazon.aws.ec2_snapshot_info:
89 owner_ids:
90 - 123456789012
91
92 # Gather information about a particular snapshot using ID
93 - amazon.aws.ec2_snapshot_info:
94 filters:
95 snapshot-id: snap-00112233
96
97 # Or alternatively...
98 - amazon.aws.ec2_snapshot_info:
99 snapshot_ids:
100 - snap-00112233
101
102 # Gather information about any snapshot with a tag key Name and value Example
103 - amazon.aws.ec2_snapshot_info:
104 filters:
105 "tag:Name": Example
106
107 # Gather information about any snapshot with an error status
108 - amazon.aws.ec2_snapshot_info:
109 filters:
110 status: error
111 """
112
113 RETURN = r"""
114 snapshots:
115 description: List of snapshots retrieved with their respective info.
116 type: list
117 returned: success
118 elements: dict
119 contains:
120 create_volume_permissions:
121 description:
122 - The users and groups that have the permissions for creating volumes from the snapshot.
123 - The module will return empty list if the create volume permissions on snapshot are 'private'.
124 type: list
125 elements: dict
126 sample: [{"group": "all"}]
127 data_encryption_key_id:
128 description:
129 - The data encryption key identifier for the snapshot. This value is a unique identifier that
130 corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy.
131 type: str
132 returned: always
133 sample: "arn:aws:kms:ap-southeast-2:123456789012:key/74c9742a-a1b2-45cb-b3fe-abcdef123456"
134 description:
135 description: The description for the snapshot.
136 type: str
137 returned: always
138 sample: "My important backup"
139 encrypted:
140 description: Indicates whether the snapshot is encrypted.
141 type: bool
142 returned: always
143 sample: "True"
144 kms_key_id:
145 description:
146 - The full ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to
147 protect the volume encryption key for the parent volume.
148 type: str
149 sample: "74c9742a-a1b2-45cb-b3fe-abcdef123456"
150 owner_id:
151 description: The AWS account ID of the EBS snapshot owner.
152 type: str
153 returned: always
154 sample: "123456789012"
155 progress:
156 description: The progress of the snapshot, as a percentage.
157 type: str
158 returned: always
159 sample: "100%"
160 snapshot_id:
161 description: The ID of the snapshot. Each snapshot receives a unique identifier when it is created.
162 type: str
163 returned: always
164 sample: snap-01234567
165 start_time:
166 description: The time stamp when the snapshot was initiated.
167 type: str
168 returned: always
169 sample: "2015-02-12T02:14:02+00:00"
170 state:
171 description: The snapshot state (completed, pending or error).
172 type: str
173 returned: always
174 sample: completed
175 state_message:
176 description:
177 - Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper
178 AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the
179 error occurred.
180 type: str
181 sample:
182 storage_tier:
183 description: The storage tier in which the snapshot is stored.
184 type: str
185 returned: always
186 sample: standard
187 tags:
188 description: Any tags assigned to the snapshot.
189 type: dict
190 returned: always
191 sample: "{ 'my_tag_key': 'my_tag_value' }"
192 volume_id:
193 description: The ID of the volume that was used to create the snapshot.
194 type: str
195 returned: always
196 sample: vol-01234567
197 volume_size:
198 description: The size of the volume, in GiB.
199 type: int
200 returned: always
201 sample: 8
202 next_token_id:
203 description:
204 - Contains the value returned from a previous paginated request where C(max_results) was used and the results exceeded the value of that parameter.
205 - This value is null when there are no more results to return.
206 type: str
207 returned: when option O(max_results) is set in input
208 """
209
210 from typing import Any
211 from typing import Dict
212
213 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
214
215 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
216 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_snapshot_attribute
217 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_snapshots
218 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
219 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
220 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
221
222
223 def build_request_args(snapshot_ids, owner_ids, restorable_by_user_ids, filters, max_results, next_token_id):
224 request_args = {
225 "Filters": ansible_dict_to_boto3_filter_list(filters),
226 "MaxResults": max_results,
227 "NextToken": next_token_id,
228 "OwnerIds": owner_ids,
229 "RestorableByUserIds": [str(user_id) for user_id in restorable_by_user_ids],
230 "SnapshotIds": snapshot_ids,
231 }
232
233 request_args = {k: v for k, v in request_args.items() if v}
234
235 return request_args
236
237
238 def list_ec2_snapshots(connection, module: AnsibleAWSModule, request_args: Dict[str, Any]) -> Dict[str, Any]:
239 try:
240 snapshots = describe_snapshots(connection, **request_args)
241 except AnsibleEC2Error as e:
242 module.fail_json_aws(e, msg="Failed to describe snapshots")
243
244 result = {}
245
246 # Add createVolumePermission info to snapshots result
247 for snapshot in snapshots.get("Snapshots", []):
248 snapshot_id = snapshot.get("SnapshotId")
249 try:
250 snapshot["CreateVolumePermissions"] = describe_snapshot_attribute(
251 connection, attribute="createVolumePermission", snapshot_id=snapshot_id
252 )["CreateVolumePermissions"]
253 except AnsibleEC2Error as e:
254 module.fail_json_aws(e, msg="Failed to describe snapshot attribute")
255
256 # Turn the boto3 result in to ansible_friendly_snaked_names
257 snaked_snapshots = []
258 for snapshot in snapshots.get("Snapshots", []):
259 snaked_snapshots.append(camel_dict_to_snake_dict(snapshot))
260
261 # Turn the boto3 result in to ansible friendly tag dictionary
262 for snapshot in snaked_snapshots:
263 if "tags" in snapshot:
264 snapshot["tags"] = boto3_tag_list_to_ansible_dict(snapshot["tags"], "key", "value")
265
266 result["snapshots"] = snaked_snapshots
267
268 if snapshots.get("NextToken"):
269 result.update(camel_dict_to_snake_dict({"NextTokenId": snapshots.get("NextToken")}))
270
271 return result
272
273
274 def main():
275 argument_spec = dict(
276 filters=dict(default={}, type="dict"),
277 max_results=dict(type="int"),
278 next_token_id=dict(type="str"),
279 owner_ids=dict(default=[], type="list", elements="str"),
280 restorable_by_user_ids=dict(default=[], type="list", elements="str"),
281 snapshot_ids=dict(default=[], type="list", elements="str"),
282 )
283
284 module = AnsibleAWSModule(
285 argument_spec=argument_spec,
286 mutually_exclusive=[
287 ["snapshot_ids", "owner_ids", "restorable_by_user_ids", "filters"],
288 ["snapshot_ids", "max_results"],
289 ["snapshot_ids", "next_token_id"],
290 ],
291 supports_check_mode=True,
292 )
293
294 connection = module.client("ec2")
295
296 request_args = build_request_args(
297 filters=module.params["filters"],
298 max_results=module.params["max_results"],
299 next_token_id=module.params["next_token_id"],
300 owner_ids=module.params["owner_ids"],
301 restorable_by_user_ids=module.params["restorable_by_user_ids"],
302 snapshot_ids=module.params["snapshot_ids"],
303 )
304
305 result = list_ec2_snapshots(connection, module, request_args)
306
307 module.exit_json(**result)
308
309
310 if __name__ == "__main__":
311 main()