How to add tags to an S3 Bucket without deleting the existing tags using AWS CLI?

Viewed 831

I am using this function: aws s3api put-bucket-tagging --bucket $bucket --tagging 'TagSet=[{Key=ss,Value=mm}]

It is deleting the existing tags and I can see only one tag.

1 Answers

That is how the API works, yes - that is how PUT APIs work in general, POST APIs may append a new tag or add a new property, etc. but PUT APIs overwrite.

To get this to work despite that you need to retrieve all tags, combine them with the new tags, and then put all tags at once. You can do that easily using e.g. jq:

# assuming there are already tags otherwise the get-bucket-tagging fails
data=$(aws s3api get-bucket-tagging --bucket $bucket | jq '.TagSet += [{"Key":"tag2", "Value": "value2"}]')
aws s3api put-bucket-tagging --bucket $bucket --tagging $data
aws s3api get-bucket-tagging --bucket $bucket # should print the merged tags
Related