AZ CLI bash script to clean up Azure Image Gallery Versions

We do lots of testing and building with operating system images in Azure Shared Image Gallery. In a short period of time the number of image versions in Azure Image Gallery increases dramatically because of the iterative approach of testing and optimizing the golden images.

Azure Shared Image Gallery – Image Versions

From time to time we need to clean up those image versions to save storage costs.
Usually cleaning up is part of an automated process in a CI/CD pipeline run.

In bash scripts we often use azure cli command-line tool to fire off the task.
Before firing off the script make sure to use az login to login to Azure on the command line.

# this script deletes all gallery image versions 
# of a gallery image definition


for i in `az sig image-version list \
--gallery-image-definition $gallery-image-definition \
--gallery-name $gallery-name \
--resource-group $resource-group \
-o tsv \
--query '[].name'`
  echo "purging image-versions: $i" && \
  $(az sig image-version delete \
  --gallery-image-definition $gallery-image-definition \
  --gallery-image-version $i \
  --gallery-name $gallery-name \
  --resource-group $resource-group)