I want to execute the following code in jenkins pipeline
def updateFunction= "vault kv patch -namespace=namespace "
updateFunction += "-mount=mount "
updateFunction += "key1=$key1"
updateFunction += "key2=$key2"
sh updateFunction
But only the first key is patched and the second part throws
script.sh.copy: line 2: key2=key2: not found
The only way it works it if I split it in two but this way I have two new versions instead of 1
There isn't enough information about the source of key1
, but I bet it has a new line character at the end. Try trimming it and adding a trailing space:
def updateFunction= "vault kv patch -namespace=namespace "
updateFunction += "-mount=mount "
updateFunction += "key1=${key1.trim()} "
updateFunction += "key2=$key2"
Generally speaking building a script like that is asking for trouble. Unless you are absolutely sure your values are [0-9a-zA-Z]+
you would need to think about escaping them. And that's a pretty deep rabbit hole if you want to do it correctly. I would replace it with:
withEnv([
"key1=$key1",
"key2=$key2",
]) {
sh script: '''
vault kv patch -namespace=namespace -mount=mount key1="$key1" key2="$key2"
'''
}
Notice '''
- they ensure that parameter expansion is happening in the shell, not in groovy.