Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS S3 cli - tag all objects within a directory

Is there a way to apply a tag (or set of tags) to all objects in an S3 directory using one single put-object-tagging cli command?

I.e if I have two files (test0.txt, test.txt) I can do the run the following two commands:

>aws s3api put-object-tagging --bucket mybucket --key foo/bar/test0.txt --tagging 'TagSet=[{Key=colour,Value=blue}]'
>aws s3api put-object-tagging --bucket mybucket --key foo/bar/test1.txt --tagging 'TagSet=[{Key=colour,Value=blue}]'

When trying to pass the folder itself as the --key option I get the following error (as it must reference a single object):

>aws s3api put-object-tagging --bucket mybucket --key foo/bar/ --tagging 'TagSet=[{Key=colour,Value=blue}]
An error occurred (NoSuchKey) when calling the PutObjectTagging operation: The specified key does not exist.

Is there a workaround for this?

like image 252
fez Avatar asked Aug 14 '17 14:08

fez


1 Answers

helloV's answer is corrected (have tested it) but it's not a good solution if the bucket is big, aws will take time to scan the whole bucket. Here is my solution

aws s3api list-objects --bucket mybucket --query 'Contents[].{Key:Key}' --prefix foo/bar --output text | xargs -n 1 aws s3api put-object-tagging  --bucket mybucket --tagging 'TagSet=[{Key=colour,Value=blue}]' --key

The command has 2 parts:

  1. List all the object in prefix of bucket and output to text
  2. Use xargs -n 1 to loop each of the result and tag it.
like image 182
Calvin Duy Canh Tran Avatar answered Sep 19 '22 13:09

Calvin Duy Canh Tran