我试图使用boto3检索来自所有区域的桶列表,但是我无法列出来自正确区域的桶
到目前为止,我已经尝试了location['LocationConstraint']
,它出现为None
我也试过下面的方法,但是没有成功。
任何帮助都是感激的,谢谢你
if client.head_bucket(Bucket=bucket['Name'])['ResponseMetadata']['HTTPHeaders']['x-amz-bucket-region'] == 'us-east-1':
print ("bucketname %s " % s3_bucket.name)
import json
import boto3
bucketlist = []
def lambda_handler(event, context):
# Get list of regions
ec2 = boto3.client('ec2')
regions = ec2.describe_regions().get('Regions',[] )
# Iterate over regions
for region in regions:
print ("*************** Checking region -- %s " % region['RegionName'])
reg=region['RegionName']
client = boto3.client('s3', region_name=reg)
response = client.list_buckets()
for bucket in response['Buckets']:
s3 = boto3.resource('s3', region_name=reg)
s3_bucket = s3.Bucket(bucket['Name'])
if client.head_bucket(Bucket=bucket['Name'])['ResponseMetadata']['HTTPHeaders']['x-amz-bucket-region'] == 'us-east-1':
print ("bucketname %s " % s3_bucket.name)
bucketlist.append(s3_bucket)
return {
"statusCode": 200
}
输出:testbucket1
和testbucket2
桶仅在us-east-1
区域可用
START RequestId: e22f6ac0-7bb9-4e2b-84d7-5512ce97acfa Version: $LATEST
*************** Checking region -- eu-north-1
bucketname testbucket1
bucketname testbucket2
*************** Checking region -- ap-south-1
bucketname testbucket1
bucketname testbucket2
[...]
*************** Checking region -- us-east-1
bucketname testbucket1
bucketname testbucket2
预期输出:
START RequestId: e22f6ac0-7bb9-4e2b-84d7-5512ce97acfa Version: $LATEST
*************** Checking region -- eu-north-1
*************** Checking region -- ap-south-1
*************** Checking region -- eu-west-3
*************** Checking region -- eu-west-2
*************** Checking region -- eu-west-1
*************** Checking region -- ap-northeast-3
*************** Checking region -- ap-northeast-2
*************** Checking region -- ap-northeast-1
*************** Checking region -- sa-east-1
*************** Checking region -- ca-central-1
*************** Checking region -- ap-southeast-1
*************** Checking region -- ap-southeast-2
*************** Checking region -- eu-central-1
*************** Checking region -- us-east-1
bucketname testbucket1
bucketname testbucket2
*************** Checking region -- us-east-2
*************** Checking region -- us-west-1
*************** Checking region -- us-west-2
您不必为客户端更改区域。list_buckets
返回所有bucket 在账户里,不管他们在哪里。这就是为什么您在代码中为每个区域获得相同的桶。
您必须迭代list_buckets
结果,并使用get_bucket_location来获取桶的实际位置。例如:
all_buckets = client.list_buckets()
for bucket in all_buckets['Buckets']:
bucket_bame = bucket["Name"]
region = client.get_bucket_location(Bucket=bucket_bame)["LocationConstraint"]
print(bucket_bame, region)