Guest User

Untitled

a guest
Aug 21st, 2019
88
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from __future__ import print_function
  2. import boto3
  3. import os
  4. import json
  5.  
  6. def lambda_handler(event, context):
  7. print("Received event: " + json.dumps(event, indent=2))
  8. if event["detail"]["event"] == "createSnapshot":
  9. handle_create_snapshot(event, context)
  10. elif event["detail"]["event"] == "shareSnapshot":
  11. handle_shared_snapshot(event, context)
  12. else:
  13. print("Unknown event")
  14.  
  15. def handle_create_snapshot(event, context):
  16. target = os.environ["TARGET_ACCOUNT_ID"]
  17. print("Share target is: '{0}'".format(target))
  18. if target == "DISABLED":
  19. return
  20.  
  21. if event["detail"]["result"] == "succeeded":
  22. print("Sharing snapshot with destination {0}".format(target))
  23. ec2 = boto3.resource('ec2')
  24. # "snapshot_id": "arn:aws:ec2::us-west-2:snapshot/snap-01234567",
  25. snap_id = event["detail"]["snapshot_id"].split("/")[1]
  26. snap = ec2.Snapshot(snap_id)
  27. snap.modify_attribute(
  28. Attribute='createVolumePermission',
  29. CreateVolumePermission={
  30. 'Add': [{'UserId': str(target)}]
  31. })
  32.  
  33.  
  34. def handle_shared_snapshot(event, context):
  35. target_region = os.environ.get("TARGET_REGION")
  36. print("Copy target is: '{0}'".format(target_region))
  37. if target_region == "DISABLED":
  38. return
  39.  
  40. if event["detail"]["result"] == "succeeded":
  41. ec2_source = boto3.resource('ec2')
  42. ec2_target = boto3.session.Session().client('ec2', region_name=target_region)
  43. # "snapshot_id": "arn:aws:ec2::us-west-2:snapshot/snap-01234567",
  44. snap_id = event["detail"]["snapshot_id"].split("/")[1]
  45. snap = ec2_source.Snapshot(snap_id)
  46. print("Copying snapshot {0} from {1} to region {2}".format(snap_id, event["account"], target_region))
  47. source_region = event["region"]
  48. # need to copy from the *target* region because snap.copy ignores destinationregion...
  49. ec2_target.copy_snapshot(
  50. SourceSnapshotId=snap_id,
  51. Description="Copy of {} from {} ({})".format(snap_id, snap.owner_id, snap.description),
  52. SourceRegion=source_region,
  53. )
RAW Paste Data