1

In FreeStyle Project, I have lots of env vars, which are available from any part of Jenkins' job. I also used ghprb plugin to trigger that job against GH PRs, which added some extra env vars.

Later, that job became more complex, so I've decided to put it on Jenkins Pipeline. But now, the issue is, I can't retrieve those env vars in a pipeline, which were available before, in the Freestyle Project.

I'm a newbie in writing Jenkins Pipeline, that's why I decided to use declarative approach for that purpose (but I don't think it's root cause). So, my question is, how to retrieve env vars in Jenkins Pipeline, such as: ${BUILD_CAUSE}, ${ghprbTargetBranch}, ${ghprbActualCommitAuthorEmail}?

5
  • Can you post an example snippet where you try to use the vars? On which OS is your Jenkins instance based? Windows?
    – Chris
    Commented Apr 10, 2019 at 13:57
  • OS, in general, is Linux. Snippet: if [ $BUILD_CAUSE == MANUALTRIGGER ]; then exit 0 fi NC=$(git merge-base HEAD remotes/origin/$ghprbTargetBranch)
    – acd
    Commented Apr 10, 2019 at 19:10
  • The bracket is missing here, isn't it? ${BUILD_CAUSE} instead of $BUILD_CAUSE
    – Chris
    Commented Apr 11, 2019 at 6:47
  • No, man, it doesn't really matter, as it's a shell. In a Freestyle project it works fine.
    – acd
    Commented Apr 11, 2019 at 8:55
  • Are you using a multi-branch pipeline? The PRs are handled in a different way and many variables are different.
    – plmaheu
    Commented May 14, 2019 at 22:30

2 Answers 2

2

If you want to use environment variables with the ${VAR} syntax in the declarative pipeline, then you need to define those variables in the environment { } block.

for example:

environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'sqlite'
    }

    stages {
        stage('Build') {
            steps {
                echo "Database engine is ${DB_ENGINE}"
                echo "DISABLE_AUTH is ${DISABLE_AUTH}"
                sh 'printenv'
            }
        }
    }

If you want to use environment variables that come from other plugins etc, then you need to access them with the env.VAR syntax. For example:

echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"

0

Not sure if you did, but put the vars into double quotes:

... "${BUILD_CAUSE}"
1
  • Thanks, Chris, for your try to help, but it's not about that. I tried different work-arounds, including setting vars in Groovy style (e.g. env.BUILD_CAUSE), but nothing helped.
    – acd
    Commented Apr 10, 2019 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.