How to use an environment variable in the agent section of a Jenkins Declarative Pipeline? How to use an environment variable in the agent section of a Jenkins Declarative Pipeline? jenkins jenkins

How to use an environment variable in the agent section of a Jenkins Declarative Pipeline?


This is definitely a bug with the declarative pipeline. You can track the issue related to this here: https://issues.jenkins-ci.org/browse/JENKINS-42369

If you move away from using the declarative pipeline and use the scripted pipelines instead, this won't occur, although your Jenkinsfile will be "wordier"


found a solution for this. Use credentials manager to add NPM_TOKEN. Then you can do

pipeline {  agent {    docker {      image 'node:latest'      args '-e NPM_TOKEN=$NPM_TOKEN'    }  }  stages {    stage('npm install') {      steps {        sh 'npm install'      }    }    stage('static code analysis') {      steps {        sh 'npx eslint .'      }    }  }}


I came up with a workaround for this and it still uses declarative pipeline.I'm using this technique to download private github repos with pip.

// Workarounds for https://issues.jenkins-ci.org/browse/JENKINS-42369// Warning: The secret will show up in your build log, and possibly be in your docker image history as well.// Don't use this if you have a super-confidential codebasedef get_credential(name) {  def v;  withCredentials([[$class: 'StringBinding', credentialsId: name, variable: 'foo']]) {      v = env.foo;  }  return v}def get_additional_build_args() {    return "--build-arg GITHUB_ACCESS_TOKEN=" + get_credential("mysecretid")}pipeline {    agent {        dockerfile {            filename 'Dockerfile.test'            additionalBuildArgs get_additional_build_args()        }    }