Skip to content

Instantly share code, notes, and snippets.

@ashutoshkarna03
Created May 18, 2020 18:25
Show Gist options
  • Save ashutoshkarna03/5a0ca1dbdaad76423fbbf96ec0dcb494 to your computer and use it in GitHub Desktop.
Save ashutoshkarna03/5a0ca1dbdaad76423fbbf96ec0dcb494 to your computer and use it in GitHub Desktop.
def migrate(instances_list):
# create boto3 client for ec2 for both source and destination region
client_src = boto3.client('ec2', region_name=os.getenv('SOURCE_REGION'))
client_des = boto3.client('ec2', region_name=os.getenv('DESTINATION_REGION'))
# create ec2 resource
ec2 = boto3.resource('ec2', region_name=os.getenv('DESTINATION_REGION'))
total_instances = len(instances_list)
# iterate through list of intances in source region to be migrated
for n, instance in enumerate(instances_list):
try:
print(str(n+1) + '/' + str(total_instances) + ': ' + instance)
# stop the source instance first, not mandatory but recommended, inorder to keep instance's integrity
stop_instance(instance_id=instance, client=client_src)
# create image of the source instance
image_id_src = create_image_of_instance(instance_id=instance, client=client_src)
print('Source image_id: ' + image_id_src)
# copy the image from source region to destination region (destination client is needed for this function)
image_id_des = copy_image_to_destination_region(image_id=image_id_src, instance_id=instance, client=client_des)
print('Destination image_id: ' + image_id_des)
result = launch_instance(
image_id=image_id_des,
instance_id=instance,
client_src=client_src,
client_des=client_des,
ec2_resource_des=ec2
)
if result['success']:
print('Migration of instance: ' + instance + ' completed successfully')
else:
print('Migration of instance: ' + instance + ' failed due to error: ' + result['error_msg'])
except Exception as e:
print('Migration of instance: ' + instance + ' failed due to error: ' + str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment