Credentials, Shared Libraries, and Declarative Pipelines

I have a declarative pipeline that uses some shared library I created to perform some commands requiring authentication. To perform these tasks, I can do it directly from my Jenkinsfile using the normal credentials syntax:

environment
{
  CREDS = credentials('my_special_creds')
}
...
step
{
  sh('mycommand.sh --username $CREDS_USR --password $CREDS_PSW')
}

However, I can’t seem to get them passed into my shared library safely (i.e. avoiding Groovy double-quote expansion). The problem seems to be passing them in as arguments.

It doesn’t work to do this:
mylib.groovy

call(Map params = [:])
{
  sh('mycommand.sh --username $params.user --password $params.pass')
}

(this seems to result in Groovy replacing $params with ‘’, so the command is “mycommand.sh --username .user --password .pass”

I also tried passing as separate strings, thinking it was a period-breaking-the-dereference issue. Didn’t work.

How should I pass credentials into Jenkins Shared Library calls within a Declarative Pipeline?

single quotes are not evaluated, so bash is trying to evaluate an environmental variable called $params. why not pass in the credential id, and use withCredentials {} block to create env variables with that credential just for that scope?

I think that’s a scripted pipeline thing, right? I’m using Declarative syntax. Thus the environment { credentials() } approach, vs withCredentials.

shared libraries are always scripted

edit: actually not always, but afaik you can only have one pipeline {} and once you go into the function your scripted.

1 Like

You’re right! It does seem that once we enter the shared library, withCredentials() works, even though the rest of the pipeline is declarative. This was confusing for me because, in the Declarative pipeline file, you cannot use the scripted Groovy shared library calls (e.g. I can’t do a “myclass.function()”, I just have to call “myclass()” and implement the call() function). So, while I am limited in how I can call shared libraries, once inside that call() function, apparently all scripting goes :slight_smile:

Thanks for the support, and hopefully this helps someone else coming across this issue.

2 Likes