-1

how to take all Working EC2 server backup automatically at particular time?

auto delete old backup and take new backup everyday

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102
  • 1
    Please note that Amazon EBS snapshots are copies of the disk volume at the time that the snapshot was made. This is not necessarily a "working backup" because the systems running on the Amazon EC2 instances might not have saved data in a consistent state. It's a bit like pulling the power out of a computer and then turning it on again. I recommend that you thoroughly test such backups and then figure out procedures on how to restore from such backups. – John Rotenstein Oct 29 '18 at 21:04

2 Answers2

1

You can create automated EC2 backups using CloudWatch Events.

You'll define the rate at which the scheduler runs inside of CloudWatch in the AWS Console.


(From AWS)

Create a rule that takes snapshots on a schedule. You can use a rate expression or a cron expression to specify the schedule. For more information, see Schedule Expressions for Rules.

To create a rule

  1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/.
  2. In the navigation pane, choose Events, Create rule.
  3. For Event Source, do the following:
    • Choose Schedule.
    • Choose Fixed rate of and specify the schedule interval (for example, 5 minutes). Alternatively, choose Cron expression and specify a cron expression (for example, every 15 minutes Monday through Friday, starting at the current time).
  4. For Targets, choose Add target and then select EC2 CreateSnapshot API call. You may have to scroll up in the list of possible targets to find EC2 CreateSnapshot API call.
  5. For Volume ID, type the volume ID of the targeted Amazon EBS volume.
  6. Choose Create a new role for this specific resource. The new role grants the target permissions to access resources on your behalf.
  7. Choose Configure details.
  8. For Rule definition, type a name and description for the rule.
  9. Choose Create rule.

I've used this exact process successfully in creating automated backups of my EC2 instances.

Shawn
  • 513
  • 9
  • 18
0

Aws lambda auto AMI backup script with cloudwatch log across all region in

2 lambda function for create and Delete and you have to make new policy and role for it

creat_backup

    var aws = require('aws-sdk');  
Region = ['ap-south-1','eu-central-1','us-east-1'];
var now = new Date();   
date = now.toISOString().substring(0, 10)  
hours = now.getHours()  
minutes = now.getMinutes()  

exports.handler =  function (event, context) 
{  
    var instanceparams = {
        Filters: [{
            Name: 'tag:Backup',
            Values: [
                'yes'
            ]
        }]
    }
    region(0);
  async function region(h){

    if(h>=Region.length)
    return;
    console.log("H Value Test",h);
    aws.config.region = Region[h];
    var ec2 = new aws.EC2(); 
    console.log("SELECTED REGION",Region[h])
   return await ec2.describeInstances(instanceparams, function(err, data) {
        if (err) console.log(err, err.stack);
        else {
            for (var i in data.Reservations) {
                var ec1 = new aws.EC2(); 
                for (var j in data.Reservations[i].Instances) {
                    console.log("instance is ",data.Reservations[i].Instances[j].InstanceId);
                    instanceid = data.Reservations[i].Instances[j].InstanceId;
                    nametag = data.Reservations[i].Instances[j].Tags
                    for (var k in data.Reservations[i].Instances[j].Tags) {
                        if (data.Reservations[i].Instances[j].Tags[k].Key == 'Name') {
                            name = data.Reservations[i].Instances[j].Tags[k].Value;
                        }
                    }
                    console.log("Creating AMIs of the Instance: ", name);
                    var imageparams = {
                        InstanceId: instanceid,
                        Name: name + "_" + date + "_" + hours + "-" + minutes,
                        NoReboot: true
                    }
                 ec1.createImage(imageparams, function(err, data) {
                        if (err) console.log(err, err.stack);
                        else {
                            image = data.ImageId;
                            console.log("image",image);
                            var tagparams = {
                                Resources: [image],
                                Tags: [{
                                    Key: 'DeleteOn',
                                    Value: 'yes'
                                }]
                            };
                            ec1.createTags(tagparams, function(err, data) {
                                console.log("Tags added to the created AMIs");
                            });
                           }ec1=null;
                    });

                }
            }
        }
        aws.config.region = null;
        ec2 = null; 
        h+=1
        region(h)
    });
    }   
}

delete function

var aws = require('aws-sdk');  
Region = ['ap-south-1','eu-central-1','us-east-1'];

var d = new Date();  
var x = 1;  /* ------Retention Days------- */  
d.setDate(d.getDate() - x);  
reqdate = d.toISOString().substring(0, 10);  


exports.handler = function(event, context) {  
var instanceparams = {
    Owners: [
        'self'
    ],
    Filters: [{
        Name: 'tag:DeleteOn',
        Values: [
            'yes'
        ]
    }]

  }

  region(0);
function region(h){

    if(h>=Region.length)
    return;
    console.log("H Value Test",h);
    aws.config.region = Region[h];
     var ec2 = new aws.EC2(); 
    console.log("SELECTED REGION",Region[h]); 

ec2.describeImages(instanceparams, function(err, data) {
    if (err) console.log(err, err.stack);
    else {
        for (var j in data.Images) {
            imagename = data.Images[j].Name
            imageid = data.Images[j].ImageId

            //if (imagename.indexOf(reqdate) > -1) {
                console.log("image that is going to be deregistered: ", imagename);
                console.log("image id: ", imageid);

                var deregisterparams = {
                    ImageId: imageid
                };
                ec2.deregisterImage(deregisterparams, function(err, data01) {
                    if (err) console.log(err, err.stack); // an error occurred
                    else {
                        console.log("Image Deregistered");

                    }
                });
            //}
        }
        setTimeout(function() {
            for (var j in data.Images) {
                imagename = data.Images[j].Name
              //  if (imagename.indexOf(reqdate) > -1) {
                    for (var k in data.Images[j].BlockDeviceMappings) {
                        snap = data.Images[j].BlockDeviceMappings[k].Ebs.SnapshotId;
                        console.log(snap);
                        var snapparams = {
                            SnapshotId: snap
                        };
                        ec2.deleteSnapshot(snapparams, function(err, data) {
                            if (err) console.log(err, err.stack); // an error occurred
                            else console.log("Snapshot Deleted"); // successful response
                        });
                    }
                //}
            }
        }, 30000);
    }
      aws.config.region = null;
        h+=1
        region(h);
});
}
}

for more info visit https://github.com/harsh4870/AWS-auto-ami-backup-across-all-region

Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102