Reputation: 179
This doesn't work:
withCredentials([usernamePassword(credentialsId: 'xxxxxxxxxxx', passwordVariable: 'ABCD', usernameVariable: 'XYZ')]) {
dir("build") {
sh "curl -u $XYZ:$ABCD --upload-file xyz.tar.gz https://mnpqr/repository/abc/$BRANCH_DIR/xyz.tar.gz"
}
}
Error:
/var/lib/jenkins/workspace/xyz/build@tmp/durable-71c2368a/script.sh: line 1: VG7cJ: No such file or directory
But this works:
withCredentials([usernamePassword(credentialsId: 'xxxxxxxxxxx', passwordVariable: 'ABCD', usernameVariable: 'XYZ')]) {
dir("build") {
sh 'curl -u $XYZ:$ABCD --upload-file xyz.tar.gz https://mnpqr/repository/abc/$BRANCH_DIR/xyz.tar.gz'
}
}
I want to interpolate more data into the sh script but I cannot as its failing with double quotes.
Upvotes: 0
Views: 1387
Reputation: 298
You have to be careful to distinguish the variable scopes:
They all have to be handled in a different way when replacing them in your double-quoted string:
node {
stage('My stage') {
// local variable scope
varContent = "Variable content"
// environment variable set up in script
env.envContent = "Environment content"
// environment variable available in shell script
withEnv(["BRANCH_NAME=myBranch"]) {
sh("echo ${varContent} XX ${env.envContent} XX \${envContent} XX \${BRANCH_NAME} XX ${env.BRANCH_NAME}")
}
}
}
In the example you see all of the three types. Let's have a closer look at the shell command:
sh("echo ${varContent} XX ${env.envContent} XX \${envContent} XX \${BRANCH_NAME} XX ${env.BRANCH_NAME}")
${varContent}
is a variable from local script scope it is replaced before the string is written to a temporary shell script${env.envContent}
and ${env.BRANCH_NAME}
handle environment variables that have already been set beforehand, as if they were a "local scope" variable\${envContent}
and \${BRANCH_NAME}
are the actual environment variables. The backslash escapes the dollar sign, and the shell script will contain shell variable placeholders ${envContent}
and ${BRANCH_NAME}
that will be replaced at shell script run time.Running the above script will show the following output:
Upvotes: 1