简体   繁体   English

使用 aws lambda 函数中的节点 js 在其中创建 s3 存储桶和文件夹

[英]creating s3 bucket and folders inside it using node js in aws lambda function

I am both new to Node js and AWS.我是 Node js 和 AWS 的新手。 I am trying to create a bucket in S3 using node js in lambda function.我正在尝试使用 lambda 函数中的节点 js 在 S3 中创建一个存储桶。 Consequently, I am trying to create folders inside this S3 bucket.因此,我试图在这个 S3 存储桶中创建文件夹。

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working.我遵循了之前回答的所有问题并尝试了不同的代码迭代,但似乎没有一个有效。 Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.以下是我的代码,它在没有出现任何问题的情况下执行,但没有创建存储桶和文件夹。

const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};

The code for creating folders inside the Lambda function is as following --在 Lambda 函数中创建文件夹的代码如下——

var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });

Both of them doesn't work.他们两个都不起作用。 I read a lot of documents on this issue and answers previously asked, but none of them are working for me.我阅读了很多关于这个问题的文件和之前提出的答案,但没有一个对我有用。

The lambda function has a timeout of 1 minute. lambda 函数的超时时间为 1 分钟。 It has following policies for the IAM role - 1. AmazonRDSFullAccess 2. AmazonS3FullAccess 3. AWSLambdaVPCExecutionRole它对 IAM 角色具有以下策略 - 1. AmazonRDSFullAccess 2. AmazonS3FullAccess 3. AWSLambdaVPCExecutionRole

The VPC security group is the default one. VPC 安全组是默认的。

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.此外,当我尝试使用以下 AWS CLI 命令创建相同的存储桶时,它会创建存储桶。

aws s3api create-bucket --bucket psychology06 --region us-east-1

I am not sure, where am i making a mistake.我不确定,我在哪里犯了错误。

确保不存在同名的存储桶。如果可能,请共享日志。

You need to chain the .promise() method to your aws-sdk calls and await on them because you are creating async functions.您需要将.promise()方法链接到您的aws-sdk调用并await它们,因为您正在创建async函数。

await s3Client.createBucket(params).promise();
await s3Client.putObject(params1).promise();

Furthermore, S3 doesn't work with directories although you may be thrown over by the way the S3 console looks like when you add / to your filenames.此外,S3 不适用于目录,尽管当您将/添加到文件名时,您可能会被 S3 控制台的外观所迷惑。 You can read more about it here你可以在这里阅读更多关于它的信息

As you are new, always try aws cli(not recommended) and then search for search for equivalent sdk function while implementing.As it(your code) is async it won't wait until the call back function executes , so you can try something like below.(This is not actual solution , it just tells how to wait until the call back does it's work.)因为你是新手,总是尝试 aws cli(不推荐),然后在实现时搜索等效的 sdk 函数。由于它(你的代码)是异步的,它不会等到回调函数执行,所以你可以尝试一些东西如下所示。(这不是实际的解决方案,它只是告诉如何等待回调完成它的工作。)

    'use strict'

    var AWS = require('aws-sdk');
    AWS.config.region = 'us-east-1';
    var s3Client = new AWS.S3({ apiVersion: '2006-03-01' });

    exports.handler = async (event, context) => {
        let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body: 'body does not matter' };
        try {
            let obj = await something(params1);
            callback(null, obj);
        }
        catch (err) {
            callback('error', err)
        }
    }

    async function something(params1) {
        return new Promise(async (resolve, reject) => {
            await s3Client.putObject(params1, function (err, data) {
                if (err) {
                    console.log('Error creating the folder:', err);
                    reject('error during putObject');
                } else {
                    console.log('success' + JSON.stringify(data));
                    resolve('success');
                }
            });
        });
    }

To your question in the comments : Hi Vinit , let me give you little background , the question you have asked is very generic.对于您在评论中的问题:嗨,Vinit,让我给您介绍一些背景知识,您提出的问题非常笼统。 Firstly VPC is something which you create where you will have your organization private and public subnets that are used to run your ec2 or any hosted services (non-managed services by aws).首先,VPC 是您创建的东西,您将在其中拥有用于运行您的 ec2 或任何托管服务(aws 的非托管服务)的组织私有和公共子网。 But as lambda is managed service it runs in aws vpc , they usually take your code and lambda configurations and execute the code.Now coming to your question if we attach vpc in your lambda configurations ( only if your lambda needs to use services hosted in your vpc, else don't use it) then as we discussed lambda runs in aws vpc , so during cold start it created an ENI(think of it as elastic IP) and tries to communicate with your VPC.但是由于 lambda 是托管服务,它在 aws vpc 中运行,它们通常采用您的代码和 lambda 配置并执行代码。 vpc,否则不要使用它)然后正如我们讨论的 lambda 在 aws vpc 中运行,因此在冷启动期间它创建了一个 ENI(将其视为弹性 IP)并尝试与您的 VPC 通信。 Before Re-invent an ENI was created for each lambda that was the reason it takes time for the first time and lambda used to time out even though your execution takes lesser time.在重新发明之前,为每个 lambda 创建了一个 ENI,这是第一次需要时间的原因,而 lambda 曾经超时,即使您的执行时间较短。 Now after re-invent EIP's are created per subnet per security group.现在重新发明后,每个安全组的每个子网都创建了 EIP。 So now coming to your question when u have attached vpc, if lambda execution is taking more time or not working as expected, then you have to see how your vpc(configs, routes, subnets) is set up and it's very hard to answer as so many parameters are involved unless we debug.因此,当您附加 vpc 时,现在来回答您的问题,如果 lambda 执行需要更多时间或未按预期工作,那么您必须查看您的 vpc(configs、routes、subnets) 是如何设置的,并且很难回答除非我们调试,否则涉及这么多参数。 So short answer do not attach vpc if your function(code) does not need to talk to any of your own managed instances in vpc (usually private subnet ) etc.因此,如果您的函数(代码)不需要与您自己在 vpc 中的任何托管实例(通常是私有子网)等进行通信,请不要附加 vpc。

Since, you are using async functionality.因为,您正在使用异步功能。 Thus, you have to use await on calling "s3Client.createBucket".因此,您必须在调用“s3Client.createBucket”时使用 await。 Then resolve the received promise.然后解决收到的承诺。

For creating folders, use trailing "/".要创建文件夹,请使用尾随的“/”。 For example "pshycology06/travasko/".例如“pshycology06/travasko/”。

Do post error logs if these doesn't work.如果这些不起作用,请发布错误日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM