Created
January 23, 2020 11:08
-
-
Save fredericrous/26e51ed936d710364fe1d1ab6572766e to your computer and use it in GitHub Desktop.
Clean docker images on slaves
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
/* | |
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