Automatically setting a bucket policy in AWS S3. How do I obtain the new buckets name for the script to refer to?

痞子三分冷 提交于 2020-07-10 06:27:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!