How to use the environment variable in the agent section of the Jenkins declarative pipeline?

I am creating a Docker image for a node.js-based application where some dependencies require an NPM token for the private NPM registry, but when creating the image, the variable containing the token is null, for example

docker build -t 3273e0bfe8dd329a96070382c1c554454ca91f96 --build-args NPM_TOKEN=null -f Dockerfile 

simplified conveyor:

 pipeline { environment { NPM_TOKEN = credentials('npm-token') } agent { dockerfile { additionalBuildArgs "--build-args NPM_TOKEN=${env.NPM_TOKEN}" } } stages { stage('Lint') { steps { sh 'npm run lint' } } } } 

Is there a way to use the env variable in this section or is it currently not supported?

By the way, I followed the offers in Dockers and private modules related to using NPM token to create docker images

+10
source share
3 answers

This is definitely a declarative pipeline error. You can track the problems associated with this here: https://issues.jenkins-ci.org/browse/JENKINS-42369

If you move away from using a declarative pipeline and use script pipelines instead, this will not happen, although your Jenkinsfile will be more β€œverbal”

+8
source

found a solution for this. Use the credential 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 .' } } } } 
0
source

I found a workaround for this, and it still uses the declarative pipeline. I use this technique to download private github repositories using 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 codebase def 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() } } 
0
source

All Articles