我不是一个强大的编码器,但是尝试使用 node.js 创建一个Lambda函数,该函数每天通过Lambda cron运行一次,以将S3存储桶中的文件移动到“归档”存储桶中
尝试了各种方法
sudo nodejs -e "console.log(require('./index').handler({}));"
我在本地计算机上的输出是:
Running MyApp
Source mybucket
Target mybucket-archive
Account test
undefined
这是我的代码:
var aws = require('./node_modules/aws-sdk');
var s3 = new aws.S3();
console.log('Running myapp');
console.log(JSON.stringify(context.invokedFunctionArn).split(':')[4]);
var AccountNumber = (JSON.stringify(context.invokedFunctionArn).split(':')[4]);
if(AccountNumber == '123456789000') { SourceBucket = 'mybucket-test'; } //test account
if(AccountNumber == '198765432101') { SourceBucket = 'mybucket-prod'; } //prod account
var targetBucket = SourceBucket+"-archive"
//Debug?
console.log("Source", SourceBucket);
console.log("Target", targetBucket);
console.log("Account", AccountNumber);
exports.handler = function () {
// var exec = require('child_process').exec;
const exec = require('child_process').exec;
exec("aws s3 mv s3://", +SourceBucket+ "/incoming/test/ s3://" +targetBucket+ "/incoming/test/ --recursive"), (err, stdout, stderr) => {
//exec(echo 'hello world'), (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
console.log(err);
return;
}
// the *entire* stdout and stderr (buffered)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
}
};
我期望的是aws cli被调用并将文件从主存储桶移动到存档存储桶。
我们只希望每天上传10-20个1kb的小txt文件,因此我们希望该文件可以在Lambda要求内运行。这必须通过Lambda cron运行,因为其他lambda上使用了s3事件。
答案 0 :(得分:0)
要将文件从一个s3存储桶移动到另一个s3存储桶,我们可以使用aws-sdk
,它是Javascript的SDK。
参考文献:
https://aws.amazon.com/sdk-for-node-js/
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html
const AWS = require('aws-sdk');
const s3 = new AWS.S3({
// Input the region that you are using here.
region: 'eu-west-1',
});
exports.handler = async (event, context) {
const sourceBucket = 'bucket-1';
const destinationBucket = 'bucket-2';
const files = await s3
.listObjects({
Bucket: sourceBucket,
})
.promise();
return Promise.all(
files.Contents.map(async content => {
await s3
.copyObject({
Bucket: destinationBucket,
CopySource: `/${sourceBucket}/${content.Key}`,
Key: content.Key,
})
.promise();
return s3
.deleteObject({
Bucket: sourceBucket,
Key: content.Key,
})
.promise();
})
);
}
您也可以使用aws cli和子进程来执行此操作。 代码中的错误是,当您尝试追加命令时,在SourceBucket之前有一个“,”。 :-)因此,该命令从未执行过。
async function handler(event, context) {
const SourceBucket = 'bucket-1';
const targetBucket = 'bucket-2';
const exec = require('child_process').exec;
console.log(
'aws s3 mv s3://'
+SourceBucket +
'/ s3://' +
targetBucket +
'/ --recursive'
);
exec(
'aws s3 mv s3://'
+SourceBucket +
'/ s3://' +
targetBucket +
'/ --recursive'
),
(err, stdout, stderr) => {
//exec(echo 'hello world'), (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
console.log(err);
return;
}
// the *entire* stdout and stderr (buffered)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
};
}