Craig Rodrigues
Craig Rodrigues

Reputation: 831

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.

Upvotes: 6

Views: 23404

Answers (3)

Craig Rodrigues
Craig Rodrigues

Reputation: 831

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")
            }
        }
    }
}

Upvotes: 12

ashish
ashish

Reputation: 31

Suppose you want a single file to from previous build, you can even use curl to place file in workspace before mvn invocation.

stage('Copy csv') {
            steps {
                   sh "mkdir -p ${env.WORKSPACE}/dump"
                    sh "curl http://<jenkins-url>:<port>/job/<job-folder>/job/<job-name>/job/<release>/lastSuccessfulBuild/artifact/dump/sample.csv/*view*/ -o ${env.WORKSPACE}/dump/sample.csv"
            }
        }    

Thanks, Ashish

Upvotes: 3

Subhash
Subhash

Reputation: 762

You Can Use Copy Artifact Plugin

For configuration visit https://wiki.jenkins.io/display/JENKINS/Copy+Artifact+Plugin

Upvotes: 0

Related Questions