I want to take backup the file from one s3 bucket to another s3 bucket. I'm using lambda function with nodejs for taking backup for dynamo DB. So i want to copy the files from s3 to another s3 bucket. Can anyone tell me the nodejs code for copying files from s3 to s3?
4
votes
2 Answers
5
votes
You can try the following code in lambda:
// Load the AWS SDK
const aws = require('aws-sdk');
const s3 = new aws.S3();
// Define 2 new variables for the source and destination buckets
var srcBucket = "YOUR-SOURCE-BUCKET";
var destBucket = "YOUR-DESTINATION-BUCKET";
var sourceObject = "YOUR-SOURCE-OBJECT";
//Main function
exports.handler = (event, context, callback) => {
//Copy the current object to the destination bucket
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#copyObject-property
s3.copyObject({
CopySource: srcBucket + '/' + sourceObject,
Bucket: destBucket,
Key: sourceObject
}, function(copyErr, copyData){
if (copyErr) {
console.log("Error: " + copyErr);
} else {
console.log('Copied OK');
}
});
callback(null, 'All done!');
};
And Attach the following Policy to your IAM Role attached in Lambda:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListSourceAndDestinationBuckets",
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:ListBucketVersions"
],
"Resource": [
"arn:aws:s3:::YOUR-SOURCE-BUCKET",
"arn:aws:s3:::YOUR-DESTINATION-BUCKET"
]
},
{
"Sid": "SourceBucketGetObjectAccess",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:GetObjectVersion"
],
"Resource": "arn:aws:s3:::YOUR-SOURCE-BUCKET/*"
},
{
"Sid": "DestinationBucketPutObjectAccess",
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": "arn:aws:s3:::YOUR-DESTINATION-BUCKET/*"
}
]
}