Search code examples
groovyjenkins-pipelinejenkins-groovy

Groovy string interpolation in jenkins pipeline - mixing credentials and constants


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.


Solution

  • 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.