Skip to content

Instantly share code, notes, and snippets.

@mryan43
Created August 14, 2017 06:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mryan43/f160fb29cbad0da169fe007735c7307b to your computer and use it in GitHub Desktop.
Save mryan43/f160fb29cbad0da169fe007735c7307b to your computer and use it in GitHub Desktop.
Nexus 3 script delete images not downloaded since X months.
import groovy.time.TimeCategory
import org.sonatype.nexus.repository.storage.Asset
import org.sonatype.nexus.repository.storage.Component
import org.sonatype.nexus.repository.storage.Query
import org.sonatype.nexus.repository.storage.StorageFacet
def repo = repository.repositoryManager.get("sq-docker")
StorageFacet storageFacet = repo.facet(StorageFacet)
def tx = storageFacet.txSupplier().get()
def cutoff
tx.begin()
try {
use(TimeCategory) {
cutoff = 1.year.ago
log.info "Deleting all docker images (components) for which the manifest has not been downloaded since [${cutoff.format('yyyy-MM-dd HH:mm:ss')}]"
}
Iterable<Asset> assets = tx
.findAssets(Query.builder()
.where('content_type = ').param('application/vnd.docker.distribution.manifest.v2+json')
.and('last_downloaded < ').param(cutoff.format("yyyy-MM-dd HH:mm:ss"))
.build(), [repo])
assets.each {
if (it.componentId() != null) {
Component image = tx.findComponent(it.componentId())
log.info("Deleting image [${image.name()}:${image.version()}] last downloaded on [${it.lastDownloaded()}]")
tx.deleteComponent(image)
}
}
} finally {
tx.commit()
}
log.info("Finished deleting unused images components. Layers will be removed when the 'purge docker unused Images and manifests' and 'Compact blob store' tasks will run")
@satyam88
Copy link

Hi where are you providing nexus URL reponame username and password

@ocanema
Copy link

ocanema commented Sep 25, 2018

Hi where are you providing nexus URL reponame username and password

This script will be configured as a nexus script task. Authentication is not useful.
http://<nexus_server>/#admin/system/tasks -> Create task -> Admin - Execute script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment