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 .'
      }
    }
  }
}