How can I copy artifacts from executed jobs with declarative pipeline?

jenkins, jenkins-pipeline

Solution

You can use Copy Artifact plugin and then you can use it with `step` step, which allows to call builders or post-build actions as in Freestyle jobs. See Pipeline Syntax of your job and consult Snippet Generator. (https://[jenkins-url]/[path-to-your-job]/pipeline-syntax/)

This is how to copy all artifacts from job `myjob` to current pipeline job workspace:

pipeline {
    agent {
        label 'my-pc'
    }

    stages {
        stage ('Build') {
            steps {
                build job: 'myjob', parameters: [string(name: 'BRANCH', value: 'master')]
            }
            post {
                always {
                    step([
                        $class: 'CopyArtifact',
                        filter: '*',
                        projectName: 'myjob',
                        selector: [
                            $class: 'StatusBuildSelector',
                            stable: false
                        ]])
                }
            }
        }
    }
}

Problem

My pipeline script looks like this: ``` pipeline { agent { label 'my-pc' } stages { stage ('Build') { steps { build job: 'myjob', parameters: [string(name: 'BRANCH', value: 'master')] } post { always { sh 'echo TODO: copy artifacts here' } } } } } ``` I want to copy artifacts generated by myjob. How can I do this? Jenkins documentation page "Recording tests and artifacts" has an instruction which is not applicable for my pipeline (in my case artifact is generated by a separate job).

Original source