An Amazon Machine Image (AMI) provides the information required to launch an instance, which is a virtual server in the cloud.
You can launch multiple instances from a single AMI when you need multiple instances with the same configuration. You can use different AMIs to launch instances when you need instances with different configurations.
This lambda function will create AMI(Amazon Machine Images) of your instances and tag them for replication or auto deletion. You can customize it to make images of only your
running
instances.
You can also follow this article in Youtube
We will need the following pre-requisites to successfully complete this activity,
- Few
Instances
with a Tag Key:AmiBackUp
and Value asYes
- By default, both running & stopped instance AMI's are baked.
- IAM Role - i.e
Lambda Service Role
- with below mentioned policy
The image above shows the execution order, that should not be confused with the numbering of steps given here
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": "ec2:Describe*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ec2:CreateImage",
"ec2:DeregisterImage",
"ec2:CreateSnapshot",
"ec2:DeleteSnapshot",
"ec2:CreateTags",
"ec2:ModifySnapshotAttribute",
"ec2:ResetSnapshotAttribute",
"iam:Get*"
],
"Resource": [
"*"
]
}
]
}
The below script is written in Python 3.8
. Remember to choose the same in AWS Lambda Functions.
-
Change the global variables at the top of the script to suit your needs.
-
globalVars['findNeedle']
- My Instances have tagAmiBackUp
, -
globalVars['RetentionDays']
- Set the value you desire, by default it is set to 30 days -
globalVars['ReplicateAMI']
- If you want to use my Serverless AMI Replicator
-
-
Copy
the code fromserverless-ami-backup.py
in this repo to the lambda function -
Increase
the lambda timeout according to the number of instances and the size of each EBS volume. You could start with60
seconds and then increase or decrease it based on your results, the default is3
seconds. -
Disable
retry attempts on asynchronous invocation (configuremaximum-retry-attempts
to0
). The default value is2
, but is not recommended to this function because of the lack of idempotence. -
Save
the lambda function
We are going to use Cloudwatch Scheduled Events to take backup everyday.
rate(1 minute)
or
rate(5 minutes)
or
rate(1 day)
# The below example creates a rule that is triggered every day at 12:00pm UTC.
cron(0 12 * * ? *)
If you want to learn more about the above Scheduled expressions, Ref: CloudWatch - Schedule Expressions for Rules
Start few Instance with the Tag KeyAmiBackUp
with Value as Yes
We have demonstrated how you can automatically identify instances that require AMI Backup, create AMIs and tag them.
You can use a serverless mechanism to replicate the AMI across Regions for Disaster Recovery. Have a look at this video