Skip to content

Instantly share code, notes, and snippets.

@fredericrous
Created January 23, 2020 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredericrous/26e51ed936d710364fe1d1ab6572766e to your computer and use it in GitHub Desktop.
Save fredericrous/26e51ed936d710364fe1d1ab6572766e to your computer and use it in GitHub Desktop.
Clean docker images on slaves
/*
Clean Docker job on every slaves
Removes stopped containers. Delete unused images.
Triggers every day at 7AM
*/
// The ArrayList of slaves is not serializable, so fetching them should be marked as @NonCPS so that
// no attempt is made to serialize and save the local state of the function. See here for details:
// https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md#serializing-local-variables
@NonCPS
def onlineSlaves() {
def slaves = []
hudson.model.Hudson.instance.slaves.each {
try {
def computer = it.computer
if (!computer.isOffline()) {
slaves << it.name
}
} catch (error) {
println error
}
}
return slaves
}
// Run a command on each slave in series
def shAllSlaves(unixCmdLine) {
onlineSlaves().each {
try {
node(it) {
if (isUnix()) {
sh "${unixCmdLine}"
}
}
} catch (error) {
println error
}
}
}
pipeline {
agent { label 'linux_x64' }
options {
ansiColor('xterm')
buildDiscarder(logRotator(numToKeepStr: '100', artifactNumToKeepStr: '20'))
timeout(time: 2, unit: 'HOURS')
timestamps()
}
triggers {
cron('H 7 * * *')
}
stages {
stage('delete stopped containers') {
steps {
shAllSlaves 'docker ps -q -f status=exited | xargs --no-run-if-empty docker rm -f'
}
}
stage('delete unused images') {
steps {
shAllSlaves 'docker images -q -f dangling=true | xargs --no-run-if-empty docker rmi -f'
}
}
}
post {
always {
deleteDir()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment