用于将文件从s3复制到s3存储桶的节点js代码

时间:2018-12-13 10:33:32

标签: node.js amazon-web-services amazon-s3

我想将文件从一个s3存储桶备份到另一个s3存储桶。我正在将lambda函数与nodejs一起使用以为dynamo DB进行备份。所以我想将文件从s3复制到另一个s3存储桶。谁能告诉我用于将文件从s3复制到s3的nodejs代码吗?

2 个答案:

答案 0 :(得分:1)

您可以在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!');
};

并将以下策略附加到Lambda中附加的IAM角色:

{
    "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/*"
        }
    ]
 }

希望这会有所帮助。

答案 1 :(得分:0)

我觉得将文件从S3复制到S3没有任何意义。通常,应该使用S3的LifeCyclePolicies将S3复制到Glacier。该功能已经存在。