Boto3 get only S3 buckets of specific region

安稳与你 提交于 2020-02-03 10:11:46

问题


The following code sadly lists all buckets of all regions and not only from "eu-west-1" as specified. How can I change that?

import boto3

s3 = boto3.client("s3", region_name="eu-west-1")

for bucket in s3.list_buckets()["Buckets"]:

    bucket_name = bucket["Name"]
    print(bucket["Name"])

回答1:


s3 = boto3.client("s3", region_name="eu-west-1")

connects to S3 API endpoint in eu-west-1. It doesn't limit the listing to eu-west-1 buckets. One solution is to query the bucket location and filter.

s3 = boto3.client("s3")

for bucket in s3.list_buckets()["Buckets"]:
    if s3.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint'] == 'eu-west-1':
        print(bucket["Name"])

If you need a one liner using Python's list comprehension:

region_buckets = [bucket["Name"] for bucket in s3.list_buckets()["Buckets"] if s3.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint'] == 'eu-west-1']
print(region_buckets)


来源:https://stackoverflow.com/questions/49814173/boto3-get-only-s3-buckets-of-specific-region

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