If you’re using AWS for a critical application then you probably have a disaster recovery region setup.   If it’s automated well, then everything you need to spin up the disaster recovery region should be quick and easy.   One thing that can be a bit of a pain is making sure all of your custom AMIs are available in your disaster recovery region.   You can do this manually every time you add or delete an AMI, but that gets time consuming and can easily be forgotten.

Here you’ll find a lambda function that you can schedule to run every so often, like once a day, to handle this for you.   It will compare your AMIs in your main region to those that exist in your DR region and copy any that do not exist.   There are a variety of options for doing this, but many solutions I’ve seen just leave any old AMIs in your DR region when they have been deleted from your main region, so eventually you have to go in and manually clean up the unused.

So the function will first look for any AMIs that exist in your DR region that do not exist in your primary region, and delete them along with the associated snapshot.   So, if you delete an AMI in your main region, when the function runs it will delete it from your DR region. For this reason, the DR region must specifically be just for disaster recovery.  If you have any custom AMIs in the region that do not exist in your primary region they will be deleted. The AMI name is used for comparison.

On to the good stuff.   You’ll first need to create an IAM role with the following policy:

Next, create a python 3.6 lambda function with a role of the previously created IAM role and put in the following code. You’ll need to edit the top 3 variables, for your source and destination region, along with your account id.

Two things I want to stress. First is, make sure you have filled in your source and destination regions properly. If you get this backwards, then this will delete all of the AMIs in your source region, so check and then check again. Secondly, dAuo not use this if you have AMIs in your destination region that do not exist in your source region that you want to keep.

Once you have checked and double checked your source and destination region, you can save and test. After a bit, you’ll see all of your AMIs being created in the specified destination region. Once that looks good you can schedule it to run once a day by using a scheduled cloudwatch event by following these steps:

  • Go to Services, Lambda, click the unction name
  • Click on Triggers and then on Add trigger
  • Select Cloudwatch Events
  • Create a new Rule.
  • Schedule Expression: cron(0 0 * * ? *)
  • Check Enable Trigger
  • Click Submit