AWS S3 刪除大量檔案

AWS S3 Bucket Lifecycle Permanently Delete

由於早期的專案有段時間是拿 AWS S3 來存放 access log,而且當初的設計是一筆 request 就會有一筆 log,導致 S3 裡面放了超多的細碎檔案,每個月單就儲存的費用就頗驚人,每個檔案又小於 256KB,如果到 Lifecycle 裡面設定 Archive to the Glacier Storage Class,AWS 會提示檔案太小放到 Glacier 可能費用會更高。

AWS S3 Glacier Transitioning Smaller Objects to Glacier May Increase Costs

最後只好把這一大批檔案備份出來後(又是另一筆費用),刪掉比較舊的,只保留某個時間點之後的檔案,但由於不是要整個 bucket 刪掉,且 bucket 裡面每個目錄都超過 20000 個檔案,從 AWS Console 裡面刪除時會跳提示說檔案太多請從 cli 刪除,試著透過
aws s3 rm s3://xxx --recursive
的方式來刪除檔案,aws cli 會一個個檔案慢慢刪,將近一億個檔案不知道要刪除到何年何月…

由於這些檔案具有時序特性,S3 又提供 Permanently Delete – N Days after the object’s creation date 的選項,就想到可以透過這個方式來刪除舊檔案,保留新的檔案,只要算好要清除的檔案是在多少天之前,設定進去,時間到後檔案舊檔案就會全部消失囉!

AWS S3 Bucket Lifecycle Permanently Delete

不知道有沒有更好的方法… XD

Leave a Reply

Your email address will not be published. Required fields are marked *