pipeline { agent any stages { stage('Build') { steps { script { // Get the current commit SHA and take the first 7 characters def commitSha = env.GIT_COMMIT.take(7) // Tag the Docker image with the short commit SHA sh """ docker buildx build -t helloworld:${commitSha} docker run --rm helloworld:${commitSha} """ } } } } post { failure { script { // Use the last commit SHA instead of the failed build's SHA def lastCommitSha = env.GIT_COMMIT.take(7) // Get the last successful build def lastSuccessfulBuild = currentBuild.rawBuild.getPreviousSuccessfulBuild() if (lastSuccessfulBuild) { // Redeploy the last successful build using the last commit SHA echo "Redeploying build #${lastSuccessfulBuild.getId()}..." echo "Last successful build was #${lastSuccessfulBuild.getNumber()}" echo "Using last commit SHA: ${lastCommitSha}" // Example: Call your deployment script or steps here // sh "deploy-script.sh ${lastSuccessfulBuild.getNumber()} --commit ${lastCommitSha}" sh """ docker buildx build -t khabir7/helloworld:${lastCommitSha} docker run --rm khabir7/helloworld:${lastCommitSha} """ } else { error "No successful build found to deploy." } } } } }