Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins 2 NPM_TOKEN credential

I'm trying to run Jenkins 2 pipeline (Jenkinsfile) that will use npm publish to publish a package to local NPM repository.
In order to do that I've try to use the following stage in Jenkinsfile:

stage('TEST npm whoami') {
    withEnv(["PATH+NPM=${tool name: 'node-6', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation'}/bin"]) {
    withCredentials([[$class: 'StringBinding', credentialsId: 'npm-token', variable: 'NPM_TOKEN']]) {
        sh """
           npm whoami
           """
    }
    }
}

Currently I'm running only npm whoami and once that will work I'll replace it with npm publish.

This is the output I'm getting:

+ npm whoami
npm ERR! Linux 4.7.5-1.el7.elrepo.x86_64
npm ERR! argv "/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node-6/bin/node" "/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node-6/bin/npm" "whoami"
npm ERR! node v6.5.0
npm ERR! npm  v3.10.3
npm ERR! code ENEEDAUTH

npm ERR! need auth this command requires you to be logged in.
npm ERR! need auth You need to authorize this machine using `npm adduser`
like image 647
Ido Ran Avatar asked Oct 13 '16 08:10

Ido Ran


2 Answers

From looking at this GitHub issue, it seems like NPM_TOKEN isn't something that npm itself recognizes, but rather a custom environment variable that heroku (and maybe other platforms) interpret.

What I've done, based on some of the discussion in that issue, is to create a project-level .npmrc at job execution time based on the token env var from my credential, then remove the file again before continuing. E.g.:

stage('TEST npm whoami') {
    withCredentials([string(
                credentialsId: 'npm-token',
                variable: 'NPM_TOKEN')]) {
        sh "echo //npm.skunkhenry.com/:_authToken=${env.NPM_TOKEN} > .npmrc"
        sh 'npm whoami'
        sh 'rm .npmrc'
    }
}

Hope this helps!

like image 157
grdryn Avatar answered Oct 26 '22 17:10

grdryn


The answer of Gerard Ryan and Gaston is correct, I just wanted to add one detail that I did not get at first:

If you want to use a private repository, the .npmrc should also specify the registry:

withCredentials([string(credentialsId: 'registry', variable: 'token')]) {
            try {
                sh "echo registry=<your-registry-URL> >> .npmrc"
                sh "echo //<your-registry-URL>/:_authToken=${env.token} >> .npmrc"
                sh 'npm whoami'
            } finally {
                sh 'rm ~/.npmrc'
            }
}
like image 1
oezpeda Avatar answered Oct 26 '22 18:10

oezpeda