arielma
arielma

Reputation: 1398

How to pass pipeline credential parameter to python script as env variable

I have a pipeline job with a credential parameter (user name and password), and also a groovy file that runs a shell script which triggers python file. How can I pass those parameters to the env so the python script can use them with os.getenv? Groovy file code:

def call() {
    final fileContent = libraryResource('com/amdocs/python_distribution_util/main.py')
    writeFile file: 'main.py', text: fileContent

    sh "python main.py"}

I know the pipeline-syntax should look something similar to that:

withCredentials([usernamePassword(credentialsId: '*****', passwordVariable: 'ARTIFACTORY_SERVICE_ID_PW', usernameVariable: 'ARTIFACTORY_SERVICE_ID_UN')]) {
    // some block
}

what is the correct way for doing it?

credential parameter from the jenkins pipeline

Upvotes: 1

Views: 4168

Answers (1)

arielma
arielma

Reputation: 1398

Correct syntax:

def call() {
        def DISTRIBUTION_CREDENTIAL_ID = params.DISTRIBUTION_CREDENTIAL_ID

        withCredentials([usernamePassword(credentialsId: '${DISTRIBUTION_CREDENTIAL_ID}', passwordVariable: 'ARTIFACTORY_SERVICE_ID_PW',  usernameVariable: 'ARTIFACTORY_SERVICE_ID_UN')]) {
        sh '''
            export ARTIFACTORY_SERVICE_ID_UN=${ARTIFACTORY_SERVICE_ID_UN}
            export ARTIFACTORY_SERVICE_ID_PW=${ARTIFACTORY_SERVICE_ID_PW}
    }
}

and then you can use config.py file to pull the values using:

import os

ARTIFACTORY_SERVICE_ID_UN = os.getenv('ARTIFACTORY_SERVICE_ID_UN')
ARTIFACTORY_SERVICE_ID_PW = os.getenv('ARTIFACTORY_SERVICE_ID_PW')

Upvotes: 1

Related Questions