{"id":389,"date":"2022-05-21T13:24:13","date_gmt":"2022-05-21T13:24:13","guid":{"rendered":"http:\/\/checkmateq.com\/blog\/?p=389"},"modified":"2024-10-19T17:41:06","modified_gmt":"2024-10-19T17:41:06","slug":"automating-ami-backup","status":"publish","type":"post","link":"https:\/\/www.checkmateq.com\/blog\/automating-ami-backup","title":{"rendered":"Automating AMI Backup Using Lambda and CloudWatch"},"content":{"rendered":"<p>In this article, we will create an AWS cloud Ec2 instances backup solution using Python script, CloudWatch, and AWS Lambda functions that will take instance backups on a regular basis.<\/p>\n<p><a href=\"https:\/\/www.checkmateq.com\/aws-cloud\"><b>AWS Lambda<\/b><\/a> is an event-driven Serverless compute service provided by AWS that lets you run your code without provisioning and managing infrastructure.<\/p>\n<p>We will create two lambda functions with Python to create a backup AMI and delete it after the retention period and use Cloudwatch to automate this task so that we get a new backup AMI every fifteen days with the previous one automatically deleted.<\/p>\n<h3><strong>Step1:<\/strong> <strong>First, we need to create an IAM Role with the required privileges<\/strong><\/h3>\n<ul>\n<li>Go to IAM-&gt;Policies-&gt;Create Policy-&gt;JSON.<\/li>\n<li>Paste the following code there<\/li>\n<\/ul>\n<pre>{\r\n\"Version\": \"2012-10-17\",\r\n\"Statement\": [\r\n{\r\n\"Effect\": \"Allow\",\r\n\"Action\": [\r\n\"logs:*\"\r\n],\r\n\"Resource\": \"arn:aws:logs:*:*:*\"\r\n},\r\n{\r\n\"Effect\": \"Allow\",\r\n\"Action\": \"ec2:*\",\r\n\"Resource\": \"*\"\r\n}\r\n]\r\n}\r\n<\/pre>\n<ul>\n<li>Click Next, add Tags.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-421\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171346-300x53.png\" alt=\"\" width=\"702\" height=\"124\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171346-300x53.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171346-1024x181.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171346-768x136.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171346-1200x212.png 1200w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171346.png 1390w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<ul>\n<li>Click Next, and give the Name and description to the policy.<\/li>\n<li>Click on create policy.<\/li>\n<li>Go to Roles-&gt;Create Roles.<\/li>\n<li>Select AWS service as the trusted entity type and Lambda in the use case.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-426\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171905-300x118.png\" alt=\"Lambda \" width=\"686\" height=\"270\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171905-300x118.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-171905.png 742w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<ul>\n<li>Click Next. Enter the name of the policy in the search bar, select it, and hit next.<\/li>\n<li>Give name and description to Role and click on Create Role.<\/li>\n<\/ul>\n<h3><strong>Step 2: Now we need to create AWS lambda functions<\/strong><\/h3>\n<ul>\n<li>Go to the Lambda service console.<\/li>\n<li>Click on Create Function.<\/li>\n<li>Select Author from scratch, give the function name, and select Python 3.9 as runtime.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-434\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744-300x121.png\" alt=\"\" width=\"719\" height=\"290\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744-300x121.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744-1024x414.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744-768x311.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744-1536x621.png 1536w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744-1200x486.png 1200w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-173744.png 1693w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<ul>\n<li>Select the architecture. Change the default execution role and select the role which we have created.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-437\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014-300x130.png\" alt=\"\" width=\"720\" height=\"312\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014-300x130.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014-1024x444.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014-768x333.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014-1536x666.png 1536w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014-1200x521.png 1200w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174014.png 1549w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<ul>\n<li>Click on Create Function. First we will create lambda function for creating AMI.<\/li>\n<li>Copy the following python script and paste it into the Code section.<\/li>\n<\/ul>\n<pre>import boto3\r\nimport os\r\nimport datetime\r\nimport time\r\nimport collections\r\n\r\ndef lambda_handler(event, context):\r\n   retention_days=15\r\n   aws_account_id = context.invoked_function_arn.split(\":\")[4]\r\n   delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)\r\n   delete_fmt = delete_date.strftime('%m-%d-%Y-%H')\r\n   create_time = datetime.datetime.now()\r\n   create_fmt = create_time.strftime('%m-%d-%Y-%H')\r\n\r\n   ec2_resource = boto3.client('ec2')\r\n\r\n   reservations = ec2_resource.describe_instances(\r\n   Filters=[\r\n             {'Name': 'tag:key', 'Values': ['Backup']}\r\n           ]\r\n             ).get(\r\n                 'Reservations', []\r\n                   )\r\n\r\n   instances = sum(\r\n             [\r\n                  [i for i in r['Instances']]\r\n                       for r in reservations\r\n             ], [])\r\n\r\n\r\n   ami_list = []\r\n   for instance in instances:\r\n         name = \"Lambda\" + \"-\" + instance['InstanceId']+ \"-\" + create_fmt\r\n         amiid = ec2_resource.create_image(\r\n                   Description=\"Lambda AMI\",\r\n                   DryRun=False,\r\n                   InstanceId=instance['InstanceId'],\r\n                   Name= name,\r\n                   NoReboot=True\r\n                  )\r\n\r\n        ec2_resource.create_tags(\r\n        Resources=[amiid['ImageId']],\r\n        Tags=[\r\n              {'Key': 'Delete', 'Value': delete_fmt},\r\n              {'Key': 'Backup', 'Value': 'True'},\r\n              {'Key': 'Name', 'Value': name}\r\n             ]\r\n          )\r\n\r\n       ami_list.append(amiid['ImageId'])\r\n       time.sleep(10)\r\n\r\n       for ami in ami_list:\r\n          snapshots = ec2_resource.describe_snapshots(\r\n          DryRun=False,\r\n          OwnerIds=[\r\n          aws_account_id\r\n           ],\r\n          Filters=[{\r\n              'Name': 'description',\r\n              'Values': [ '*'+ami+'*']\r\n                  }] ).get('Snapshots', [] )\r\n\r\n         delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)\r\n         delete_fmt = delete_date.strftime('%m-%d-%Y-%H')\r\n         snap_tag = ami + \"-\" + \"Lambda\"\r\n         \r\n         for snapshot in snapshots:\r\n              ec2_resource.create_tags(\r\n              Resources=[snapshot['SnapshotId']],\r\n              Tags=[\r\n                 {'Key': 'DeleteOn', 'Value': delete_fmt},\r\n                 {'Key': 'Backup', 'Value': 'True'},\r\n                 {'Key': 'Name', 'Value': snap_tag},\r\n                ]\r\n               )\r\n<\/pre>\n<ul>\n<li>Go to Configuration-&gt; Edit General Configuration. Increase the timeout to 15 seconds.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-441\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174702-300x136.png\" alt=\"\" width=\"686\" height=\"311\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174702-300x136.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174702-1024x466.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174702-768x349.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-174702.png 1051w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<ul>\n<li>Click on Test to create AMI.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-442\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-175037-300x70.png\" alt=\"Lambda \" width=\"579\" height=\"135\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-175037-300x70.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-175037-1024x238.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-175037-768x179.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-175037-1200x279.png 1200w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-175037.png 1225w\" sizes=\"(max-width: 579px) 85vw, 579px\" \/><\/p>\n<ul>\n<li>Now create another lambda function to delete the AMI. Copy the following python script in Code and increase the timeout to 15 seconds in Configuration.<\/li>\n<\/ul>\n<pre>import boto3\r\nimport datetime\r\nimport os\r\nimport time\r\n\r\nec2_resource = boto3.client('ec2')\r\ndef lambda_handler(event, context):\r\n      aws_account_id = context.invoked_function_arn.split(\":\")[4]\r\n      image_resource = ec2_resource.describe_images(\r\n                DryRun=False,\r\n                Owners=[aws_account_id],\r\n                Filters=[\r\n                     {'Name': 'tag:Backup', 'Values': ['True']}\r\n                        ]\r\n               ).get(\r\n                      'Images', []\r\n                     )\r\n                amiList = []\r\n      current_date = datetime.datetime.now().strftime('%m-%d-%Y-%H:%M:%S')\r\n      time.sleep(5)\r\n      for image in image_resource:\r\n      deleteon = ''\r\n      for tag in image['Tags']:\r\n             if tag['Key'] == 'DeleteOn':\r\n                deleteon = tag['Value']\r\n                break\r\n             if deleteon == '':\r\n                continue\r\n             if deleteon &gt; currentDate:\r\n                ec2_resource.deregister_image(\r\n                DryRun=False,\r\n                 ImageId=image['ImageId']\r\n               )\r\n                amiList.append(image['ImageId'])\r\n                snapshots = ec2_resource.describe_snapshots(\r\n                               DryRun=False,\r\n                               OwnerIds=[\r\n                                    aws_account_id\r\n                                        ],\r\n                               Filters=[\r\n                                 {\r\n                                    'Name': 'description',\r\n                                    'Values': [ '*'+image['ImageId']+'*' ]\r\n                                 } ]\r\n                                      ).get(\r\n                                               'Snapshots', []\r\n                                            )\r\n               for snapshot in snapshots:\r\n                     time.sleep(5)\r\n                     ec2_resource.delete_snapshot(\r\n                             DryRun = False,\r\n                             SnapshotId = snapshot['SnapshotId']\r\n                                 )\r\n<\/pre>\n<h3><strong>Step 3: Create a Trigger for our Lambda Functions<\/strong><\/h3>\n<ul>\n<li>Select our lambda function for AMI backup.<\/li>\n<li>Go to Configuration-&gt;Triggers-&gt;Add Triggers.<\/li>\n<li>Select EventBridge(CloudWatch Events).<\/li>\n<li>Enter your cron expression in Schedule Expression.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-451\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-185819-300x88.png\" alt=\"Lambda \" width=\"726\" height=\"213\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-185819-300x88.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-185819-1024x300.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-185819-768x225.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-185819.png 1108w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>This will run our function on the 1st and 15th of every month at 8 AM.<\/li>\n<li>Click on Add Trigger.<\/li>\n<li>Now repeat the above steps and create a trigger for our other lambda function for deleting AMI.<\/li>\n<li>Add the following cron expression to delete our old AMI on the 1st and 15th of every month at 11 AM.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" class=\"alignnone wp-image-448\" src=\"http:\/\/checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-184459-300x41.png\" alt=\"\" width=\"732\" height=\"100\" srcset=\"https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-184459-300x41.png 300w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-184459-1024x141.png 1024w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-184459-768x106.png 768w, https:\/\/www.checkmateq.com\/blog\/wp-content\/uploads\/2022\/05\/Screenshot-2022-05-21-184459.png 1093w\" sizes=\"(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/p>\n<p>Author info<\/p>\n<p>This blog is written by Checkmate Management Consulting cloud engineering team. Please <a href=\"https:\/\/www.checkmateq.com\/contact-us\">write<\/a> to our technical to <a href=\"https:\/\/www.checkmateq.com\/hire-developer\">hire fully managed cloud engineer<\/a> to transform entire cloud infrastructure and <a href=\"https:\/\/www.checkmateq.com\/hire-developer\">IT Staffing Services in India<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will create an AWS cloud Ec2 instances backup solution using Python script, CloudWatch, and AWS Lambda functions that will take instance backups on a regular basis. AWS Lambda is an event-driven Serverless compute service provided by AWS that lets you run your code without provisioning and managing infrastructure. We will create &hellip; <a href=\"https:\/\/www.checkmateq.com\/blog\/automating-ami-backup\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Automating AMI Backup Using Lambda and CloudWatch&#8221;<\/span><\/a><\/p>\n","protected":false},"author":3,"featured_media":518,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[4,3,7,11,8,6],"_links":{"self":[{"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/posts\/389"}],"collection":[{"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/comments?post=389"}],"version-history":[{"count":20,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/posts\/389\/revisions"}],"predecessor-version":[{"id":4630,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/posts\/389\/revisions\/4630"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/media\/518"}],"wp:attachment":[{"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/media?parent=389"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/categories?post=389"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.checkmateq.com\/blog\/wp-json\/wp\/v2\/tags?post=389"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}