请求协助:创建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:
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
bucketNamewith a type ofString—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.
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):
- Go to the Lambda console, create a new function, and choose "Author from scratch".
- Name your function (e.g.,
LogNewS3BucketsToDynamoDB), select Python 3.x as the runtime, and create a new execution role (we'll tweak permissions later). - 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)}" }
- Save the function.
S3 doesn't send direct triggers for bucket creation—instead, we use EventBridge (formerly CloudWatch Events) to catch the CreateBucket API call via CloudTrail:
- In your Lambda function's console, go to the "Configuration" tab and select "Triggers".
- Click "Add trigger", choose "EventBridge (CloudWatch Events)", then select "Create a new rule".
- Name the rule (e.g.,
S3BucketCreationRule), set the rule type to "Event pattern". - 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"] } }
- Save the trigger—this tells EventBridge to send every
CreateBucketevent to your Lambda function.
Lambda needs two key permissions to work:
- 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" } ] }
- 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.
Now let's verify everything works:
- Create a new S3 bucket in your AWS account.
- 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.
- Open your DynamoDB table, go to "Explore table items"—you'll see a new entry with the bucket name, creation time, and status.
- If nothing shows up in DynamoDB: Double-check that CloudTrail is enabled, and that your EventBridge rule is correctly targeting the
CreateBucketevent. - Duplicate entries: The
ConditionExpressionin 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
AccessDeniedmessages—this means your IAM role is missing a necessary permission.
内容的提问来源于stack exchange,提问作者Pradeep

