Scheduled clean-up of images stored on an ACR


Azure Container Registries don’t clear past images by default

When using the ‘basic’ SKU of Azure Container Registry the native ‘retention’ feature is not available, instead you need to use tasks which essentially just run a command on a schedule

To create a task you can do this directly from Terraform or via a powershell script:

Terraform -

module.tf

resource "azurerm_container_registry_task" "acr_purge_task" {
  name                  = var.acr_task_name
  container_registry_id = var.container_registry_id
  platform {
    os           = "Linux"
  }
  encoded_step {
    task_content = <<EOF
    version: v1.1.0
    steps:
      - cmd: az acr task create --name ${var.acr_task_name} --registry ${var.container_registry_id} --cmd ${var.acr_task_command} --schedule ${var.acr_task_schedule} --context /dev/null
        disableWorkingDirectoryOverride: true
        timeout: 3600
    EOF
  }
}

variables.tf

variable "acr_task_name" {
}

variable "container_registry_id" {
}

variable "acr_task_command" {
    default = "acr purge --filter '*:.*' --ago 0d --keep 2 --untagged"
    description = "--filter {image_name:version} --ago {image age} --keep {minimum images retained}"
}

variable "acr_task_schedule" {
    default = "0 6 * * *"
    description = "{minute} {hour} {day} {month} {day-of-week} - defaults to 06:00 every day"
}

Powershell

$acrName = ''
$taskName = 'purgetask'

$purgeCommand = "acr purge --filter '*:.*' --ago 0d --keep 2 --untagged"

# --schedule {minute} {hour} {day} {month} {day-of-week} | currently runs at 6:00 every day
az acr task create --name $taskName --registry $acrName --cmd $purgeCommand --schedule "0 6 * * *" --context /dev/null

# show tasks
# az acr task show --name $taskName --registry $acrName --output table

acr runs