Skip to content

Add tags to aws resources #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
node_modules/

# OS generated files
.DS_Store
.DS_Store

*.zip
65 changes: 65 additions & 0 deletions add-tags-to-aws-resources/add_tags_to_aws_resources.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const ec2 = require('./ec2');
// const lb = require('./elb');
const s3 = require('./s3');

async function configureAwsProfile(roleArn, externalId, region) {
try {
const AWS = require('aws-sdk');
if (roleArn && roleArn.trim() !== '') {
console.log('found roleArn');
const sts = new AWS.STS();
const params = {
DurationSeconds: 3600,
RoleArn: roleArn,
RoleSessionName: "Bob"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RoleSessionName seems not correct

};
if (externalId && externalId.trim() !== '') {
params.ExternalId = externalId;
}
const stsAssumeRoleResponse = await sts.assumeRole(params).promise();
AWS.config.update({
accessKeyId: stsAssumeRoleResponse.Credentials.AccessKeyId,
secretAccessKey: stsAssumeRoleResponse.Credentials.SecretAccessKey,
sessionToken: stsAssumeRoleResponse.Credentials.SessionToken
});
}
if (region) {
AWS.config.update({
region: region
});
}
return AWS;
} catch (error) {
throw error;
}
}

/**
*
* @param {*} resources {"s3": ["bucket-name-1","bucket-name-2"], "ec2": ["i-sdfsdf21", "vol-fwfddwf", "sg-dsfsd"] }
* @param {*} tags [{"Key": "demoKey", "Value": "demoValue"}]
* @param {*} region
* @param {*} roleArn
* @param {*} externalId
*/
async function handler(resources, tags, region, roleArn, externalId) {
try {
if (!resources || !tags || !region) {
throw new Error("Pass required values - resourceIds(['i-a123sd', 'vol-aff2123', 'sg-qdqe1232', ...]), tags([{Key:'sdad', Value: 'dd'}, ...]), region");
}
const AWS = await configureAwsProfile(roleArn, externalId, region);
await Promise.all([ec2.addTagsToEc2Resources(AWS, resources.ec2, tags),
s3.addTagsToS3Buckets(AWS, resources.s3, tags)
]);
} catch (error) {
throw error;
}
}
// handler(['i-sfsfg', 'vol-afafsf', 'i-01dc72751bb497ce3'], [{
// Key: 'demokey',
// Value: 'demovalue'
// }], 'ap-south-1');

module.exports = {
handler: handler
};
103 changes: 103 additions & 0 deletions add-tags-to-aws-resources/ec2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
let ec2 = null;
let errors = null;

function describeSgs(sgIds) {
const params = {
GroupIds: sgIds
};
return ec2.describeSecurityGroups(params).promise();
}

function describeVolumes(volumeIds) {
const params = {
VolumeIds: volumeIds
};
return ec2.describeVolumes(params).promise();
}

function describeInstances(instanceIds) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like these functions not doing much, do we really require a wrapper for this?

// console.log('Describing ', instanceIds);
const params = {
InstanceIds: instanceIds
};
return ec2.describeInstances(params).promise();
}

async function filterCorrectEc2Resources(ec2Resources) {
const correctEc2Resources = ec2Resources;
errors = [];
for (const id of correctEc2Resources.ec2InstanceIds) {
try {
await describeInstances([id]);
} catch (error) {
errors.push({
resource: id,
errorMessage: JSON.stringify(error.message)
});
// Remove element from array
correctEc2Resources.ec2InstanceIds.splice(correctEc2Resources.ec2InstanceIds.indexOf(id), 1);
}
}
for (const id of correctEc2Resources.volumeIds) {
try {
await describeVolumes([id]);
} catch (error) {
errors.push({
resource: id,
errorMessage: JSON.stringify(error.message)
});
// Remove element from array
correctEc2Resources.volumeIds.splice(correctEc2Resources.volumeIds.indexOf(id), 1);
}
}
for (const id of correctEc2Resources.sgIds) {
try {
await describeSgs([id]);
} catch (error) {
errors.push({
resource: id,
errorMessage: JSON.stringify(error.message)
});
// Remove element from array
correctEc2Resources.sgIds.splice(correctEc2Resources.sgIds.indexOf(id), 1);
}
}
return correctEc2Resources;
}

function filterEc2Resources(resources) {
const _resources = {};
_resources.ec2InstanceIds = resources.filter(id => id.startsWith('i-'));
_resources.volumeIds = resources.filter(id => id.startsWith('vol-'));
_resources.sgIds = resources.filter(id => id.startsWith('sg-'));
return _resources;
}

async function addTagsToEc2Resources(awsObject, resources, tags) {
try {
const AWS = awsObject;
ec2 = new AWS.EC2();
const ec2Resources = filterEc2Resources(resources);
const correctEc2Resources = await filterCorrectEc2Resources(ec2Resources);
const allCorrectResourcesInAnArray = correctEc2Resources.ec2InstanceIds
.concat(correctEc2Resources.volumeIds)
.concat(correctEc2Resources.sgIds);
if (allCorrectResourcesInAnArray && allCorrectResourcesInAnArray.length > 0) {
await ec2.createTags({
Resources: allCorrectResourcesInAnArray,
Tags: tags
}).promise();
console.log('Tags added successfully for EC2 resources are\n',
JSON.stringify(allCorrectResourcesInAnArray, null, 2));
}
if (errors && errors.length > 0) {
console.log('Problem with EC2 resources are\n', JSON.stringify(errors, null, 2));
}
} catch (error) {
throw error;
}
}

module.exports = {
addTagsToEc2Resources: addTagsToEc2Resources
};
73 changes: 73 additions & 0 deletions add-tags-to-aws-resources/elb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
let elbv2 = null;
let errors = null;

function addTags(resourceArns, tags) {
const params = {
ResourceArns: resourceArns,
Tags: tags
};
return elbv2.addTags(params).promise();
}

function describeLbs(lbArn) {
const params = {
LoadBalancerArns: [
lbArn
]
};
return elbv2.describeLoadBalancers(params).promise();
}

async function filterCorrectElbResources(elbResources) {
errors = [];
const _elbResources = elbResources;
for (const elbResource of _elbResources) {
try {
await describeLbs(elbResource);
} catch (error) {
errors.push({
resource: elbResource,
errorMessage: JSON.stringify(error.message)
});
// Remove element from array
_elbResources.splice(_elbResources.indexOf(elbResource), 1);
}
}
return _elbResources;
}
// filterCorrectElbResources(['afdf.elb.adfafd']).then(res => {
// console.log(res);
// console.log(errors)
// })

function filterElbResources(resources) {
return resources.filter(resource => resource.includes('elasticloadbalancing'));
}
// console.log(filterElbResources(['adfdf.elb.', 'asdasd']))

async function addTagsToElbResources(awsObject, resources, tags) {
try {
const AWS = awsObject;
elbv2 = new AWS.ELBv2();
const elbResources = filterElbResources(resources);
const correctElbResources = await filterCorrectElbResources(elbResources);
if (correctElbResources && correctElbResources.length > 0) {
await addTags(correctElbResources, tags);
console.log('Tags added successfully for LB resources are\n',
JSON.stringify(correctElbResources, null, 2));
}
if (errors && errors.length > 0) {
console.log('Problem with LB resources are\n', JSON.stringify(errors, null, 2));
}
} catch (error) {
throw error;
}
}
// addTagsToElbResources(require('aws-sdk'), ['arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188'], [{
// Key: 'demokey',
// Value: 'demovalue'
// }]);

module.exports = {
addTagsToElbResources: addTagsToElbResources
};
15 changes: 15 additions & 0 deletions add-tags-to-aws-resources/lambda.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const addTagsToAwsResourcesHandler = require('./add_tags_to_aws_resources');

/**
*
* @param {*} event {"resources":{"s3": ["bucket-name-1","bucket-name-2"], "ec2": ["i-sdfsdf21", "vol-fwfddwf", "sg-dsfsd"] },"tags":[{"Key": "demoKey", "Value": "demoValue"}] }
*
*/
exports.handler = async (event) => {
console.log('Received event\n', JSON.stringify(event, null, 2));
try {
await addTagsToAwsResourcesHandler.handler(event.resources, event.tags, event.region, event.roleArn, event.externalId);
} catch (error) {
throw error;
}
};
60 changes: 60 additions & 0 deletions add-tags-to-aws-resources/s3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
let errors = null;
let s3 = null;

function addTags(bucket, tags) {
const params = {
Bucket: bucket,
Tagging: {
TagSet: tags
}
};
return s3.putBucketTagging(params).promise();
}

function listAllBuckets() {
return s3.listBuckets({}).promise();
}

async function filterCorrectS3Resources(s3Buckets) {
try {
errors = [];
const _s3Buckets = s3Buckets;
const allBuckets = await listAllBuckets();
return _s3Buckets.filter((bucketOf_s3Buckets) => {
if (allBuckets.Buckets.findIndex((bucketOfAllBuckets) => bucketOfAllBuckets.Name === bucketOf_s3Buckets) !== -1) {
return true;
} else {
errors.push({
bucket: bucketOf_s3Buckets,
errorMessage: 'Bucket not found'
});
return false;
}
});
} catch (error) {
throw error;
}
}

async function addTagsToS3Buckets(awsObject, buckets, tags) {
try {
const AWS = awsObject;
s3 = new AWS.S3();
const correctS3Buckets = await filterCorrectS3Resources(buckets);
if (correctS3Buckets && correctS3Buckets.length > 0) {
for (const bucket of correctS3Buckets) {
await addTags(bucket, tags);
}
console.log('Tags added for S3 buckets are\n', JSON.stringify(correctS3Buckets, null, 2));
}
if (errors && errors.length > 0) {
console.log('Problem with S3 buckets are\n', JSON.stringify(errors, null, 2));
}
} catch (error) {
throw error;
}
}

module.exports = {
addTagsToS3Buckets: addTagsToS3Buckets
}