如何删除 Azure 存储帐户中具有创建日期的容器

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

我需要删除 Azure 存储帐户中创建日期超过 1 年的容器,因为我们每个月都会创建容器。

我厌倦了使用Azure存储生命周期管理,但我们无法删除容器,但我们可以删除内部文件。

有没有办法从 Azure / Terraform 中删除容器本身?

我想通过 terraform 自动删除突出显示的容器。

Azure 门户

enter image description here

azure terraform terraform-provider-azure terragrunt
1个回答
0
投票

使用 terraform 根据创建/修改时间删除存储帐户内的容器。

使用 terraform 无法直接实现上述要求,因为它不支持基于时间统计的功能。

为了实现这个要求,我们需要使用具有获取资源元数据信息权限的CLI命令。如果你仍然想使用 terraform 来实现这一点,你可以使用 null 资源。

最初我测试删除 2 天前的容器,如下所示

enter image description here

配置:

variable "resource_group_name" {
  description = "Resource group name"
  type        = string
  default     = "vinay-rg"
}

variable "storage_account_name" {
  description = "Storage account name"
  type        = string
  default     = "testsamoeksas"
}

resource "null_resource" "delete_old_containers" {
  provisioner "local-exec" {
    interpreter = ["/bin/bash", "-c"]
    command = <<EOT
      #!/bin/bash

      storageAccount="${var.storage_account_name}"
      cutoffDate=$(date -d '-2 days' +"%Y-%m-%dT%H:%M:%SZ")  # here is tried to set this for 2 days ago containerss

     
      delete_if_old() {
          local containerName=$1

          # Get the last modified date of the container
          lastModified=$(az storage container show \
              --name $containerName \
              --account-name $storageAccount \
              --auth-mode login \
              --query properties.lastModified \
              --output tsv)

          if [[ -z "$lastModified" ]]; then
              echo "Error: Could not retrieve the last modified date for container: $containerName"
              return
          fi

          
          lastModifiedEpoch=$(date -d "$lastModified" +%s)
          cutoffDateEpoch=$(date -d "$cutoffDate" +%s)

          # Compare lastModified date with the cutoff date (2 days ago)
          if [[ $lastModifiedEpoch -lt $cutoffDateEpoch ]]; then
              echo "Deleting container: $containerName (Last Modified: $lastModified)"
              az storage container delete \
                  --name $containerName \
                  --account-name $storageAccount \
                  --auth-mode login
          else
              echo "Skipping container: $containerName (Last Modified within the last 2 days)"
          fi
      }

      
      list=$(az storage container list \
          --query "[].name" \
          --account-name $storageAccount \
          --auth-mode login \
          --output tsv)

      for containerName in $list; do
          delete_if_old $containerName
      done
    EOT
  }
}

部署:

enter image description here

enter image description here

参考:

https://learn.microsoft.com/en-us/azure/storage/blobs/blob-containers-cli#delete-containers

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/storage_container

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