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

请求协助:创建AWS Lambda实现S3桶创建时写入DynamoDB条目

Got it, let's break down exactly how to build this solution—automatically logging new S3 buckets to a DynamoDB table using Lambda. Here's a step-by-step guide that's easy to follow:

Step 1: Create Your DynamoDB Table

First, you need a place to store the bucket details. Let's set up a basic table:

  • Head to the DynamoDB console and create a new table.
  • Name it something like S3BucketInventory (you can adjust this, just remember it for later).
  • Set the partition key to bucketName with a type of String—since S3 bucket names are globally unique, this works perfectly as a primary key.
  • Leave all other settings at their defaults and finish creating the table.
Step 2: Build the Lambda Function

Next, create the Lambda function that will handle the event and write to DynamoDB. We'll use Python here (it's the most common choice for quick AWS automation):

  1. Go to the Lambda console, create a new function, and choose "Author from scratch".
  2. Name your function (e.g., LogNewS3BucketsToDynamoDB), select Python 3.x as the runtime, and create a new execution role (we'll tweak permissions later).
  3. Replace the default code with this:
import boto3
import logging

# Set up basic logging to track what's happening
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# Initialize DynamoDB resource (replace the table name with yours!)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('S3BucketInventory')

def lambda_handler(event, context):
    try:
        # Pull the bucket name and creation time from the incoming event
        bucket_name = event['detail']['requestParameters']['bucketName']
        creation_time = event['detail']['eventTime']
        
        # Write the bucket info to DynamoDB—we use a condition to avoid duplicate entries
        table.put_item(
            Item={
                'bucketName': bucket_name,
                'creationTime': creation_time,
                'status': 'Active'
            },
            ConditionExpression='attribute_not_exists(bucketName)'
        )
        
        logger.info(f"Successfully logged bucket: {bucket_name}")
        return {
            'statusCode': 200,
            'body': f"Bucket {bucket_name} added to inventory"
        }
    
    except Exception as e:
        logger.error(f"Failed to process event: {str(e)}")
        return {
            'statusCode': 500,
            'body': f"Error: {str(e)}"
        }
  1. Save the function.
Step 3: Set Up the EventBridge Trigger

S3 doesn't send direct triggers for bucket creation—instead, we use EventBridge (formerly CloudWatch Events) to catch the CreateBucket API call via CloudTrail:

  1. In your Lambda function's console, go to the "Configuration" tab and select "Triggers".
  2. Click "Add trigger", choose "EventBridge (CloudWatch Events)", then select "Create a new rule".
  3. Name the rule (e.g., S3BucketCreationRule), set the rule type to "Event pattern".
  4. Under "Event pattern", choose "Custom pattern" and paste this JSON:
{
  "source": ["aws.s3"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": ["s3.amazonaws.com"],
    "eventName": ["CreateBucket"]
  }
}
  1. Save the trigger—this tells EventBridge to send every CreateBucket event to your Lambda function.
Step 4: Fix Permissions (Critical!)

Lambda needs two key permissions to work:

  1. Write access to DynamoDB:
    • Go to the IAM console, find the execution role you created for your Lambda function.
    • Attach a new inline policy with this JSON (replace REGION, ACCOUNT_ID, and your table name):
      {
          "Version": "2012-10-17",
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": "dynamodb:PutItem",
                  "Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/S3BucketInventory"
              }
          ]
      }
      
  2. CloudTrail must be enabled:
    • EventBridge relies on CloudTrail to log S3 API calls. Make sure CloudTrail is enabled in your AWS account and region, and that it's set to log S3 events.
    • You can check this in the CloudTrail console—look for a trail that includes S3 in its data events.
Step 5: Test It Out

Now let's verify everything works:

  1. Create a new S3 bucket in your AWS account.
  2. Go back to your Lambda function, check the "Monitor" tab, then click "Logs" to view CloudWatch logs. You should see a log entry saying the bucket was successfully logged.
  3. Open your DynamoDB table, go to "Explore table items"—you'll see a new entry with the bucket name, creation time, and status.
Troubleshooting Tips
  • If nothing shows up in DynamoDB: Double-check that CloudTrail is enabled, and that your EventBridge rule is correctly targeting the CreateBucket event.
  • Duplicate entries: The ConditionExpression in the Lambda code prevents this, but if you see duplicates, make sure the rule isn't triggering multiple times (check EventBridge metrics).
  • Permission errors: Look at Lambda's CloudWatch logs for AccessDenied messages—this means your IAM role is missing a necessary permission.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:54:42