Cleanup outdated artifacts in Artifactory
The below script can be used to cleanup outdated artifacts in Artifactory. It uses REST API to scan and delete items by age. Make sure you use Powershell 5.
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
# | |
# CleanupArtifacts.ps1 | |
# Cleans up Artifactory repository from old artifacts. | |
# Requires Powershell 5 because of the bug with Invoke-RestMethod in PS 3,4! | |
# | |
param([Parameter(Mandatory=$true)]$artifactoryUrl, [Parameter(Mandatory=$true)]$authorization, [Parameter(Mandatory=$true)]$repo, [Parameter(Mandatory=$true)]$path, [Parameter(Mandatory=$true)]$lifetime) | |
$ErrorActionPreference = "Stop" | |
trap | |
{ | |
Write-Host $_ | |
exit 1 | |
} | |
$headers = @{Authorization = "Basic $authorization" } | |
$criteria = @{ | |
"repo" = @{"`$eq" = $repo} | |
"path" = @{"`$match" = $path} | |
"created" = @{"`$lt" = (get-date).AddDays(-$lifetime).ToString("yyyy-MM-dd")} | |
} | |
$query = 'items.find(' + ($criteria | ConvertTo-Json) + ')'; | |
Write-Host Requesting a list of outdated artifacts in $repo/$path | |
$expiredItems = Invoke-RestMethod -Uri "$artifactoryUrl/api/search/aql" -Headers $headers -Method Post -Body $query | |
Write-Host Found $expiredItems.results.Count outdated artifacts | |
Write-Host Deleting outdated artifacts | |
foreach ($artifact in $expiredItems.results) { | |
$artifactPath = $($artifact.repo + "/" + $artifact.path + "/" + $artifact.name) | |
Write-Host Removing $artifactPath | |
Invoke-RestMethod -Uri "$artifactoryUrl/$artifactPath" -Headers $headers -Method Delete | |
} | |
Write-Host Deleted $expiredItems.results.Count outdated artifacts |
Comments
Post a Comment