Search code examples
jenkinsgroovystring-interpolation

Jenkins groovy string interpolation using a combination of secret and non secret values


I have a shell command in my Jenkins script that uses string interpolation for non secret values as well as secret values.

For non secret values, you are expected to use double quotes and the string should look something like this:

def variable = 'myValue'
sh("echo variable has value: ${variable}")

And for secret values (when using credentials for example) you are expected to use single quotes so you do not expose the secret values:

withCredentials([usernamePassword(credentialsId: 'myCreds', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
    sh('echo username: $USERNAME, password: $PASSWORD')
}

However, I have a use case where I am using secret + non secret values in the same shell command. What is the best practice for string interpolation in this case?

def variable = 'myValue'
withCredentials([usernamePassword(credentialsId: 'myCreds', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
    sh("variable has value: ${variable} and your creds are: username: $USERNAME, password: $PASSWORD")
}

This prints the expected warning in my console log that the secret values should not be string interpolated in this way, but it doesn't look like the official docs give any examples where you would need to use both secret + non secret values in a single interpolated string, so the only way I believe it can be done is using double quotes which risks leaking the value of the secrets. Is there another way or do I just have to take that risk?


Solution

  • After asking this question, the suggested "Related questions" have the answers I need:

    Use double quotes but escape the $ sign for secret values ".... \$USERNAME and \$PASSWORD".

    This then uses groovy string interpolation for the non secret values but does not for the ignored $ symbols, for these, they are set as an environment variable, just like with single quotes.