Search code examples
jenkinsgroovystring-interpolation

Jenkins string interpolation with credentials


I'm coding this function in Jenkins to query Artifactory:

def curlDockerArtifact(URL, registryName, moduleName, tag, token) {
 def controlURI = "${URL}/artifactory/api/storage/${registryName}/${moduleName}/${tag}"
 def result = sh(script: """
                         curl -I -H \'Authorization: Bearer $token\' \
                         https://$controlURI -o /dev/null -w \'%{http_code}\' -s
                         """, returnStdout: true)
}

But I get this warning which I'm tying to avoid.

Warning: A secret was passed to "sh" using Groovy string interpolation, which is insecure.

I tried using single quotes but the variables don't get correctly interpreted from Groovy. Any idea how to fix/refactor the code?


Solution

  • You have to keep double quotes like you do, but you need to escape the $ sign for the token. Like this :

    curl -I -H \'Authorization: Bearer \$token\'
    

    The groovy will not interpolate the variable and the correct value will be passed on the shell level.

    More informations : https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#interpolation-of-sensitive-environment-variables