jenkinsbuildenvironment-variablescicdsecrets

How do I copy secret to Environment variable in jenkins?


I have a secret key stored in Jenkins Secret String.

I am trying to set it as environment variable, however, it doesn't work

withCredentials([string(credentialsId: 'SECRET_KEY', variable: 'SECRET_KEY')]) {
    sh '''
        echo "SECRET_KEY: $SECRET_KEY"
        export SECRET_KEY="$SECRET_KEY"
    '''
    echo "SECRET_KEY: ${env.SECRET_KEY}"
}
echo "SECRET_KEY: ${env.SECRET_KEY}"

Whenever inside of withCredentials, variable is available, however, outside of that scope it gots reset to null value


Solution

  • Actually, I have found a way to get access to environment variable across the steps and stages.

    Instead of using

    withCredentials
    

    I should actually use credentials helper method

    def call(String startParam) {
    
        pipeline {
            agent any
    
            environment {
                SECRET_KEY = credentials('SECRET_KEY')
            }