Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.21 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import boto3
  4. import datetime
  5. import time
  6. import collections
  7.  
  8. client = boto3.client('ec2')
  9. resource = boto3.resource('ec2')
  10.  
  11. TARGET_ACCOUNT_ID = '<redacted>'
  12. ROLE_ON_TARGET_ACCOUNT = 'arn:aws:iam::<redacted>:role/copy_snapshots'
  13. SOURCE_REGION = 'eu-west-1'
  14. TARGET_REGION = 'eu-west-1'
  15.  
  16.  
  17. def role_arn_to_session(**args):
  18.  
  19.     client = boto3.client('sts')
  20.     response = client.assume_role(**args)
  21.     return boto3.Session(aws_access_key_id=response['Credentials'
  22.                          ]['AccessKeyId'],
  23.                          aws_secret_access_key=response['Credentials'
  24.                          ]['SecretAccessKey'],
  25.                          aws_session_token=response['Credentials'
  26.                          ]['SessionToken'])
  27.  
  28.  
  29. to_tag = collections.defaultdict(list)
  30.  
  31. reservations = client.describe_instances(Filters=[{'Name': 'tag-key',
  32.         'Values': ['backup', 'Backup']}]).get('Reservations', [])
  33.  
  34. instances = sum([[i for i in r['Instances']] for r in reservations], [])
  35.  
  36. print 'Found %d instances that need backing up' % len(instances)
  37.  
  38. for reservation in reservations:
  39.  
  40.     # for instance in reservation.instances:
  41.  
  42.     for instance in reservation['Instances']:
  43.        
  44.             retention_days = [int(t.get('Value')) for t in
  45.                               instance['Tags'] if t['Key']
  46.                               == 'Retention'][0]
  47.             retention_days = 4
  48.  
  49.             created_on = datetime.datetime.now().strftime('%Y%m%d-%H%M')
  50.             delete_date = datetime.date.today() \
  51.                 + datetime.timedelta(days=retention_days)
  52.             delete_fmt = delete_date.strftime('%Y-%m-%d')
  53.  
  54.             ec2instance = resource.Instance(instance['InstanceId'])
  55.             instance_id = instance['InstanceId']
  56.             instancename = ''
  57.             print("here")
  58.             for tags in ec2instance.tags:
  59.                 if tags['Key'] == 'Name':
  60.                     instancename = tags['Value']
  61.             ami_name = 'InstanceId(' + instancename + ')_CreatedOn(' \
  62.                 + created_on + ')_DeleteOn(' + delete_fmt + '))'
  63.             print ami_name
  64.             print 'Creating Backup: ' + instancename
  65.             try:
  66.                 image_description = \
  67.                     client.create_image(InstanceId=instance_id,
  68.                         Name=ami_name, NoReboot=True)
  69.             except Exception, e:
  70.                 print 'Backup ' + instancename + ': ' + e.message
  71.                 continue
  72.             print 'Backup ' + instancename + ': ' + ami_name
  73.             image = resource.Image(image_description['ImageId'])
  74.             ami_name = image_description['ImageId']
  75.             image.create_tags(Tags=[{'Key': 'DeleteOn',
  76.                               'Value': delete_fmt}, {'Key': 'Name',
  77.                               'Value': instancename}])
  78.             while image.state == 'pending':
  79.                 print 'still not ready'
  80.                 time.sleep(5)
  81.                 image.reload()
  82.             if image.state == 'available':
  83.                 print 'New AMI ' + ami_name
  84.  
  85.             # Now share newly created AMI with Target Account
  86.  
  87.             source_ec2 = boto3.resource('ec2')
  88.             source_ami = source_ec2.Image(ami_name)
  89.  
  90.             devices = image.block_device_mappings
  91.             for device in devices:
  92.                 if 'Ebs' in device:
  93.                     snapshot_id = device['Ebs']['SnapshotId']
  94.                     source_snapshot = source_ec2.Snapshot(snapshot_id)
  95.                     source_snapshot.create_tags(Tags=[{'Key': 'DeleteOn'
  96.                             , 'Value': delete_fmt}, {'Key': 'Name',
  97.                             'Value': instancename}])
  98.  
  99.                     source_sharing = \
  100.                         source_snapshot.describe_attribute(Attribute='createVolumePermission'
  101.                             )
  102.                     if source_sharing['CreateVolumePermissions'] \
  103.                         and source_sharing['CreateVolumePermissions'
  104.                             ][0]['UserId'] != TARGET_ACCOUNT_ID:
  105.                         print 'Snapshot already shared with account, creating a copy'
  106.                     else:
  107.                         print 'Sharing with target account'
  108.                         source_snapshot.modify_attribute(Attribute='createVolumePermission'
  109.                                 , OperationType='add',
  110.                                 UserIds=[TARGET_ACCOUNT_ID])
  111.  
  112.             # Get session with target account
  113.  
  114.             target_session = \
  115.                 role_arn_to_session(RoleArn=ROLE_ON_TARGET_ACCOUNT,
  116.                                     RoleSessionName='share-admin-temp-session'
  117.                                     )
  118.             target_ec2 = target_session.resource('ec2',
  119.                     region_name=TARGET_REGION)
  120.  
  121.             # A shared snapshot, owned by source account
  122.  
  123.             shared_snapshot = target_ec2.Snapshot(snapshot_id)
  124.  
  125.             # Ensure source snapshot is completed, cannot be copied otherwise
  126.  
  127.             if shared_snapshot.state != 'completed':
  128.                 print 'Shared snapshot not in completed state, got: ' \
  129.                     + shared_snapshot.state
  130.                 exit(1)
  131.  
  132.             # Create a copy of the shared snapshot on the target account
  133.  
  134.             copy = shared_snapshot.copy(SourceRegion=SOURCE_REGION,
  135.                     KmsKeyId='arn:aws:kms:eu-west-1:<redacted>:key/3280caa5-512f-4844-8e79-26ea70199061'
  136.                     , Encrypted=True)
  137.  
  138.             # Wait for the copy to complete
  139.  
  140.             copied_snapshot = target_ec2.Snapshot(copy['SnapshotId'])
  141.  
  142.             copied_snapshot.wait_until_completed()
  143.  
  144.             delete_target_date = datetime.datetime.now() \
  145.                 + datetime.timedelta(hours=1)
  146.             delete_target_fmt = delete_target_date.strftime('%Y-%m-%d')
  147.  
  148.             copied_snapshot.create_tags(Tags=[{'Key': 'DeleteOn',
  149.                     'Value': delete_target_fmt}, {'Key': 'Name',
  150.                     'Value': instancename}])
  151.  
  152.             print 'Created target-owned copy of shared snapshot with id: ' \
  153.                 + copy['SnapshotId']
  154.  
  155.             # Remove AMI from source account
  156.  
  157.             source_ami.deregister()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement