Reputation: 2156
I have a file stored in AWS S3 which has a tag of the 'retention' type set to '1d'. The following example command will show this:
aws s3api get-object-tagging --bucket my-bucket --key "directory/subdirectory/My Test File.xlsx"
{
"VersionId": "3KD8GJ4NDNVJFJ4Jjfj4j",
"TagSet": [
{
"Value": "1d",
"Key": "Retention"
}
]
}
I wish to remove this tag, but only this tag. In the case where there is a file with two tags within the Tag Set, I don't want both to be removed -- just the Retention tag.
I've researched the delete-object-tagging documentation, which seems to indicate you can remove a Tag Set entirely -- but not a specific tag.
Upvotes: 2
Views: 2216
Reputation: 441
I have a python script which can achieve this use the boto3 library.
import boto3
from botocore.exceptions import ClientError
aws_session = boto3.session.Session(profile_name='default')
s3_resource = aws_session.resource('s3')
def delete_bucket_name_tag_to_all_buckets():
TAG_NAME = 'Retention'
for s3_bucket in s3_resource.buckets.all():
s3_bucket_name = s3_bucket.name
print(f'Deleting tag "{TAG_NAME}" in "{s3_bucket_name}" to "{s3_bucket_name}"...')
# catch tag error if there are no tags at all
bucket_tagging = s3_resource.BucketTagging(s3_bucket_name)
try:
tags = bucket_tagging.tag_set # This throws if there are no tags
except ClientError:
print(f'No tag "{TAG_NAME}" in "{s3_bucket_name}", we are good...')
saved_tags = [x for x in tags if x['Key'] != TAG_NAME]
bucket_tagging.delete()
bucket_tagging.put(Tagging={'TagSet':saved_tags})
if __name__ == '__main__':
delete_bucket_name_tag_to_all_buckets()
Hope it is helpful to you.
Upvotes: 1
Reputation: 1148
I don't think there's a function to delete a specific tag out of the box. However, I did a workaround for this some time back.
1.List the tags of the bucket via boto3 get_bucket_tagging
2.Delete the entire tag set of the bucket bucket_tagging.delete
3.Filter out the unwanted tag (Retention in your case) and reattach the rest
Hope this helps.
Upvotes: 3