pro-aws-ebs-snapshot.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import boto3
  2. import os,time
  3. from botocore.exceptions import ClientError
  4. from datetime import datetime, timedelta, timezone
  5. client = boto3.client('ec2')
  6. ec2 = boto3.resource('ec2')
  7. ddb = boto3.resource('dynamodb')
  8. # 'EBS-Snapshot-Lifecycle' is the table you store snapshot metadata, modify it to your own table name
  9. table = ddb.Table('EBS-Snapshot-Lifecycle')
  10. # set days to keep 快照保留周期
  11. DAYS_TO_RETAIN = 7
  12. def lambda_handler(event, context):
  13. os.environ['TZ'] = 'Asia/Shanghai'
  14. time.tzset()
  15. i=time.strftime('%X %x %Z')
  16. # set volume id, get volume who has a tag-key is 'Snapshot'
  17. describe_volumes=client.describe_volumes(
  18. Filters=[
  19. {
  20. 'Name': 'tag-key',
  21. 'Values': ['Snapshot',
  22. ]
  23. }
  24. ]
  25. )
  26. volume_id_list = []
  27. for vol in describe_volumes['Volumes']:
  28. volume_id_list.append(vol.get('VolumeId'))
  29. # set snapshot
  30. for volume_id in volume_id_list:
  31. volume = ec2.Volume(volume_id)
  32. for tags in volume.tags:
  33. if(tags.get('Key') == 'Name'):
  34. volume_name = tags.get('Value')
  35. description = volume_name + ' volume snapshot is created at ' + i
  36. try:
  37. response = client.create_snapshot(
  38. Description=description,
  39. VolumeId=volume_id)
  40. except:
  41. print('Create Snapshot occured error, Volume id is ' + volume_id)
  42. else:
  43. print('Snapshot is created succeed, Snapshot id is ' + response.get('SnapshotId'))
  44. # write into DynanoDB table
  45. snapshot_id = response.get('SnapshotId')
  46. start_time = response.get('StartTime')
  47. ttl_time = int(start_time.timestamp()) + 86400 * DAYS_TO_RETAIN
  48. try:
  49. table.put_item(
  50. Item={
  51. 'snapshot_id': snapshot_id,
  52. 'create_time': start_time.astimezone(timezone(timedelta(hours=8))).strftime('%X %x %Z'),
  53. 'description': description,
  54. 'timestamp': int(start_time.timestamp()),
  55. 'ttl': ttl_time,
  56. }
  57. )
  58. except:
  59. print('Write to DynanoDB Table occured error, snapshot id is ' + snapshot_id)
  60. else:
  61. print('Write to DynanoDB Table succeed, snapshot id is ' + snapshot_id)