Get a list of filenames in a given folder in Jenkinsfile (Groovy)
This one works, but it's ugly as hell:
#!groovy
node('master') {
FILES_DIR = './foo'
cleanWs()
sh """
mkdir foo
touch foo/bar1
touch foo/bar2
touch foo/bar3
"""
def TMP_FILENAME = ".docker_files_list"
sh "ls ${FILES_DIR} > ${TMP_FILENAME}"
def filenames = readFile(TMP_FILENAME).split( "\\r?\\n" );
sh "rm -f ${TMP_FILENAME}"
for (int i = 0; i < filenames.size(); i++) {
def filename = filenames[i]
echo "${filename}"
}
}
You can't really make use of the new File
and normal Groovy/Java ways to traverse file systems. The call is security checked by default (see JENKINS-38131) and won't even generally work because of how Jenkins Pipelines executes your pipeline code.
One way you could do this would be to use the findFiles
step from the Pipeline Utility Steps plugin. It returns a FileWrapper[]
which can be inspected/used for other purposes.
node {
// ... check out code, whatever
final foundFiles = findFiles(glob: 'dockerfiles/**/*')
// do things with FileWrapper[]
}
Another option is to shell out and capture the standard out:
node {
// ... check out code, whatever
final foundFiles = sh(script: 'ls -1 dockerfiles', returnStdout: true).split()
// Do stuff with filenames
}