Tag an S3 Bucket with AWS CLI

avatar

Borislav Hadzhiev

Thu Sep 16 20212 min read

banner

Photo by Anatol Lem

Tagging S3 Buckets with AWS CLI #

To tag an S3 bucket with the AWS CLI, run the put-bucket-tagging command, passing in the tag key-value pairs.

shell
aws s3api put-bucket-tagging --bucket your_bucket --tagging "TagSet=[{Key=department, Value=accounting}]"

create bucket tag

The command creates a tag with the key of department and value - accounting.

The put-bucket-tagging command deletes any tags the S3 bucket previously had, before it creates the new tags.

To verify the S3 bucket got successfully tagged, run the get-bucket-tagging command:

shell
aws s3api get-bucket-tagging --bucket your_bucket

verify bucket tagged

To create multiple tags on the bucket, pass multiple key-value pairs to the --tagging parameter:

shell
aws s3api put-bucket-tagging --bucket your_bucket --tagging "TagSet=[{Key=department, Value=accounting}, {Key=food, Value=cake}]"

create multiple bucket tags

To verify the tags got created successfully, run the get-bucket-tagging command again:

shell
aws s3api get-bucket-tagging --bucket your_bucket

verify multiple tags created

An alternative to passing the tag key-value pairs directly in the --tagging parameter is to store the tag values in a file and pass the file to the put-bucket-tagging command.

Create a file called bucket-tags.json with the following contents:

bucket-tags.json
{ "TagSet": [ { "Key": "color", "Value": "green" }, { "Key": "fruit", "Value": "avocado" } ] }

Open your terminal in the directory where you stored the bucket-tags.json file and run the put-bucket-tagging command pointing to the file:

shell
aws s3api put-bucket-tagging --bucket your_bucket --tagging file://bucket-tags.json

create tag from file

When we list the tags for the bucket, we can see that the tags from the file have been created:

list bucket tags

To delete all of the tags of an S3 bucket, run the delete-bucket-tagging command:

shell
aws s3api delete-bucket-tagging --bucket your_bucket

delete bucket tags

Note that running the get-bucket-tagging command on a bucket that has no tags, throws an error - "The TagSet does not exist":

tagset does not exist

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee