Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Jenkinsfile Interpolation Syntax Issue


I have the following Step in my Declarative Jenkinsfile:

stage('Download Lambda Artifacts') {
    steps {
        script {
            withCredentials([usernamePassword(credentialsId: ARTIFACTORY_CREDENTIALS_ID, usernameVariable: 'ARTIFACTORY_USERNAME', passwordVariable: 'ARTIFACTORY_PASSWORD')]) {
                def lambdaNames = env.LAMBDA_NAME.tokenize(',')
                for (lambdaName in lambdaNames) {
                    sh '''
                        python get-artifact.py -u ${ARTIFACTORY_USERNAME} -p ${ARTIFACTORY_PASSWORD} -b "${lambdaName}.jar"
                    '''
                }
            }
        }
    }
}

The python script essentially just downloads the ${lambdaName}.jar from my Artifactory, and LAMBDA_NAME is just a bunch of strings separated by a comma.

Here is my issue: "${lambdaName}.jar" is not being interpolated, and is an empty value.

If i use """ for my sh instead of ''', it works, but then I get the warning about my ARTIFACTORY_USERNAME/PASSWORD having insecure interpolation of sensitive variables.

I'm sure it's a simple syntax issue, and I though wrapping my ${lambdaName} within "" would fix the issue. Is anyone able to see an solution? Many thanks.


Solution

  • As you seem to already know from the question, you need to interpolate the lambdaName as a Groovy variable within the string, and resolve the credentials variables as environment variables in the shell interpreter to avoid leaking them in the pipeline logs. You can achieve this via:

    sh "python get-artifact.py -u \${ARTIFACTORY_USERNAME} -p \${ARTIFACTORY_PASSWORD} -b ${lambdaName}.jar"
    

    Escaping the $ characters prevents Groovy from interpolating them within the string, and will instead cause them to be resolved by the shell interpreter. The " syntax interpolates the lambdaName as per usual within the Groovy string as you expect.