You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用户注册触发Lambda创建同名S3文件夹报错求助

Hey there! Let's fix those issues step by step—you're almost there, just a few tweaks needed.

First, let's break down why your current code isn't working:

  • You don't need to call list_users in Python to get the newly registered user's name. When Cognito triggers your Lambda after registration, the event object already contains the username (and other user details). Calling list_users would fetch all users in your pool, which isn't what you want here.
  • Your Python code has a syntax error with the if statement (you used curly braces like JavaScript instead of Python's colon and indentation).
  • In both Python and Node.js, you're hardcoding the folder name as 'userName' instead of using the actual username from the event.
  • For Node.js, you need to handle the async operation properly so Lambda doesn't exit before the S3 call finishes.

Python Fixed Code
import json
import boto3

def lambda_handler(event, context):
    # Get the username directly from the Cognito trigger event
    username = event['request']['userAttributes']['username']
    
    s3 = boto3.client('s3')
    bucket_name = "demoupload1"
    # S3 "folders" are just keys with a trailing slash
    folder_key = f"{username}/"
    
    try:
        s3.put_object(Bucket=bucket_name, Key=folder_key)
        print(f"Successfully created folder for user: {username}")
        return {
            'statusCode': 200,
            'body': json.dumps(f"Folder created for {username}")
        }
    except Exception as e:
        print(f"Error creating folder: {str(e)}")
        return {
            'statusCode': 500,
            'body': json.dumps(f"Failed to create folder: {str(e)}")
        }

Key Fixes:

  • Pulled the username straight from event['request']['userAttributes']['username']—this is the standard structure for Cognito post-registration triggers.
  • Used an f-string to create the folder key with a trailing slash (required for S3 to recognize it as a folder).
  • Added error handling with try/except to catch and log any issues.

Node.js Fixed Code
const AWS = require('aws-sdk');
const s3Client = new AWS.S3();

exports.handler = async (event) => {
    try {
        const username = event.request.userAttributes.username;
        const params = { 
            Bucket: 'demoupload1', 
            Key: `${username}/`,
            Body: '' // Required for upload, even if empty
        };
        
        await s3Client.upload(params).promise();
        console.log(`Successfully created folder for user: ${username}`);
        return {
            statusCode: 200,
            body: JSON.stringify(`Folder created for ${username}`)
        };
    } catch (err) {
        console.log("Error creating the folder: ", err);
        return {
            statusCode: 500,
            body: JSON.stringify(`Failed to create folder: ${err.message}`)
        };
    }
};

Key Fixes:

  • Switched to async/await for cleaner async handling (ensures Lambda waits for the S3 operation to finish before exiting).
  • Pulled the username from the event's request.userAttributes.username (same standard structure as Python).
  • Added an empty Body parameter—upload requires this, even for folders.
  • Added proper error handling with try/catch.

Critical Additional Setup
  • Lambda Execution Role: Make sure your Lambda's IAM role has permission to put objects in your S3 bucket. Add a policy like this to the role:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::demoupload1/*"
        }
    ]
}
  • Cognito Trigger Setup: Double-check that you've added this Lambda as a Post Confirmation trigger in your Cognito User Pool. That's how the event with the username gets sent to Lambda after registration.

内容的提问来源于stack exchange,提问作者AMAN MAKWANA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:32:31