9

Struggling with a part of my jenkinsfile which requires mixed credentials and defined variables passed into a function.

Function looks like this:

platformList.each { platform -> 
    stage("Build ${platform}") {
        withCredentials([usernamePassword(credentialsId: 'XXX-XXX-XX', passwordVariable: 'unity_password', usernameVariable: 'unity_username')]) {
            sh label: "Build App", script: '${WORKSPACE}/ci/build_app.sh build_app ${platform} ${deployment} $unity_username $unity_password'
        }
    }
}

I'm trying to adhere to the advice around string interpolation as discussed here: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#string-interpolation

However, I don't seem to be able to mix the interpolated credentials with single-quotes, and the derived ${platform} variable as defined in the each loop.

platformList is an array containing 1+ strings. It is generated like this:

script {
    if (params['windows'] == true) {
        platformList.add("windows")
    }
    if (params['osx'] == true) {
        platformList.add("osx")
    }
    ...
}

If I run this script as-is, the ${platform} variable will be passed as a blank string to the sh call.

If I double-quote the sh call it works fine, but then I get the warning about insecure credentials passed via interpolation.

The ${deployment} variable, which is a string param defined as part of the execution of the job, parses without issue, so I assume this is a problem related to the each loop specifically.

Stephen Wright
  • 2,908
  • 4
  • 19
  • 28

2 Answers2

20

Use double quotes but Escape the $ sign for password ".... \$unity_password"

In this case it will not be interpolated on the level of groovy and will be passed as is to the shell and environment variable will be used on the level of shell.

daggett
  • 26,404
  • 3
  • 40
  • 56
  • 1
    Indeed key difference here is between Groovy variable and shell environment variable, and when during execution these variables should be resolved. – Matthew Schuchard Nov 15 '20 at 12:13
  • 1
    The answer becomes even more absurd because in powershell environment variables are under `$Env`, rather than directly added into regular variable scope. – Dragas May 14 '21 at 08:09
  • You still have to escape `$` before `Env:` when using it in doublequotes. And in shell Env variable syntax is similar to groovy that is confusing. – daggett May 14 '21 at 10:02
0

Use single quotes, and use the withEnv step to pass non-secret values as environment variables. Do not use string interpolation at the Groovy level.

Jesse Glick
  • 24,539
  • 10
  • 90
  • 112