1
votes

I have a common Jenkins shared library for all the repositories as below

vars/_publish.groovy

def call(opts) {
    pipeline {
        environment {
            abc= credentials(’abc')
            def= credentials(‘def’)
 
        }
        stages {
            stage('Build') {
                steps{
                    sh ‘docker build'
                }
            }

jenkinsfile

@Library('my-shared-library@branch') _

_publish() {
}

This works fine successfully for 1 single service. now I want to keep this jenkins shared library for all the services/projects but each service has different env variables.

The environment block {} in vars/_publish.groovy has 10 env variables that are not constant for all the projects/services. The values differ according to the project/services. How can I pass env variables to this jenkins shared library for different projects? Each project/service has different Jenkins pipeline. can I pass the variables from jenkinsfile to shared library? Can anyone help?

1

1 Answers

0
votes

You can pass them with the help of withEnv (Documentation) method from your Jenkins file.

@Library('my-shared-library@branch') _

node(''){
 withEnv([
  “credId='id-cred'”,
  “y=20”
 ]){
  _publish() {}
 }
}


// shared lib

def call(opts) {
  stage('Build') {
  echo "env is ${env.credId}"
          withCredentialswithCredentials([usernamePassword(credentialsId: env.credId, usernameVariable: 'USER', passwordVariable: 'PASSWORD')]){  
             sh ‘docker build'
           }
        }
}