Issue
I'm pretty new with Jenkins declarative pipeline. In Jenkinsfile, I want to check if a specific docker image is already on the machine or not. If the image is already so it just delete the old one then build the new one and if its not then its just build the new one. How can I reach this goal with declarative pipeline?
Much appreciate if you want to help
Solution
You can delete image using sh "docker rmi -f <ImageID>"
command.
And to find the ImageID you can use -qf
option of docker to list the imageids.
Reference example as below:
stage('Remove old Image') {
steps {
script {
def imageName = "<Your image Name>"
env.imageName = "${imageName}"
def oldImageID = sh(
script: 'docker images -qf reference=\${imageName}:\${imageTag}',
returnStdout: true
)
echo "Image Name: " + "${imageName}"
echo "Old Image: ${oldImageID}"
if ( "${oldImageID}" != '' ) {
echo "Deleting image id: ${oldImageID}..."
sh "docker rmi -f ${oldImageID}"
} else {
echo "No image to delete..."
}
}
}
}
For info about docker images options visit : https://docs.docker.com/engine/reference/commandline/images/
Answered By - Altaf