Search code examples
jenkinsjenkins-declarative-pipeline

How to handle a possible non-existant branch when copying artifacts in a Jenkins declarative pipeline?


I have two multi-branch pipeline jobs, where one has to take artifacts from the other. If both repositories have matching branches, I want to use the corresponding branch, but I want to fall back to using master if necessary; the library may or may not be being modified for this feature in the application. I can pick the current branch easily

copyArtifacts(projectName: "upstream_library/${BRANCH_NAME}", selector:lastSuccessful())

but if there is no branch the build fails. It seems I either need to catch the error, or test for the existence of the branch before fetching, neither of which I can see how to do in a declarative pipeline. Do I have to use a script step? (Declarative jenkins pipeline, retrieve artifact suggests that solution for a slightly different problem)


Solution

  • A script step works

    steps {
        script {
            try {
                copyArtifacts(projectName: "upstream_library/${BRANCH_NAME}", selector:lastSuccessful())
            } catch (err) {
                copyArtifacts(projectName: "upstream_library/master", selector:lastSuccessful())
            }
        }