AWS S3 cli - tag all objects within a directory
Calvin Duy Canh Tran 's answer might return error for filename with spaces, in the command below, I added an -I flag for xargs
to replace the argument "targetobject" with standard input.
aws s3api list-objects --bucket mybucket --query 'Contents[].{Key:Key}' --prefix testfolder/ --output text | xargs -n 1 -I targetobject aws s3api put-object-tagging --bucket mybucket --tagging 'TagSet=[{Key=colour,Value=blue}]' --key targetobject
There is no concept of a directory in S3. Here is a crude way of achieving what you want. Other posters may have a better solution. The following solution first gets all the objects in the folder and then calls put-object-tagging
for each one of them. Note: I didn't test this solution.
aws s3api list-objects --bucket mybucket --query 'Contents[].{Key:Key}'
--output text | grep foo/bar/ | xargs aws s3api put-object-tagging
--bucket mybucket --tagging 'TagSet=[{Key=colour,Value=blue}]' --key
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:
- List all the object in prefix of bucket and output to text
- Use
xargs -n 1
to loop each of the result and tag it.