我正在寻找使用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中添加条目,然后将其作为新策略进行PUT,但我正在寻找允许用户在不知道退出策略的情况下更新策略的调用。
答案 0 :(得分:3)
我有类似的要求,即必须以编程方式修改存储桶和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()
答案 1 :(得分:1)
IAM未提供更新策略的方法,但未提供完整有效的策略作为替代。您需要执行PUT,传入原始策略名称。
答案 2 :(得分:0)
当前的boto3 API没有附加存储桶策略的功能,无论是否添加其他项/元素/属性。您需要自己加载和操作JSON。例如。 write script将策略加载到dict中,附加" Statement"元素列表,然后使用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)
用户在此过程中不需要知道旧政策。