Search code examples
node.jsnpm-scriptsjenkins-job-dslpact

Passing parameters from Jenkins CI to npm script


When I run Jenkins build, I would like to pass COMMIT_HASH and BRANCH_NAME to one of my javascript files: publish.js, so that I can remove hard-coded values for tags and consumerVersion.

Here is my code:

Jenkinsfile

stage('Publish Pacts') {
    steps {
        script {
            sh 'npm run publish:pact -Dpact.consumer.version=${COMMIT_HASH} -Dpact.tag=${env.BRANCH_NAME}'
        }
    }
}

package.json

"scripts": {
    "publish:pact": "node ./src/test/pact/publish.js"
}

./src/test/pact/publish.js

let publisher = require('@pact-foundation/pact-node');
let path = require('path');

let opts = {
    providerBaseUrl: `http://localhost:${global.port}`,
    pactFilesOrDirs: [path.resolve(process.cwd(), 'pacts')],
    pactBroker: 'http://localhost:80',
    tags: ["prod", "test"], // $BRANCH_NAME
    consumerVersion: "2.0.0" // $COMMIT_HASH
};

publisher.publishPacts(opts).then(() => {
    console.log("Pacts successfully published");
    done()
});

Does anyone know how to do this?


Solution

  • You can pass cli arguments to your node script which end up in your process.argv. Also npm passes on cli arguments via two dashes --.

    To illustrate this consider this example:

    Jenkinsfile

    stage('Publish Pacts') {
        steps {
            script {
                sh 'npm run publish:pact -- ${COMMIT_HASH} ${env.BRANCH_NAME}'
            }
        }
    }
    

    package.json

    "scripts": {
        "publish:pact": "node ./src/test/pact/publish.js"
    }
    

    publish.js

    // process.argv[0] = path to node binary
    // process.argv[1] = path to script
    
    console.log('COMMIT_HASH:',process.argv[2]);
    console.log('BRANCH_NAME:',process.argv[3]);
    

    I left the cli flags out for simplicity. Hope this helps