Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import boto3
- import datetime
- import time
- import collections
- client = boto3.client('ec2')
- resource = boto3.resource('ec2')
- TARGET_ACCOUNT_ID = '<redacted>'
- ROLE_ON_TARGET_ACCOUNT = 'arn:aws:iam::<redacted>:role/copy_snapshots'
- SOURCE_REGION = 'eu-west-1'
- TARGET_REGION = 'eu-west-1'
- def role_arn_to_session(**args):
- client = boto3.client('sts')
- response = client.assume_role(**args)
- return boto3.Session(aws_access_key_id=response['Credentials'
- ]['AccessKeyId'],
- aws_secret_access_key=response['Credentials'
- ]['SecretAccessKey'],
- aws_session_token=response['Credentials'
- ]['SessionToken'])
- to_tag = collections.defaultdict(list)
- reservations = client.describe_instances(Filters=[{'Name': 'tag-key',
- 'Values': ['backup', 'Backup']}]).get('Reservations', [])
- instances = sum([[i for i in r['Instances']] for r in reservations], [])
- print 'Found %d instances that need backing up' % len(instances)
- for reservation in reservations:
- # for instance in reservation.instances:
- for instance in reservation['Instances']:
- retention_days = [int(t.get('Value')) for t in
- instance['Tags'] if t['Key']
- == 'Retention'][0]
- retention_days = 4
- created_on = datetime.datetime.now().strftime('%Y%m%d-%H%M')
- delete_date = datetime.date.today() \
- + datetime.timedelta(days=retention_days)
- delete_fmt = delete_date.strftime('%Y-%m-%d')
- ec2instance = resource.Instance(instance['InstanceId'])
- instance_id = instance['InstanceId']
- instancename = ''
- print("here")
- for tags in ec2instance.tags:
- if tags['Key'] == 'Name':
- instancename = tags['Value']
- ami_name = 'InstanceId(' + instancename + ')_CreatedOn(' \
- + created_on + ')_DeleteOn(' + delete_fmt + '))'
- print ami_name
- print 'Creating Backup: ' + instancename
- try:
- image_description = \
- client.create_image(InstanceId=instance_id,
- Name=ami_name, NoReboot=True)
- except Exception, e:
- print 'Backup ' + instancename + ': ' + e.message
- continue
- print 'Backup ' + instancename + ': ' + ami_name
- image = resource.Image(image_description['ImageId'])
- ami_name = image_description['ImageId']
- image.create_tags(Tags=[{'Key': 'DeleteOn',
- 'Value': delete_fmt}, {'Key': 'Name',
- 'Value': instancename}])
- while image.state == 'pending':
- print 'still not ready'
- time.sleep(5)
- image.reload()
- if image.state == 'available':
- print 'New AMI ' + ami_name
- # Now share newly created AMI with Target Account
- source_ec2 = boto3.resource('ec2')
- source_ami = source_ec2.Image(ami_name)
- devices = image.block_device_mappings
- for device in devices:
- if 'Ebs' in device:
- snapshot_id = device['Ebs']['SnapshotId']
- source_snapshot = source_ec2.Snapshot(snapshot_id)
- source_snapshot.create_tags(Tags=[{'Key': 'DeleteOn'
- , 'Value': delete_fmt}, {'Key': 'Name',
- 'Value': instancename}])
- source_sharing = \
- source_snapshot.describe_attribute(Attribute='createVolumePermission'
- )
- if source_sharing['CreateVolumePermissions'] \
- and source_sharing['CreateVolumePermissions'
- ][0]['UserId'] != TARGET_ACCOUNT_ID:
- print 'Snapshot already shared with account, creating a copy'
- else:
- print 'Sharing with target account'
- source_snapshot.modify_attribute(Attribute='createVolumePermission'
- , OperationType='add',
- UserIds=[TARGET_ACCOUNT_ID])
- # Get session with target account
- target_session = \
- role_arn_to_session(RoleArn=ROLE_ON_TARGET_ACCOUNT,
- RoleSessionName='share-admin-temp-session'
- )
- target_ec2 = target_session.resource('ec2',
- region_name=TARGET_REGION)
- # A shared snapshot, owned by source account
- shared_snapshot = target_ec2.Snapshot(snapshot_id)
- # Ensure source snapshot is completed, cannot be copied otherwise
- if shared_snapshot.state != 'completed':
- print 'Shared snapshot not in completed state, got: ' \
- + shared_snapshot.state
- exit(1)
- # Create a copy of the shared snapshot on the target account
- copy = shared_snapshot.copy(SourceRegion=SOURCE_REGION,
- KmsKeyId='arn:aws:kms:eu-west-1:<redacted>:key/3280caa5-512f-4844-8e79-26ea70199061'
- , Encrypted=True)
- # Wait for the copy to complete
- copied_snapshot = target_ec2.Snapshot(copy['SnapshotId'])
- copied_snapshot.wait_until_completed()
- delete_target_date = datetime.datetime.now() \
- + datetime.timedelta(hours=1)
- delete_target_fmt = delete_target_date.strftime('%Y-%m-%d')
- copied_snapshot.create_tags(Tags=[{'Key': 'DeleteOn',
- 'Value': delete_target_fmt}, {'Key': 'Name',
- 'Value': instancename}])
- print 'Created target-owned copy of shared snapshot with id: ' \
- + copy['SnapshotId']
- # Remove AMI from source account
- source_ami.deregister()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement