S3 bucket policy using Boto3



我正在编写一个boto脚本来收集日志并将其存储到S3存储桶中,我收到了一个错误"botocore.errorfacactory.NoSuchBucket:调用PutBucketPolicy操作时发生错误(NoSuchBucket(:指定的bucket不存在"我事先把水桶装起来,然后试图把政策附加到水桶上,水桶也出现在控制台上。我不明白是什么原因导致了这个问题。

import boto3
import sys
import json
import time 
iam = boto3.client('iam')
sts = boto3.client('sts')
ec2 = boto3.resource('ec2')
cloudtrail = boto3.client('cloudtrail')
s3  = boto3.client('s3')

s3.create_bucket(Bucket='goodbucket3')
# Create a bucket policy
bucket_name = 'goodbucket3'
bucket_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": "s3:GetBucketAcl",
"Resource": f"arn:aws:s3:::{bucket_name}"
},
{
"Effect": "Allow",
"Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": 
"s3:PutObject",
"s3:PutObjectAcl"
"s3:GetObject"
"s3:GetObjectAcl"
"s3:DeleteObject"
"Resource": f"arn:aws:s3:::{bucket_name}/AWSLogs/XXXXXXXX/*",
"Condition": {"StringEquals": {"s3:x-amz-acl": "bucket-owner-full-control"}}
}
]
}
# Convert the policy from JSON dict to string
bucket_policy = json.dumps(bucket_policy)
# Set the new policy
s3.put_bucket_policy(Bucket='bucket_name', Policy=bucket_policy)
result = s3.get_bucket_policy(Bucket='bucket_name')
logs = cloudtrail.create_trail(
Name='GoodTrail',
S3BucketName='bucket_name',
)
print(logs)

您可能需要等待bucket创建完全传播。您可以使用waiter来执行此操作。请参阅底层客户端文档或boto3中的"如何使用服务员"。

使用客户端的get_waiter((方法,可以获得特定的服务生从可能的服务员名单中:

# Retrieve waiter instance that will wait till a specified bucket exists
s3_bucket_exists_waiter = s3.get_waiter('bucket_exists')

然后要真正开始等待,您必须调用服务员的wait((方法的适当参数传入:

# Begin waiting for the S3 bucket, mybucket, to exist
s3_bucket_exists_waiter.wait(Bucket='mybucket')

相关内容

  • 没有找到相关文章

最新更新