问题
This script requires the name of the new bucket in order to be attached. However, it would not receive the name of the new S3 bucket to be referred to in the script. What way can I obtain the name of the new bucket automatically in this script?
import json
# Create a bucket policy
bucket_name = 'BUCKET_NAME'
bucket_policy = {
'Version': '2012-10-17',
'Statement': [{
'Sid': 'AddPerm',
'Effect': 'Allow',
'Principal': '*',
'Action': ['s3:GetObject'],
'Resource': f'arn:aws:s3:::{bucket_name}/*'
}]
}
# Convert the policy from JSON dict to string
bucket_policy = json.dumps(bucket_policy)
# Set the new policy
s3 = boto3.client('s3')
s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy)
This is from the boto3 documentation. I need the bucket_name
to be replaced with the name of the new bucket automatically for this script to attach the policy. Any ideas are greatly appreciated.
回答1:
From the comments I take that you have a Lambda function triggered by the s3:CreateObject
event. In this case you can retrieve the bucket name directly from the event. This is what your handler could look like:
import boto3
import json
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Get bucket name from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
# Create a bucket policy
bucket_policy = json.dumps({
'Version': '2012-10-17',
'Statement': [{
'Sid': 'AddPerm',
'Effect': 'Allow',
'Principal': '*',
'Action': ['s3:GetObject'],
'Resource': f"arn:aws:s3:::{bucket_name}/*"
}]
})
# Set the new policy
s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy)
If you need more information from the event, refer to the S3 event message structure documentation.
来源:https://stackoverflow.com/questions/62763858/automatically-setting-a-bucket-policy-in-aws-s3-how-do-i-obtain-the-new-buckets