通过 bicep 从 azure 存储帐户中删除 blob,但从开发分支中排除 blob

问题描述 投票:0回答:1

我们设置了存储帐户和天蓝色存储帐户生命周期管理策略,用于删除超过 100 天的 Blob 等。我们注意到,这一政策将删除所有 Blob,包括来自开发分支的 Blob。我们想要实现的目标是创建这样的策略,以便我们从开发分支中排除 blob,但从容器中删除所有其他 blob 文件。找不到任何相关示例来执行此操作。是的,azure 生命周期管理具有用于过滤目的的

prefixMatch
属性,但我们不能在这里使用否定规则。有没有人有更好的想法如何实现它以及一些好的例子(如果可能的话)。

这是我们的二头肌生命周期管理规则示例,目前如下所示:

resource storageAccountManagementPolicies 'Microsoft.Storage/storageAccounts/managementPolicies@2023-01-01'{
  name: 'Storage Account Name'
  properties: {
    policy: {
      rules: [
        {
          enabled: true
          name: 'Delete blobs'
          type: 'Lifecycle'
          definition: {
            actions: {
              baseBlob: {
                delete: {
                  daysAfterCreationGreaterThan: 100
                }
              }
            }
            filters: {
              blobTypes: [
                'blockBlob'
              ]
            }
          }
        }
      ]
    }
  }
}
azure azure-blob-storage azure-storage-account
1个回答
0
投票

通过 bicep 从 azure 存储帐户中删除 blob,但从开发分支中排除 blob

根据 Ramya Harinarthini_MSFT 的 MS-Q&A

在azure blob存储生命周期策略中,没有排除特定文件夹的功能。因此,无法使用 azure blob 生命周期策略。

您可以使用 python 代码删除特定日期内的 blob,并排除特定文件夹。

代码:

import datetime
from azure.storage.blob import BlobServiceClient


blob_service_client = BlobServiceClient.from_connection_string("DefaultEndpointsProtocol=https;AccountName=<storage account name>;AccountKey=<accountkey>;EndpointSuffix=core.windows.net")

# Define the container and the "test" prefix to exclude
container_name = "data"
excluded_prefix = "test/"
days_threshold = 5


container_client = blob_service_client.get_container_client(container_name)
blobs = container_client.list_blobs()

for blob in blobs:
    if blob.name.startswith(excluded_prefix):
        continue
    
    blob_creation_date = blob.creation_time
    blob_age = (datetime.datetime.now(datetime.timezone.utc) - blob_creation_date).days

    if blob_age > days_threshold:
        print(f"Deleting blob: {blob.name}")
        container_client.delete_blob(blob.name)

以上代码将排除

test
文件夹并删除超过 5 天的 blob 以进行测试。

输出:

Deleting blob: README.txt
Deleting blob: backup-2022-11-15-1430.zip.zip
Deleting blob: demo.pdf
Deleting blob: demo326.cer
Deleting blob: demo326.cer.thumbprint.txt
Deleting blob: demo326.key.txt
Deleting blob: demo326.pfx
Deleting blob: example.csv

enter image description here

您可以使用

Azure Automation
Azure function
通过自动化流程运行 Python 脚本。

© www.soinside.com 2019 - 2024. All rights reserved.