使用Azure Blob存储,是否可以像Amazon AWS S3的对象过期功能一样,在特定时间后删除单个Blob或容器内的所有Blob?或者Azure存储不提供这样的功能?
使用Azure Blob存储,是否可以像Amazon AWS S3的对象过期功能一样,在特定时间后删除单个Blob或容器内的所有Blob?或者Azure存储不提供这样的功能?
因为我错过了这个功能好多年,所以我写了一个小项目,并加入了一个漂亮的'Deploy to Azure button'。虽然还不完美,但是可以使用。https://github.com/nulllogicone/ExpireBlobFunction
现在我发现Microsoft已经在2019年3月27日将此作为新功能发布。
以下是文章中的摘录:
Azure Blob存储生命周期管理为GPv2和Blob存储帐户提供丰富的基于规则的策略。 使用策略将数据转换为适当的访问层或在数据生命周期结束时过期。
生命周期管理策略可让您执行以下操作:
- 将Blob转换为更冷的存储层(热到低温、热到归档或低温到归档),以优化性能和成本
- 删除Blob在其生命周期结束时
- 定义每天在存储帐户级别运行一次的规则 将规则应用于容器或一组blob(使用前缀作为过滤器)
是的,这是可能的。参考以下两个链接,这些示例代码并不好找。
Python 示例代码参考:https://github.com/Azure-Samples/azure-samples-python-management/blob/master/samples/storage/manage_management_policy.py
我使用的代码片段:
def add_expiry_rule(self):
token_credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret,
)
storage_client = StorageManagementClient(
credential=token_credential, subscription_id=subscription_id
)
rule = {
"id": "test",
"prefix": "test/",
"expiration": 91,
}
azure_rule = {
"enabled": True,
"name": rule.get("id"),
"type": "Lifecycle",
"definition": {
"filters": {"blob_types": ["blockBlob"], "prefix_match": [rule.get("prefix")]},
"actions": {
"base_blob": {
"delete": {
"days_after_modification_greater_than": str(rule.get("expiration"))
}
}
},
},
}
try:
management_policy = storage_client.management_policies.get(
group_name, storage_account, "default"
)
existing_rules = management_policy.policy.as_dict()
existing_rules.get("rules").append(azure_rule)
management_policy_rules = existing_rules
except Exception as e:
management_policy_rules = {"rules": [azure_rule]}
try:
management_policy = storage_client.management_policies.create_or_update(
group_name,
storage_account,
"default",
{"policy": management_policy_rules},
)
print("Azure: Added rule {} successfully".format(rule.get("id")))
except Exception as e:
if e.message.endswith("conflicting rule name."):
print("Azure: Rule ID: {} exists".format(rule.get("id")))
else:
raise Exception("Azure: Error adding rule. {}".format(e.message))