Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joech4n/333054cfcc381a865c26229442f78d26 to your computer and use it in GitHub Desktop.
Save joech4n/333054cfcc381a865c26229442f78d26 to your computer and use it in GitHub Desktop.
a lambda function to automatically take ownership of any objects written into an s3 bucket. Inspired by https://gist.github.com/joech4n/953c1cd6a36698c5d120
console.log('Loading event');
var aws = require('aws-sdk');
var s3 = new aws.S3({apiVersion: '2006-03-01'});
exports.handler = function(event, context) {
// uses s3.listBuckets to fetch the canonical ID of the AWS account
s3.listBuckets(function(err,data) {
if (err) {
console.log(err, err.stack);
} else {
var canonicalAccountId = data.Owner.ID;
console.log('Received event:');
console.log(JSON.stringify(event, null, ' '));
// Get the data from the event
var bucket = event.Records[0].s3.bucket.name;
var key = event.Records[0].s3.object.key;
var getOwnerParams = {
Bucket: bucket, /* required */
Key: decodeURIComponent(key), /* required */
};
// Gets the owner of the S3 Object
s3.getObjectAcl(getOwnerParams, function(err, data) {
if (err)
console.log(err, err.stack); // an error occurred
else {
// If the owner is not the correct, then overwrite itself, else do nothing
var objectOwnerId = data.Owner.ID;
if (objectOwnerId != canonicalAccountId) {
console.log("INFO: Object owner not correct. overwriting...");
overwriteS3Object();
} else {
console.log("INFO: Object owner correct. Not doing anything...");
context.done(null,'');
}
}
});
function overwriteS3Object() {
// Configure params for CopyObject: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#copyObject-property
var copyParams = {
Bucket: bucket, /* required */
CopySource: bucket + '/' + key, /* required */
Key: decodeURIComponent(key), /* required; URL-decoded because event URL-encodes the key.
For some reason, CopySource does not require this */
StorageClass: 'STANDARD', /* Must include this to be able to overwrite a file */
ServerSideEncryption: 'AES256' /* server side encryption */
};
s3.copyObject(copyParams,
function(err,data) {
if (err) {
console.log('ERROR: Problem overwriting ' + bucket + '/' +key + '. Make sure they exist and your bucket is in the same region as this function.');
errorMessage = 'ERROR: Error from S3: '+err;
console.log(errorMessage);
context.done('error', errorMessage);
}
else {
console.log('SUCCESS: Overwritten ' + bucket + '/' + key);
context.done(null,'');
}
}
);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment