无法根据标签值获取S3存储桶名称

时间:2019-08-12 10:14:40

标签: python python-3.x amazon-s3

在我们的aws帐户中,我们有〜1000个S3存储桶,每个S3存储桶都有对应于应用程序名称的标签(例如,key = application,value = app1)。我正在尝试找出一个特定应用程序拥有多少个S3存储桶。因此,首先获得了所有S3存储桶的列表;然后遍历列表以匹配标签值“ app1”。它应该很简单,但是由于某种原因,它会给出“调用GetBucketTagging操作时出现AccessDenied”错误。我验证了IAM角色(假设我具有GetBucketTagging的权限)

1)使用凭据获得了s3存储桶的列表(我假设是IAM角色) 2)遍历列表,尝试匹配标签的键,值对(key = application,value = application1)

第一个选项

import boto3
client = boto3.client('s3')
buckets = client.list_buckets()['Buckets']
matching_buckets = []
# tag key and value to search for
tag_key = 'application'
tag_value = 'app1'
for bucket in buckets:
    tags = client.get_bucket_tagging(Bucket=bucket['Name'])['TagSet']

    for tag in tags:
        if tag['Key'] == tag_key and tag['Value'] == tag_value:
        matching_buckets.append(bucket['Name'])

第二个选项

import boto3
s3 = boto3.client('s3')
app = "app1"
bucketlist = s3.list_buckets()['Buckets']
print(len(bucketlist))
bucketname = []
n=0
#iterate thru the list of {Name, CreationDate} to get all the bucket names and append to empty list

def bucket_tagging_method(b,app):
    mybucketlist = []
    bucket_tagging = s3.get_bucket_tagging(Bucket=b)
    tag_set = bucket_tagging['TagSet']
    for tag in tag_set:
        if (tag['Key'] == "application") and (tag['Value'] == app) :
            mybucketlist.append(b)
            pass
    return(mybucketlist)


while n < len(bucketlist):
    d = bucketlist[n]
    bucketname.append(d['Name'])
    n+=1

for i in bucketname:
    print(bucket_tagging_method(i,app))

出现以下错误

tags = client.get_bucket_tagging(Bucket=bucket['Name'])['TagSet']
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the GetBucketTagging operation: Access Denied

1 个答案:

答案 0 :(得分:0)

Customer Model