我有一个S3存储桶里面有很多文件。我想创建一个规则,在1天后删除所有以.pdf结尾的文件。
我能使用S3生命周期规则来实现吗?
因为我尝试过`*.pdf delete after 1 day`,但是没有起作用。
我还尝试过`copy_* delete after 1 day`,但也没有起作用。
我能使用S3生命周期规则来实现吗?
因为我尝试过`*.pdf delete after 1 day`,但是没有起作用。
我还尝试过`copy_* delete after 1 day`,但也没有起作用。
我也需要这样做。由于生命周期规则仍不支持基于后缀的规则,因此我编写了一个快速而简单的Python脚本来为我标记所有文件。该脚本甚至可以根据指定的任何后缀跨存储桶进行标记。
#!/usr/bin/env python3
import boto3
# Setup session. I use SSO so this may be slightly different for you if you don't.
boto3.setup_default_session(profile_name='your-profile-name')
# Connection to S3 Client
s3 = boto3.client('s3')
# If tagging a single bucket use this
bucket = 'your-bucket'
# Get all object keys. We need to specify keys in all later steps
response = s3.list_objects_v2(
Bucket= bucket,
Delimiter="\n"
)
# We are only interested in the metadata about the contents
response = response['Contents']
keys = [] # List of keys globally accessible
file_suffix = 'pdf'
for key in response:
if key.get('Key').endswith(file_suffix):
keys.append(key.get('Key'))
else:
print('no pdf files found')
exit()
for key in keys:
obj = s3.put_object_tagging(
Bucket=bucket,
Key=key,
Tagging={
'TagSet': [
{
'Key': 'file_type',
'Value': file_suffix
}
]
}
)
可能存在更高效的分隔符,请参见https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/list_objects_v2.html