I want to run an external shell command (for example, git clone
) inside a Jenkins pipeline.
I have found 2 ways of doing this.
This one works:
steps {
sh "git clone --branch $BRANCH --depth 1 --no-single-branch $REMOTE $LOCAL
}
Downsides:
- I only see the output when the complete command is finished. Which is annoying if the command takes a long time.
- I need to do some Groovy scripting to look up values in a
Map
, based on parameters chosen by the user who starts the build. Haven't found a way to do that without ascript {}
block. - A variation is to run a Bash script that runs the
git clone
command, that also works. Which will get me into trouble when running on Windows nodes.
The next one errors on
fatal: could not create work tree dir 'localFolder'.: Permission denied
steps {
script {
def localFolder = new File(products[params.PRODUCT].local)
if (!localFolder.exists()) {
def gitCommand = 'git clone --branch ' + params.BRANCH + ' --depth 1 --no-single-branch ' + products[params.PRODUCT].remote + ' ' + localFolder
runCommand(gitCommand)
}
}
}
This is the runCommand()
wrapper:
def runCommand = { strList ->
assert ( strList instanceof String ||
( strList instanceof List && strList.each{ it instanceof String } ) \
)
def proc = strList.execute()
proc.in.eachLine { line -> println line }
proc.out.close()
proc.waitFor()
print "[INFO] ( "
if(strList instanceof List) {
strList.each { print "${it} " }
} else {
print strList
}
println " )"
if (proc.exitValue()) {
println "gave the following error: "
println "[ERROR] ${proc.getErrorStream()}"
}
assert !proc.exitValue()
}
My question is: how come I have permission to create directories when running a sh
command, and how come I don't have that permission when I do the same thing inside a script {}
block with .execute()
?
I'm intentionally using the example of the git clone
command to avoid getting answers that don't read the question, like using a dir {}
block. If I can't create the git directory, then I can also not create the files inside that directory.