Consider using Data Lifecycle Manager or Backup.
Lambda functions to backup and rotate images of EC2 instance.
Set environment variable AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_REGION.
direnv is very useful for this.
Instead of setting AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, you can write your credentials on ~/.aws/credentials (and set AWS_PROFILE if it's not [default]).
Clone repo.
$ git clone https://github.com/y13i/amirotate.gitInstall dependencies.
$ cd amirotate
$ yarn
# or
$ npm installDeploy.
$ yarn run deploy
# or
$ npm run deployBy default, the functions will be scheduled to be invoked daily at 0:00 UTC (create) and 1:00 UTC (delete).
If you want to change the schedule, edit cron(0 0 ? * * *) in serverless.yml. See Serverless Framework - AWS Lambda Events - Scheduled & Recurring.
Create a tag for the EC2 instances you want to backup like below.
| Key | Value |
|---|---|
| amirotate:default | (JSON string) |
JSON string represents the option of amirotate for the instance. The structure is...
{
"NoReboot": (true | false), // Boolean. Optional. If true, CreateImage API will called with `NoReboot` option.
"Retention": { // Required. This option specifies retention policy for the image.
"Count": 1, // Numeric. Optional. If present, specified number of newest images will retained.
"Period": 180000000 // Numeric. Optional. Unit is in milliseconds. If present, the image will retained in specified time period after creation.
}
}The value must be valid JSON. Example below (No reboot, retain 3 images):
{"NoReboot": true, "Retention": {"Count": 3}}If you want to change the key of the tag from amirotate:default, simply edit provider.environment.tagKey in format of amirotate:<your alternate name here> in serverless.yml.
You can set multiple cycles by settting multiple schedule on functions.<create|delete>.events in serverless.yml. In that case, you must override tagKey value also.
For example...
functions:
create:
handler: lambda/create.default
events:
- schedule:
rate: cron(0 0 ? * * *)
input:
tagKey: amirotate:daily
- schedule:
rate: cron(0 1 ? * SUN *)
input:
tagKey: amirotate:weekly
delete:
handler: lambda/delete.default
events:
- schedule:
rate: cron(0 2 ? * * *)
input:
tagKey: amirotate:daily
- schedule:
rate: cron(0 3 ? * SUN *)
input:
tagKey: amirotate:weekly$ yarn run create
# or
$ npm run create$ yarn run delete
# or
$ npm run deleteIf you want to override tagKey with manual invocation,
$ echo '{"tagKey": "amirotate:daily"}' | yarn run create
# or
$ echo '{"tagKey": "amirotate:daily"}' | npm run create$ yarn run remove
# or
$ npm run remove- v1 - amirotate written in Ruby. Moved to y13i/amirotate-rb
- v2 - amirotatejs written in JavaScript with Apex. Moved to branch: apex-final
- v3 - current.