EBS-Snapgots.py 2.5 KB

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