I have a Jenkins step which needs to run an inline shell script. The script requires a couple of arguments, which are contained in the config. What's the correct way of doing this? The shell script does need to be inline and can't be in a separate file. I've tried something like this, but it doesn't work.
stage('Build Image') {
steps {
script {
docker.withRegistry('.......', 'Gitlab') {
CHECK_SHA_RESULT = sh '''
ARG1=$1
ARG2=$2
// Do other stuff and output a result
''' ${config.var1} ${config.var2}
}
}
}
}
There are two options to pass values:
You may just pass values by expanding variables in Groovy strings:
sh """\
ARG1=${config.var1}
ARG2=${config.var2}
echo $ARG1
echo $ARG2
"""
(double quotes are used instead of single one)
You must be careful, because the values are fist expanded and next the code is executed. It means you are able to inject code. Example:
var1=text; cat /etc/passwd
var2=hello
ARG1=text; cat /etc/passwd
ARG2=hello
echo $ARG1
echo $ARG2
You may inject values by using environment variables. It is much safer, because the values are expanded by the shell process (prevent command injection).
withEnv([
"ARG1=${config.var1}",
"ARG2=${config.var2}"
]) {
sh '''\
echo $ARG1
echo $ARG2
'''
}
(sh
script is defined by using singe quotes)
Example:
var1=text; cat /etc/passwd
var2=hello
text; cat /etc/passwd
hello
echo $ARG1
echo $ARG2