Dean Erling
Dean Erling

Reputation: 21

Jenkins credentials in script block

I am attempting to retrieve a value stored in Jenkins Credentials in a Jenkins file script block but am unable to retreive the value

The following block in my jenkins file works

I have a Jenkins file that sets an environment variable with a credential value stored in jenkins credentials:

environment {
    CERT_CLIENT_TH = credentials("stored.cred.name")
}

When I try to do the same thing in a script block I'm unable to retreive the Credentials.

script {
  env.CERT_CLIENT_TH = credentials("stored.cred.name")
}

when I check the output using these two methods using echo "${env.CERT_CLIENT_TH}"

When getting in an envrionment block the output is "****" as expected because it is an encrypted credential value.

when I attempt to get credentials in a script block the echo output is

    @credentials(<anonymous>=stored.cred.name)

How to I get credentials in a script block in a Jenkins file?

Upvotes: 1

Views: 6599

Answers (1)

Dibakar Aditya
Dibakar Aditya

Reputation: 4203

As per this documentation, the credentials() is a special helper method supported by the environment directive. It therefore won’t work within the script block. The environment directive itself can be defined at the top-level of the pipeline or within a stage to limit its scope.

You might alternatively use the withCredentials( …​ ) { …​ } step as described here to limit the scope of the credentials in your pipeline.

Upvotes: 6

Related Questions