2013-02-19 52 views
10

我試圖找出一種方法來清理我的S3桶。我想刪除所有超過X天的密鑰(在我的情況下,X是30天)。S3使用boto的對象過期

我找不出一種方法來刪除s3中的對象。我使用了以下方法,其中沒有一個能夠工作(通過工作,我的意思是我在X天后嘗試獲取對象,並且s3仍在服務該對象。我期待「找不到對象」或「對象已過期」消息

方法1:

k = Key(bucket) 
    k.key = my_key_name 
    expires = datetime.utcnow() + timedelta(seconds=(10)) 
    expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT") 
    k.set_contents_from_filename(filename,headers={'Expires':expires}) 

方法2:

k = Key(bucket) 
    k.key = "Event_" + str(key_name) + "_report" 
    expires = datetime.utcnow() + timedelta(seconds=(10)) 
    expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT") 
    k.set_meta_data('Expires', expires) 
    k.set_contents_from_filename(filename) 

如果任何人都可以分享這是爲他們工作的代碼,它刪除S3對象,這將非常好

回答

12

您可以使用lifecycle policies從s3中刪除 比X天更舊的對象。例如,假設你有這些 對象:

logs/first 
logs/second 
logs/third 
otherfile.txt 

到期下日誌一切/ 30天之後,你會說:

import boto 
from boto.s3.lifecycle import (
    Lifecycle, 
    Expiration, 
) 

lifecycle = Lifecycle() 
lifecycle.add_rule(
    'rulename', 
    prefix='logs/', 
    status='Enabled', 
    expiration=Expiration(days=30) 
) 

s3 = boto.connect_s3() 
bucket = s3.get_bucket('boto-lifecycle-test') 
bucket.configure_lifecycle(lifecycle) 

您也可以檢索生命週期配置:

>>> config = bucket.get_lifecycle_config() 
>>> print(config[0]) 
<Rule: ruleid> 
>>> print(config[0].prefix) 
logs/ 
>>> print(config[0].expiration) 
<Expiration: in: 30 days> 
+0

我是想測試這一點,並想知道如果到期可以用分/秒進行測試檢查。 看起來像days = 1是可以使用的最短時間 – user2005798 2013-02-22 21:23:08

+0

沒有辦法使用分鐘/秒。最低限度爲0天,唯一的保證是AWS根據[PUT Bucket生命週期](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html)在次日午夜UTC之前採取行動。 。 – MeSee 2013-08-20 05:09:01

+0

請將LifeCycle更改爲「from boto.s3.lifecycle import LifeCycle」中的生命週期,因爲Lifecycle是正確的類名稱。 – AliBZ 2013-08-31 00:03:40

0

回答jamesis正在使用boto這是舊版本,將被棄用。 當前支持的版本是boto3

import boto3 
from botocore.exceptions import ClientError 

client = boto3.client('s3') 
try: 
    policy_status = client.put_bucket_lifecycle_configuration(
       Bucket='boto-lifecycle-test', 
       LifecycleConfiguration={ 
        'Rules': 
          [ 
          { 
          'Expiration': 
           { 
           'Days': 30, 
           'ExpiredObjectDeleteMarker': True 
           }, 
          'Prefix': 'logs/', 
          'Filter': { 
           'Prefix': 'logs/', 
          }, 
          'Status': 'Enabled', 
          } 
         ]}) 
except ClientError as e: 
    print("Unable to apply bucket policy. \nReason:{0}".format(e)) 

這將覆蓋在logs任何現有的生命週期配置策略:

上的日誌文件夾相同的到期策略可以如下進行。

一個很好的事情是檢查如果桶存在,如果你有申請前的try-except

bucket_exists = client.head_bucket(
    Bucket='boto-lifecycle-test' 
) 

即到期構造。由於logs文件夾之前訪問它的權限本身ISN」 t存儲桶而是存儲桶boto-lifecycletest內的對象時,存儲桶本身可以有不同的過期策略。 您可以從以下policy_exists的結果中進行檢查。

policy_exists = client.get_bucket_lifecycle_configuration(
    Bucket='boto-lifecycle-test') 
bucket_policy = policy_exists['Rules'][0]['Expiration'] 

有關設置過期策略的更多信息,Expiry policy

相關問題