Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_snapshot.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
10 version_added: 1.0.0
11 short_description: Creates a snapshot from an existing volume
12 description:
13 - Creates an EC2 snapshot from an existing EBS volume.
14 options:
15 volume_id:
16 description:
17 - Volume from which to take the snapshot.
18 required: false
19 type: str
20 description:
21 description:
22 - Description to be applied to the snapshot.
23 required: false
24 type: str
25 instance_id:
26 description:
27 - Instance that has the required volume to snapshot mounted.
28 required: false
29 type: str
30 device_name:
31 description:
32 - Device name of a mounted volume to be snapshotted.
33 required: false
34 type: str
35 snapshot_tags:
36 description:
37 - A dictionary of tags to add to the snapshot.
38 - If the volume has a V(Name) tag this will be automatically added to the
39 snapshot.
40 type: dict
41 required: false
42 default: {}
43 wait:
44 description:
45 - Wait for the snapshot to be ready.
46 type: bool
47 required: false
48 default: true
49 wait_timeout:
50 description:
51 - How long before wait gives up, in seconds.
52 required: false
53 default: 600
54 type: int
55 state:
56 description:
57 - Whether to add or create a snapshot.
58 required: false
59 default: present
60 choices: ['absent', 'present']
61 type: str
62 snapshot_id:
63 description:
64 - Snapshot id to remove.
65 required: false
66 type: str
67 last_snapshot_min_age:
68 description:
69 - If the volume's most recent snapshot has started less than O(last_snapshot_min_age) minutes ago, a new snapshot will not be created.
70 required: false
71 default: 0
72 type: int
73 modify_create_vol_permission:
74 description:
75 - If set to V(true), ec2 snapshot's createVolumePermissions can be modified.
76 required: false
77 type: bool
78 version_added: 6.1.0
79 purge_create_vol_permission:
80 description:
81 - Whether unspecified group names or user IDs should be removed from the snapshot createVolumePermission.
82 - Must set O(modify_create_vol_permission) to V(True) for when O(purge_create_vol_permission) is set to V(True).
83 required: False
84 type: bool
85 default: False
86 version_added: 6.1.0
87 group_names:
88 description:
89 - The group to be added or removed. The possible value is V(all).
90 - Mutually exclusive with O(user_ids).
91 required: false
92 type: list
93 elements: str
94 choices: ["all"]
95 version_added: 6.1.0
96 user_ids:
97 description:
98 - The account user IDs to be added or removed.
99 - If createVolumePermission on snapshot is currently set to Public i.e. O(group_names=all),
100 providing O(user_ids) will not make createVolumePermission Private unless O(modify_create_vol_permission) is set to V(true).
101 - Mutually exclusive with O(group_names).
102 required: false
103 type: list
104 elements: str
105 version_added: 6.1.0
106 author: "Will Thames (@willthames)"
107 extends_documentation_fragment:
108 - amazon.aws.common.modules
109 - amazon.aws.region.modules
110 - amazon.aws.boto3
111 """
112
113 EXAMPLES = r"""
114 # Simple snapshot of volume using volume_id
115 - amazon.aws.ec2_snapshot:
116 volume_id: vol-abcdef12
117 description: snapshot of /data from DB123 taken 2013/11/28 12:18:32
118
119 # Snapshot of volume mounted on device_name attached to instance_id
120 - amazon.aws.ec2_snapshot:
121 instance_id: i-12345678
122 device_name: /dev/sdb1
123 description: snapshot of /data from DB123 taken 2013/11/28 12:18:32
124
125 # Snapshot of volume with tagging
126 - amazon.aws.ec2_snapshot:
127 instance_id: i-12345678
128 device_name: /dev/sdb1
129 snapshot_tags:
130 frequency: hourly
131 source: /data
132
133 # Remove a snapshot
134 - amazon.aws.ec2_snapshot:
135 snapshot_id: snap-abcd1234
136 state: absent
137
138 # Create a snapshot only if the most recent one is older than 1 hour
139 - amazon.aws.ec2_snapshot:
140 volume_id: vol-abcdef12
141 last_snapshot_min_age: 60
142
143 - name: Reset snapshot createVolumePermission (change permission to "Private")
144 amazon.aws.ec2_snapshot:
145 snapshot_id: snap-06a6f641234567890
146 modify_create_vol_permission: true
147 purge_create_vol_permission: true
148
149 - name: Modify snapshot createVolmePermission to add user IDs (specify purge_create_vol_permission=true to change permssion to "Private")
150 amazon.aws.ec2_snapshot:
151 snapshot_id: snap-06a6f641234567890
152 modify_create_vol_permission: true
153 user_ids:
154 - '123456789012'
155 - '098765432109'
156
157 - name: Modify snapshot createVolmePermission - remove all except specified user_ids
158 amazon.aws.ec2_snapshot:
159 snapshot_id: snap-06a6f641234567890
160 modify_create_vol_permission: true
161 purge_create_vol_permission: true
162 user_ids:
163 - '123456789012'
164
165 - name: Replace (purge existing) snapshot createVolmePermission annd add user IDs
166 amazon.aws.ec2_snapshot:
167 snapshot_id: snap-06a6f641234567890
168 modify_create_vol_permission: true
169 purge_create_vol_permission: true
170 user_ids:
171 - '111111111111'
172
173 - name: Modify snapshot createVolmePermission - make createVolumePermission "Public"
174 amazon.aws.ec2_snapshot:
175 snapshot_id: snap-06a6f641234567890
176 modify_create_vol_permission: true
177 purge_create_vol_permission: true
178 group_names:
179 - all
180 """
181
182 RETURN = r"""
183 snapshot_id:
184 description: The ID of the snapshot. Each snapshot receives a unique identifier when it is created.
185 type: str
186 returned: always
187 sample: snap-01234567
188 snapshots:
189 description: List of snapshots.
190 returned: always
191 type: list
192 elements: dict
193 contains:
194 description:
195 description: Description specified by the CreateSnapshotRequest that has been applied to all snapshots.
196 type: str
197 returned: always
198 sample: ""
199 encrypted:
200 description: Indicates whether the snapshot is encrypted.
201 type: bool
202 returned: always
203 sample: false
204 owner_id:
205 description: Account id used when creating this snapshot.
206 type: str
207 returned: always
208 sample: 123456
209 progress:
210 description: Progress this snapshot has made towards completing.
211 type: str
212 returned: always
213 sample: ""
214 snapshot_id:
215 description: Snapshot id that can be used to describe this snapshot.
216 type: str
217 returned: always
218 sample: snap-1234
219 start_time:
220 description: Time this snapshot was started. This is the same for all snapshots initiated by the same request.
221 type: str
222 returned: always
223 sample: "2024-05-07T14:29:24.523000+00:00"
224 state:
225 description: Current state of the snapshot.
226 type: str
227 returned: always
228 sample: pending
229 tags:
230 description: Tags associated with this snapshot.
231 type: dict
232 returned: always
233 sample: "{ 'Name': 'instance-name' }"
234 volume_id:
235 description: The ID of the volume that was used to create the snapshot.
236 type: str
237 returned: always
238 sample: vol-01234567
239 volume_size:
240 description: The size of the volume, in GiB.
241 type: int
242 returned: always
243 sample: 8
244 tags:
245 description: Any tags assigned to the snapshot.
246 type: dict
247 returned: always
248 sample: "{ 'Name': 'instance-name' }"
249 volume_id:
250 description: The ID of the volume that was used to create the snapshot.
251 type: str
252 returned: always
253 sample: vol-01234567
254 volume_size:
255 description: The size of the volume, in GiB.
256 type: int
257 returned: always
258 sample: 8
259 """
260
261 import datetime
262 from typing import Any
263 from typing import Dict
264 from typing import List
265 from typing import Optional
266
267 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
268
269 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
270 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_snapshot
271 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_snapshot
272 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_snapshot_attribute
273 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_snapshots
274 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_volumes
275 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_snapshot_attribute
276 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import reset_snapshot_attribute
277 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
278 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
279 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
280 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
281 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
282
283
284 def _get_most_recent_snapshot(snapshots, max_snapshot_age_secs=None, now=None):
285 """
286 Gets the most recently created snapshot and optionally filters the result
287 if the snapshot is too old
288 :param snapshots: list of snapshots to search
289 :param max_snapshot_age_secs: filter the result if its older than this
290 :param now: simulate time -- used for unit testing
291 :return:
292 """
293 if len(snapshots) == 0:
294 return None
295
296 if not now:
297 now = datetime.datetime.now(datetime.timezone.utc)
298
299 youngest_snapshot = max(snapshots, key=lambda s: s["StartTime"])
300 snapshot_start = youngest_snapshot["StartTime"]
301 snapshot_age = now - snapshot_start
302
303 if max_snapshot_age_secs is not None:
304 if snapshot_age.total_seconds() > max_snapshot_age_secs:
305 return None
306
307 return youngest_snapshot
308
309
310 def get_volume_by_instance(module: AnsibleAWSModule, ec2, device_name: str, instance_id: str) -> Dict[str, Any]:
311 try:
312 _filter = {"attachment.instance-id": instance_id, "attachment.device": device_name}
313 volumes = describe_volumes(ec2, Filters=ansible_dict_to_boto3_filter_list(_filter))
314 except AnsibleEC2Error as e:
315 module.fail_json_aws(e, msg="Failed to describe Volume")
316
317 if not volumes:
318 module.fail_json(msg=f"Could not find volume with name {device_name} attached to instance {instance_id}")
319
320 volume = volumes[0]
321 return volume
322
323
324 def get_volume_by_id(module: AnsibleAWSModule, ec2, volume: str) -> Dict[str, Any]:
325 try:
326 volumes = describe_volumes(ec2, VolumeIds=[volume])
327 except AnsibleEC2Error as e:
328 module.fail_json_aws(e, msg="Failed to describe Volume")
329
330 if not volumes:
331 module.fail_json(msg=f"Could not find volume with id {volume}")
332
333 return volumes[0]
334
335
336 def get_snapshots_by_volume(module: AnsibleAWSModule, ec2, volume_id: str) -> Optional[List[Dict[str, Any]]]:
337 _filter = {"volume-id": volume_id}
338 try:
339 results = describe_snapshots(ec2, Filters=ansible_dict_to_boto3_filter_list(_filter))
340 except AnsibleEC2Error as e:
341 module.fail_json_aws(e, msg="Failed to describe snapshots from volume")
342
343 return results.get("Snapshots", [])
344
345
346 def _create_snapshot(module, ec2):
347 snapshot = None
348 changed = False
349
350 volume_id = module.params.get("volume_id")
351 description = module.params.get("description")
352 instance_id = module.params.get("instance_id")
353 device_name = module.params.get("device_name")
354 wait = module.params.get("wait")
355 wait_timeout = module.params.get("wait_timeout")
356 last_snapshot_min_age = module.params.get("last_snapshot_min_age")
357 snapshot_tags = module.params.get("snapshot_tags")
358
359 if instance_id:
360 volume = get_volume_by_instance(module, ec2, device_name, instance_id)
361 volume_id = volume["VolumeId"]
362 else:
363 volume = get_volume_by_id(module, ec2, volume_id)
364 if "Tags" not in volume:
365 volume["Tags"] = {}
366 if last_snapshot_min_age > 0:
367 current_snapshots = get_snapshots_by_volume(module, ec2, volume_id)
368 last_snapshot_min_age = last_snapshot_min_age * 60 # Convert to seconds
369 snapshot = _get_most_recent_snapshot(current_snapshots, max_snapshot_age_secs=last_snapshot_min_age)
370 # Create a new snapshot if we didn't find an existing one to use
371 if snapshot is None:
372 volume_tags = boto3_tag_list_to_ansible_dict(volume["Tags"])
373 volume_name = volume_tags.get("Name")
374 _tags = dict()
375 if volume_name:
376 _tags["Name"] = volume_name
377 if snapshot_tags:
378 _tags.update(snapshot_tags)
379
380 params = {"VolumeId": volume_id}
381 if description:
382 params["Description"] = description
383 if _tags:
384 params["TagSpecifications"] = [
385 {
386 "ResourceType": "snapshot",
387 "Tags": ansible_dict_to_boto3_tag_list(_tags),
388 }
389 ]
390 try:
391 if module.check_mode:
392 module.exit_json(
393 changed=True,
394 msg="Would have created a snapshot if not in check mode",
395 volume_id=volume["VolumeId"],
396 volume_size=volume["Size"],
397 )
398 volume_id = params.pop("VolumeId")
399 snapshot = create_snapshot(ec2, volume_id=volume_id, **params)
400 except AnsibleEC2Error as e:
401 module.fail_json_aws(e, msg="Failed to create snapshot")
402 changed = True
403 if wait:
404 wait_for_resource_state(
405 ec2,
406 module,
407 "snapshot_completed",
408 delay=3,
409 max_attempts=wait_timeout // 3,
410 SnapshotIds=[snapshot["SnapshotId"]],
411 )
412
413 _tags = boto3_tag_list_to_ansible_dict(snapshot["Tags"])
414 _snapshot = camel_dict_to_snake_dict(snapshot)
415 _snapshot["tags"] = _tags
416 results = {
417 "snapshot_id": snapshot["SnapshotId"],
418 "volume_id": snapshot["VolumeId"],
419 "volume_size": snapshot["VolumeSize"],
420 "tags": _tags,
421 "snapshots": [_snapshot],
422 }
423
424 module.exit_json(changed=changed, **results)
425
426
427 def _delete_snapshot(module: AnsibleAWSModule, connection) -> None:
428 snapshot_id = module.params.get("snapshot_id")
429 if module.check_mode:
430 try:
431 snapshots = describe_snapshots(connection, SnapshotIds=[(snapshot_id)])
432 if not snapshots:
433 module.exit_json(changed=False, msg="snapshot not found")
434 module.exit_json(changed=True, msg="Would have deleted snapshot if not in check mode")
435 except AnsibleEC2Error as e:
436 module.fail_json_aws(e, msg="Failed to describe snapshots")
437 try:
438 changed = delete_snapshot(connection, snapshot_id)
439 except AnsibleEC2Error as e:
440 module.fail_json_aws(e, msg="Failed to delete snapshot")
441
442 # successful delete
443 module.exit_json(changed=changed)
444
445
446 def build_modify_createVolumePermission_params(module):
447 snapshot_id = module.params.get("snapshot_id")
448 user_ids = module.params.get("user_ids")
449 group_names = module.params.get("group_names")
450
451 if not user_ids and not group_names:
452 module.fail_json(msg="Please provide either Group IDs or User IDs to modify permissions")
453
454 params = {
455 "Attribute": "createVolumePermission",
456 "OperationType": "add",
457 "SnapshotId": snapshot_id,
458 "GroupNames": group_names,
459 "UserIds": user_ids,
460 }
461
462 # remove empty value params
463 params = {k: v for k, v in params.items() if v}
464
465 return params
466
467
468 def check_user_or_group_update_needed(module: AnsibleAWSModule, ec2) -> bool:
469 try:
470 existing_create_vol_permission = describe_snapshot_attribute(
471 ec2, snapshot_id=module.params.get("snapshot_id"), attribute="createVolumePermission"
472 )["CreateVolumePermissions"]
473 except AnsibleEC2Error as e:
474 module.fail_json_aws(e, failed="Failed to describe snapshot attribute")
475 purge_permission = module.params.get("purge_create_vol_permission")
476 supplied_group_names = module.params.get("group_names")
477 supplied_user_ids = module.params.get("user_ids")
478
479 # if createVolumePermission is already "Public", adding "user_ids" is not needed
480 if any(item.get("Group") == "all" for item in existing_create_vol_permission) and not purge_permission:
481 return False
482
483 if supplied_group_names:
484 existing_group_names = {item.get("Group") for item in existing_create_vol_permission or []}
485 if set(supplied_group_names) == set(existing_group_names):
486 return False
487 else:
488 return True
489
490 if supplied_user_ids:
491 existing_user_ids = {item.get("UserId") for item in existing_create_vol_permission or []}
492 if set(supplied_user_ids) == set(existing_user_ids):
493 return False
494 else:
495 return True
496
497 if purge_permission and existing_create_vol_permission == []:
498 return False
499
500 return True
501
502
503 def _modify_snapshot_createVolumePermission(module: AnsibleAWSModule, ec2) -> None:
504 snapshot_id = module.params.get("snapshot_id")
505 purge_create_vol_permission = module.params.get("purge_create_vol_permission")
506 update_needed = check_user_or_group_update_needed(module, ec2)
507
508 if not update_needed:
509 module.exit_json(changed=False, msg="Supplied CreateVolumePermission already applied, update not needed")
510
511 if purge_create_vol_permission:
512 if module.check_mode:
513 module.exit_json(changed=True, msg="Would have reset CreateVolumePermission")
514 try:
515 reset_snapshot_attribute(ec2, attribute="createVolumePermission", snapshot_id=snapshot_id)
516 except AnsibleEC2Error as e:
517 module.fail_json_aws(e, msg="Failed to reset createVolumePermission")
518 if not module.params.get("user_ids") and not module.params.get("group_names"):
519 module.exit_json(changed=True, msg="Reset createVolumePermission successfully")
520
521 params = build_modify_createVolumePermission_params(module)
522
523 if module.check_mode:
524 module.exit_json(changed=True, msg="Would have modified CreateVolumePermission")
525
526 try:
527 snapshot_id = params.pop("SnapshotId")
528 modify_snapshot_attribute(ec2, snapshot_id=snapshot_id, **params)
529 except AnsibleEC2Error as e:
530 module.fail_json_aws(e, msg="Failed to modify createVolumePermission")
531
532 module.exit_json(changed=True, msg="Successfully modified CreateVolumePermission")
533
534
535 def create_snapshot_ansible_module() -> AnsibleAWSModule:
536 argument_spec = dict(
537 volume_id=dict(),
538 description=dict(),
539 instance_id=dict(),
540 snapshot_id=dict(),
541 device_name=dict(),
542 wait=dict(type="bool", default=True),
543 wait_timeout=dict(type="int", default=600),
544 last_snapshot_min_age=dict(type="int", default=0),
545 snapshot_tags=dict(type="dict", default=dict()),
546 state=dict(choices=["absent", "present"], default="present"),
547 modify_create_vol_permission=dict(type="bool"),
548 purge_create_vol_permission=dict(type="bool", default=False),
549 user_ids=dict(type="list", elements="str"),
550 group_names=dict(type="list", elements="str", choices=["all"]),
551 )
552 mutually_exclusive = [
553 ("instance_id", "snapshot_id", "volume_id"),
554 ("group_names", "user_ids"),
555 ]
556 required_if = [
557 ("state", "absent", ("snapshot_id",)),
558 ("purge_create_vol_permission", True, ("modify_create_vol_permission",)),
559 ]
560 required_one_of = [
561 ("instance_id", "snapshot_id", "volume_id"),
562 ]
563 required_together = [
564 ("instance_id", "device_name"),
565 ]
566
567 module = AnsibleAWSModule(
568 argument_spec=argument_spec,
569 mutually_exclusive=mutually_exclusive,
570 required_if=required_if,
571 required_one_of=required_one_of,
572 required_together=required_together,
573 supports_check_mode=True,
574 )
575
576 return module
577
578
579 def main():
580 module = create_snapshot_ansible_module()
581
582 state = module.params.get("state")
583 modify_create_vol_permission = module.params.get("modify_create_vol_permission")
584
585 ec2 = module.client("ec2")
586
587 if state == "absent":
588 _delete_snapshot(module, ec2)
589 elif modify_create_vol_permission is True:
590 _modify_snapshot_createVolumePermission(module, ec2)
591 elif state == "present":
592 _create_snapshot(module, ec2)
593
594
595 if __name__ == "__main__":
596 main()