Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins pipeline, how can I copy artifact from previous build to current build?

In Jenkins Pipeline, how can I copy the artifacts from a previous build to the current build? I want to do this even if the previous build failed.

like image 607
Craig Rodrigues Avatar asked Dec 14 '22 13:12

Craig Rodrigues


1 Answers

Stuart Rowe also recommended to me on the Pipeline Authoring Sig Gitter channel that I look at the Copy Artifact Plugin, but also gave me some sample Jenkins Pipeline syntax to use.

Based on the advice that he gave, I came up with this fuller Pipeline example which copies the artifacts from the previous build into the current build, whether the previous build succeeded or failed.

pipeline {
    agent any;

    stages {
        stage("Zeroth stage") {
            steps {
                script {
                    if (currentBuild.previousBuild) {
                        try {
                            copyArtifacts(projectName: currentBuild.projectName,
                                          selector: specific("${currentBuild.previousBuild.number}"))
                            def previousFile = readFile(file: "usefulfile.txt")
                            echo("The current build is ${currentBuild.number}")
                            echo("The previous build artifact was: ${previousFile}")
                        } catch(err) {
                            // ignore error
                        }
                    }
                }
            }
        }

        stage("First stage") {
            steps {
                echo("Hello")
                writeFile(file: "usefulfile.txt", text: "This file ${env.BUILD_NUMBER} is useful, need to archive it.")
                archiveArtifacts(artifacts: 'usefulfile.txt')
            }
        }

        stage("Error") {
            steps {
                error("Failed")
            }
        }
    }
}
like image 52
Craig Rodrigues Avatar answered Dec 26 '22 12:12

Craig Rodrigues