简体   繁体   中英

Jenkins groovy scripted pipeline variables not substituting correctly

I'm running a very simple pipeline to create maven projects, the pipeline is to run a single maven install command.

The trouble is substituting variables into the one-liner. I've tried various different things but stuck in a strange place. Take example pipeline below:

node {
    stage('Set Vars') {
        GIT_HASH = sh (script: "git log -n 1 --pretty=format:'%H'" , returnStdout: true)
        echo "git hash is >>>>>>>> $GIT_HASH"
        BUILD_NUM="${env.BUILD_NUMBER}"
        echo "build no is >>>>>>>> ${BUILD_NUM}"
    }
    stage('Build Project') {
        sh "mvn clean install -PrunInstallPackage -Duser=admin -Dpass=guessing -Dip=200.0.0.1 -Dport=4444 -Dhash=${GIT_HASH} -Dbuildnumber=${BUILD_NUM}"
    }
}

I would expect to see the variables substitued in the mvn install command, this does not seem to work this way though.

This build results in:

sh "mvn clean install -PrunInstallPackage -Duser=admin -Dpass=guessing -Dip=200.0.0.1 -Dport=4444 -Dhash=${GIT_HASH}

Both echo commands print out correct output.

Why does the last command get cut off after the first variable substitution?

Also, for some unknown reason, I cannot substitute -Dbuildnumber=${env.BUILD_NUMBER}" directly into the maven command. Seems like something that a user should be able to do. What am I missing here?

Many thanks in advance

I am trying to remember how I solved same issues in the past..

Problem 1

You are using the GIT_HASH variable across two stages, so you have to declare it global to share it across them:

// Global variables declaration

GIT_HASH = null

// Pipeline code

node {
    stage('Set Vars') {
        GIT_HASH = sh (script: "git log -n 1 --pretty=format:'%H'" , returnStdout: true)
        echo "git hash is >>>>>>>> $GIT_HASH"
        BUILD_NUM="${env.BUILD_NUMBER}"
        echo "build no is >>>>>>>> ${BUILD_NUM}"
    }
    stage('Build Project') {
        sh "mvn clean install -PrunInstallPackage -Duser=admin -Dpass=guessing -Dip=200.0.0.1 -Dport=4444 -Dhash=${GIT_HASH} -Dbuildnumber=${BUILD_NUM}"
    }
}

Problem 2

env.BUILD_NUMBER is a Groovy statement, instead mvn gets executed inside a shell instance by the sh command.

For that reason I suggest you to use the BUILD_NUM variable way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM