Oren
Oren

Reputation: 85

Getting files' tag in AWS S3 bucket

I have a bucket in AWS S3. Lets call it MY_BUCKET.

I would like to iterate the files in this bucket (with Python) and get the tags keys and values.

How do I do it?

Upvotes: 1

Views: 2679

Answers (2)

Srividya
Srividya

Reputation: 61

Code to get tags :

s3_resource = boto3.resource('s3')
client = boto3.client('s3')
bucket = s3_resource.Bucket("MY_BUCKET")

for name in bucket.objects.all() :
    response = client.get_object_tagging (
        Bucket = bucket.name,
        Key = name.key
)
print(name.key, response["TagSet"], sep = "\t")

First, it retrieves all objects of the bucket using bucket.objects.all() and for each object, call get_object_tagging which returns dictionary which contains Tagset of the object.

Thanks, Hope it helps !!

Upvotes: 2

John Rotenstein
John Rotenstein

Reputation: 269480

Your code would:

  • Use list_objects_v2() to obtain a list of the objects in the bucket
  • For each object, call head_object(), which returns metadata
  • Parse metadata for the tags

The above functions use the client method of calling S3. You could probably do it with the resource method too if that is your preference.

Upvotes: 1

Related Questions