Created
December 5, 2022 16:04
-
-
Save asbiin/faaf3b4d612bdc37ab6fbebac594934f to your computer and use it in GitHub Desktop.
Azure Container Registry cleaning script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| param( | |
| [parameter(Mandatory=$true)] [String] $SubscriptionID, | |
| [parameter(Mandatory=$true)] [string] $RegistryName, | |
| [parameter(Mandatory=$true)] [int] $DelayInDays = "30", | |
| [parameter()] [string] $ExcludedRepositories = "", | |
| [parameter()] [string] $ExcludedTags = "*/latest", | |
| [switch] $WhatIf | |
| ) | |
| $ExcludedRepositories = $ExcludedRepositories -split ',' | |
| $ExcludedTags = $ExcludedTags -split ',' | |
| $ErrorActionPreference = 'stop' | |
| function Login([string] $Subscription) { | |
| # Ensures you do not inherit an AzContext in your runbook | |
| Disable-AzContextAutosave -Scope Process | Out-Null | |
| # Connect using a Managed Service Identity | |
| try { | |
| $AzureContext = (Connect-AzAccount -Identity).context | |
| Write-Output "Successfully connected with Automation account's Managed Identity" | |
| } catch { | |
| Write-Output "There is no system-assigned user identity. Aborting."; | |
| exit 1 | |
| } | |
| # set context | |
| $AzureContext = Set-AzContext -Subscription $Subscription -DefaultProfile $AzureContext.context | |
| Write-Output "Connected to subscription $($AzureContext.Subscription.Name)" | |
| } | |
| Login -Subscription $SubscriptionID | |
| # Get current date minus DelayInDays | |
| $cutoffDate = (Get-Date).AddDays($DelayInDays * -1).Date | |
| Write-Output "Start cleaning registry $RegistryName" | |
| Get-AzContainerRegistryRepository -RegistryName $RegistryName | Where-Object { | |
| $_ -notin $ExcludedRepositories | |
| } | ForEach-Object { | |
| $repository = $_ | |
| Write-Output "Repository ${repository}:" | |
| $tags = (Get-AzContainerRegistryTag -RegistryName $RegistryName -RepositoryName $repository).Tags | |
| $tags | Where-Object { | |
| $tag = $_.Name | |
| $testTags = $true | |
| $ExcludedTags | ForEach-Object { | |
| $testTags = $testTags -and "$repository/$tag" -NotLike $_ | |
| } | |
| $testTags -and ([DateTime] $_.LastUpdateTime) -lt $cutoffDate | |
| } ` | |
| | Sort-Object -Property LastUpdateTime -Descending ` | |
| | Select-Object -Skip 1 ` | |
| | ForEach-Object { | |
| Write-Output "Deleting tag $($_.Name) from repository $repository" | |
| Remove-AzContainerRegistryTag -RegistryName $RegistryName -RepositoryName $repository -Name $_.Name -WhatIf:$WhatIf | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment