Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a second Jenkinsfile from a Jenkinsfile but continue to use original workspace - multibranch pipeline

I have a need to load in an external project from a base project at build time. (I own both code bases.) The external project contains a Jenkinsfile that I need to execute from the base project's Jenkinsfile, along with other scripts that need to be ran.

However, loading the external Jenkinsfile after cloning in the project causes a new WORKSPACE to be used (@2,3,4 etc appended at the end). This new workspace does not have the external project's cloned in files from the original workspace.

My hacky solution so far was to reset the WORKSPACE in the external Jenkinsfile to the original workspace.

environment {
    WORKSPACE = path/to/original/workspace
}

However, this will not work for a multibranch job, because those workspaces have a randomly generated set of characters at the end.

My thought was to pass in the workspace as a different environment variable name and set WORKSPACE in the second job to that. However, withEnv seems to work with regular strings but not variables.

Here is basically what I am doing so far, which does not work:

base Jenkinsfile:

node {
 cleanWs()
 checkout scm
 checkout([$class: 'GitSCM', branches: [[name: 'branch-name']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'sub-dir']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'creds', url: 'url']]])
  withEnv (['BASE_WORKSPACE=$WORKSPACE']) {
    load 'sub-dir/Jenkinsfile'
 }
}

cloned in Jenkinsfile:

pipeline {
 agent any
 environment {
    WORKSPACE = env.BASE_WORKSPACE
 }
 stages {
     stage('Stage 1'){
         steps{
             sh '''
             $WORKSPACE/sub-dir/bash-script.sh
             '''
        }
     }
  }
}

I have a few more hacky solutions in mind

  • Guessing at the base workspace from the external Jenkinsfile (subtract 1 from the end of the workspace name after the @ sign)

  • Writing the base workspace to a file in the base Jenkinsfile, and reading it in the second Jenkinsfile

  • Trying different syntax with withEnv

But before I went even more into the weeds wanted to reach out to this awesome community to see if anyone had thoughts on this.

Thanks!

like image 542
mm1620 Avatar asked Jul 10 '18 19:07

mm1620


2 Answers

However, withEnv seems to work with regular strings but not variables.

Use the following syntax instead to have the variable expanded:

 withEnv(["BASE_WORKSPACE=${env.WORKSPACE}"]) {
like image 190
Grisha Levit Avatar answered Oct 02 '22 19:10

Grisha Levit


withEnv (['BASE_WORKSPACE=' + WORKSPACE]) {
     load 'sub-dir/Jenkinsfile'
 }

worked for me, while the quotes are bash the rest is still groovy in the Jenkinsfile. Allowing you to concatenate the strings.

like image 23
Benbentwo Avatar answered Oct 02 '22 20:10

Benbentwo