python : amiCreateCopyRotate.py
This script creates an AMI of each running instance, tags them with a datestamp, copies them to a disaster recovery region, and trims images that are 7 days old. This script needs some refactoring, but works at the moment. I think I would like to decouple it a bit so that the sleep timers can be removed.
#!/usr/bin/python
import boto3
import botocore
from datetime import datetime, timedelta
from time import sleep
import re
# variables
local_region = 'us-west-2'
dr_region = 'us-east-1'
current_date = datetime.now().today()
last_week = current_date - timedelta(days=7)
current_date_tag = str(current_date.strftime("%Y-%m-%d"))
last_week_date_tag = str(last_week.strftime("%Y-%m-%d"))
local_ami_list = []
dr_ami_list = []
ami_list_to_copy = []
ec2_local = boto3.client('ec2', region_name=local_region)
ec2_dr = boto3.client('ec2', region_name=dr_region)
# 1. pull list of running instances in us-west-2
try:
local_instances = ec2_local.describe_instances()
for key in local_instances['Reservations']:
for instance in key['Instances']:
if instance['State']['Name'] == 'running':
local_instance_id = instance['InstanceId']
local_instance_tags= instance['Tags'][0]
local_instance_name = str(local_instance_tags.get('Value'))
entry = local_instance_id + ',' + local_instance_name
local_ami_list.append(entry)
else:
pass
except botocore.exceptions.ClientError as error:
print('error: {0}'.format(error))
# 2. Creates an AMI of each instance and tags it with the current date and name
for line in local_ami_list:
image_data_combined_list = line.split(',')
#pprint(image_data_combined_list)
local_instance_id = image_data_combined_list[0]
local_instance_name = current_date_tag + '-' + image_data_combined_list[1]
image = ec2_local.create_image(InstanceId=local_instance_id, Description=local_instance_name, DryRun=False,
Name = local_instance_name, NoReboot=True)
entry = local_instance_name + ',' + image['ImageId']
ami_list_to_copy.append(entry)
sleep(90)
# 3. Copies the AMIs to the DR region us-east-1
for line in ami_list_to_copy:
ami_list_combined_data = line.split(',')
local_ami_name = ami_list_combined_data[0]
local_ami_id = ami_list_combined_data[1]
try:
image_copy = ec2_dr.copy_image(Description=local_ami_name, Name=local_ami_name, SourceImageId=local_ami_id,
SourceRegion=local_region, DryRun=False)
entry = local_ami_name + ',' + image_copy['ImageId']
dr_ami_list.append(entry)
except botocore.exceptions.ClientError as error:
print('error: {0}'.format(error))
sleep(90)
# 4. Pulls a list of current private AMIs in us-west-2 and drops AMIs that are tagged 7 days older
local_amis_to_prune = ec2_local.describe_images(Owners=['self'])
local_amis = local_amis_to_prune['Images']
for ami in local_amis:
entry = str(ami['Name']) + ',' + str(ami['ImageId'])
match = re.search(last_week_date_tag,entry)
if match:
ec2_local.deregister_image(ImageId=ami['ImageId'])
#print('deleting: ', ami['Name'])
else:
pass
#print('not deleting', ami['Name'])
# 5. same for dr region
remote_amis_to_prune = ec2_dr.describe_images(Owners=['self'])
remote_amis = remote_amis_to_prune['Images']
for ami in remote_amis:
entry = str(ami['Name']) + ',' + str(ami['ImageId'])
match = re.search(last_week_date_tag,entry)
if match:
ec2_dr.deregister_image(ImageId=ami['ImageId'])
#print('deleting: ', ami['Name'])
else:
pass
#print('not deleting', ami['Name'])