Link to home
Start Free TrialLog in
Avatar of peter
peterFlag for United States of America

asked on

Help preserve AWS tags in node.js

Hi everyone,
Does anyone know how to preserve snapshot tags in AWS. This node.js function moves the snapshots to another region but does not preserve tags so it becomes difficult to identify which server the snapshot belonged to.
If I cannot preserve tags, I would like to know how to tag a snapshot using the javascript code below. Example Key:DeleteOn Value [currentdate]
I found this code snippet that may be of help:
http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-creating-an-instance.html

 // Add tags to the instance
   params = {Resources: [instanceId], Tags: [
      {
         Key: 'DeleteOn',
         Value: 'current date as 2017-12-05'
      }
   ]};
   ec2.createTags(params, function(err) {
      console.log("Tagging instance", err ? "failure" : "success");
   });
Thanks!
Peter
//define variables
var sourceRegion = 'us-east-1';
var destinationRegion = 'us-east-2';
var AWS = require('aws-sdk');
console.log ('Loading function');

//main function
exports.handler = (event, context, callback) => {

    //Get the EBS snapshot ID from Cloudwatch event details
    var snapshotArn = event.detail.snapshot_id.split('/');
    const snapshotId = snapshotArn['1'];
    const description = 'Snapshot copy from ${snapshotId} in ${sourceRegion}';
    console.log ("snapshotId:", snapshotId);

    //Load EC2 class and update the configuration to use destination
    AWS.config.update({region: destinationRegion});
    var ec2 = new AWS.EC2();

    //Prepare variables for ec2.modifySnapshotAttribute call
    const copySnapshotParams = {
        Description: description,
        DestinationRegion: destinationRegion,
        SourceRegion: sourceRegion,
        SourceSnapshotId: snapshotId
    };

    ec2.copySnapshot(copySnapshotParams, (err, data) => {
        if (err) {
            const errorMessage = `Error copying snapshot ${snapshotId} to region ${destinationRegion}.`;
            console.log(errorMessage);
            console.log(err);
            callback(errorMessage);
        } else {
            const successMessage = `Successfully started copy of snapshot ${snapshotId} to region ${destinationRegion}.`;
            console.log(successMessage);
            console.log(data);
            callback(null, successMessage);
        }
    });
};

Open in new window

Avatar of Phil Phillips
Phil Phillips
Flag of United States of America image

You'll likely have to describe the tags on the source snapshot, then create them on the destination.  Something like this (untested, so I don't know if it works or not! But hopefully gives you the right idea):

//define variables
var sourceRegion = 'us-east-1';
var destinationRegion = 'us-east-2';
var AWS = require('aws-sdk');
console.log ('Loading function');

//main function
exports.handler = (event, context, callback) => {

    //Get the EBS snapshot ID from Cloudwatch event details
    var snapshotArn = event.detail.snapshot_id.split('/');
    const snapshotId = snapshotArn['1'];
    const description = 'Snapshot copy from ${snapshotId} in ${sourceRegion}';
    console.log ("snapshotId:", snapshotId);

    //Load EC2 class and update the configuration to use destination
    AWS.config.update({region: destinationRegion});
    var ec2 = new AWS.EC2();

    //Prepare variables for ec2.modifySnapshotAttribute call
    const copySnapshotParams = {
        Description: description,
        DestinationRegion: destinationRegion,
        SourceRegion: sourceRegion,
        SourceSnapshotId: snapshotId
    };

    ec2.copySnapshot(copySnapshotParams, (err, data) => {
        if (err) {
            const errorMessage = 'Error copying snapshot ${snapshotId} to region ${destinationRegion}.';
            console.log(errorMessage);
            console.log(err);
            callback(errorMessage);
        } else {
            const successMessage = 'Successfully started copy of snapshot ${snapshotId} to region ${destinationRegion}.';
            console.log(successMessage);
            console.log(data);
            copyTags(snapshotId, data.SnapshotId, (err, data) => {
                if (err) {
                    callback(err);
                }
                else {
                    callback(null, successMessage);
                }
            });
        }
    });
};

function copyTags(sourceId, destinationId, callback) {
    // Get the tags to copy
    ec2.describeTags({
        Filters: [
            {
                Name: "resource-id",
                Values: [ sourceId ]
            }
        ]
    }, (err, data) => {
        if (err) {
            const errorMessage = 'Error describing ${sourceId}';
            console.log(errorMessage);
            console.log(err);
            callback(errorMessage);
        } else {
            ec2.createTags({
                Resources: [ destinationId ],
                Tags: data.Tags
            }, (err, data) => {
                if (err) {
                    const errorMessage = 'Error tagging ${destinationId}';
                    console.log(errorMessage);
                    console.log(err);
                    callback(errorMessage);
                }
                else {
                    callback(null);
                }
            });
        }
    });
}

Open in new window

Avatar of peter

ASKER

Ok, that does make sense. I don't know about the formatting however, looks pretty broken. But , I can work with it. I'm wondering however if maybe its best to have a separate Python or node.js script at the destination [in us-east-2] to iterate over any new snapshots that have arrived, and tag them, with the current time. Then another script to delete snapshots with tags older then 7 days.
ASKER CERTIFIED SOLUTION
Avatar of Phil Phillips
Phil Phillips
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of peter

ASKER

I'll close this question, as helpful to solve my problem, thank you!
Peter