【问题标题】:Amazon S3 modify bucket policy using boto/boto3Amazon S3 使用 boto/boto3 修改存储桶策略
【发布时间】:2025-12-22 02:10:05
【问题描述】:

我正在寻找使用 boto/boto3 修改 S3 存储桶策略。我在boto3中发现了两种模式,通过它我们可以对桶策略进行操作。

# i can get bucket policy object as follows
import boto3
s3_conn = boto3.resource('s3')
bucket_policy = s3_conn.BucketPolicy('bucket_name')
# i can make put(), load(), policy on bucket_policy object.

#similar in other way i can use following code
policy = s3_conn.get_bucket_policy(Bucket='bucket_name')
# similar to this there are two other calls put_bucket_policy and delete_bucket_policy.

我正在寻找可以添加更多属性的更新存储桶策略。

例如。我想在以下策略的 Statement 键下再添加一个条目。

{
    "Version": "2012-10-17",
    "Id": "Policy14564645656",
    "Statement": [{
        "Sid": "Stmt1445654645618",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::6164563645030:root"
        },
        "Action": "s3:Get*",
        "Resource": "arn:aws:s3:::bucket_name/abc/*"
    }]
}

有没有直接的方法可以做到这一点。一种非常奇怪的方法是在 JSON 中添加条目,然后将其作为新策略放置,但我正在寻找允许用户在不知道退出策略的情况下更新策略的调用。

【问题讨论】:

    标签: amazon-web-services amazon-s3 boto boto3


    【解决方案1】:

    当前 boto3 API 没有附加存储桶策略的功能,是否添加其他项目/元素/属性。您需要自己加载和操作 JSON。例如。编写脚本将策略加载到字典中,附加“语句”元素列表,然后使用 policy.put 替换整个策略。如果没有原始语句 ID,将附加用户策略。但是,无法判断以后的用户策略是否会覆盖先前的规则。

    例如

    import boto3
    s3_resource = boto3.resource('s3')
    bucket_policy = s3_resource.BucketPolicy('bucket_name')
    
    # Or use client to get Bucket policy
    s3_client = boto3.client('s3')
    policy = s3_client.get_bucket_policy(Bucket='bucket_name')
    
    # assign policy using s3 resource 
    user_policy = { "Effect": "Allow",... } 
    new_policy =  policy['Statement'].append(user_policy)
    bucket_policy.put(Policy=new_policy) 
    

    用户在这个过程中不需要知道旧的策略。

    【讨论】:

    • 你需要一个 Client() 来调用 get_bucket_policy。
    【解决方案2】:

    我有类似的要求,必须以编程方式修改存储桶和 KMS 策略。我想出了自己的课程,将政策和声明视为对象。它包含在一个 pip 包“awspolicy”中 - https://github.com/totoleon/AwsPolicy

    我希望它可以帮助。快速示例:

    import boto3
    from awspolicy import BucketPolicy
    
    s3_client = boto3.client('s3')
    bucket_name = 'hailong-python'
    
    # Load the bucket policy as an object
    bucket_policy = BucketPolicy(serviceModule=s3_client, resourceIdentifer=bucket_name)
    
    # Select the statement that will be modified
    statement_to_modify = bucket_policy.select_statement('AutomatedRestrictiveAccess')
    
    # Insert new_user_arn into the list of Principal['AWS']
    new_user_arn = 'arn:aws:iam::888888888888:user/daniel'
    statement_to_modify.Principal['AWS'].append(new_user_arn)
    
    # Save change of the statement
    statement_to_modify.save()
    
    # Save change of the policy. This will update the bucket policy
    statement_to_modify.source_policy.save() # Or bucket_policy.save()
    

    【讨论】:

      【解决方案3】:

      如果不提供完整的有效策略作为替代,IAM 不会提供更新策略的方法。您需要执行 PUT,并传入原始策略名称。

      【讨论】: