2

Currently I am having the following code in my Jenkins file

     environment {
        GITHUB_USER = credentials('GITHUB_USER')
        GITHUB_TOKEN= credentials('GITHUB_TOKEN')
        DOCKER_USER = credentials('DOCKER_USER')
        ARTIFACTORY_USER = credentials('ARTIFACTORY_USER')
     }

Since this code is being used in several place I want this code to be in shared library Like vars/commonCredentials.groovy

What's the best way to archive this and how can I use this in my Jenkins file?

Shilpi Das
  • 51
  • 3
  • do you want only the credential to be part of the shared library or all the build/deployment steps? If you feel all the build and deployment pipeline are the same, you could move everything to shared library and reference it from Jenkinsfile – Samit Kumar Patel Jan 20 '21 at 13:33
  • But It's possible to do it another way around. [here](https://stackoverflow.com/questions/48234633/access-environment-variables-in-jenkins-shared-library-code) is some discussion from the stack overflow – Samit Kumar Patel Jan 20 '21 at 14:11
  • @SamitKumarPatel I just have some common credentials that I want to move. I don't want to move entire pipeline – Shilpi Das Jan 21 '21 at 07:04
  • I don't think it's ever possible to have it in a shared library as declarative pipelines are meant to simplify the pipeline flow not to be for reusable purposes. try to use scripted [withCredential](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/) – Samit Kumar Patel Feb 08 '21 at 19:53

1 Answers1

0

Next code works for me - I exported credentials as variables.

    withCredentials([usernamePassword(credentialsId: 'svcacct_user', usernameVariable: 'SVCACCT_USER_USR', passwordVariable: 'SVCACCT_USER_PSW')]){
    sh '''#!/bin/bash --login
    echo $SVCACCT_USER_USR
    echo $SVCACCT_USER_PSW
    '''
    }
Ivan Kit
  • 1
  • 1