简体   繁体   中英

Access Jenkins Credentials Environment Variables from Node.js

I have set up some credentials environment variables using the Credentials plugin for Jenkins. I am using them in my Jenkinsfile like this :

pipeline {
  agent any
  environment {
      
      DEV_GOOGLE_CLIENT_ID          = credentials('DEV_GOOGLE_CLIENT_ID')
      DEV_GOOGLE_CLIENT_SECRET      = credentials('DEV_GOOGLE_CLIENT_SECRET')
     
  }
stages {
stage('Install dependencies') {
  steps {
      dir("./codes") {
            sh 'npm install'
        }
  }
}
stage('Stop previous forever process') {
  steps {
    dir("./codes") {
       sh 'forever stop dev || ls'
    }
  }
}
stage('Clean forever logs') {
    steps {
        dir("./codes") {
            sh 'forever cleanlogs'
        }
    }
}
stage('Test ') {
    steps {
        dir("./codes") {
            sh 'npm run test'
        }
     }
   }
 }
}

In my Node.js code, I'm trying to get access to those env variables by writing process.env.DEV_GOOGLE_CLIENT_SECRET but that is not working I am getting undefined ... Thank you

Which type of credentials did you use: secret text or username and password ?

While using username and password you can get username and password separately each other like this

pipeline {
  agent any
  environment {
      DEV_GOOGLE_CLIENT = credentials('DEV_GOOGLE_CLIENT')
  }
stages {
stage('Get username and password') {
  steps {
    echo "username is $DEV_GOOGLE_CLIENT_USR"
    echo "password is $DEV_GOOGLE_CLIENT_PSW"
  }
}
}

I don't know how to call $DEV_GOOGLE_CLIENT_USR and $DEV_GOOGLE_CLIENT_PSW in node.js, sorry.

You pass your credentials in this order: Jenkins credentials > pipeline environment variable > node.js command line parameter

Make sure to create a Jenkins credentials as secret text first.

pipeline {
  agent any
  environment {
      JENKINS_SECRET_TEXT=credentials('JENKINS_SECRET_TEXT')
  }
  stages {
    stage('Pass secret as command line parameter') {
      steps {
        sh 'SECRET_ENV_VAR="$JENKINS_SECRET_TEXT" node app.js'
      }
    }
  }
}

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