Create a temporary directory for specific steps in Jenkins pipeline

How about this to create a temp path and then use it via a dir clause. It seems to work for me.

dir (pwd(tmp: true)) {...}

I'm not sure if this creates A temp directory or uses THE one and only temp directory for the workspace. The docs say 'a' but seeing is believing.


Not exactly. There's the deleteDir step, which deletes the current directory, so you could do:

dir('/tmp/jobDir') {
    // your steps here
    deleteDir()
}

If this comes up often enough, you could also just make your own function:

def tempDir(path, closure) {
    dir(path) {
        closure()
        deleteDir()
    }
}

And use it like this:

tempDir('/tmp/jobDir') {
    // your steps here
}

Edit: If you only want to delete the directory if it was newly created, you can use fileExists:

def tempDir(path, closure) {
    def dirExisted = fileExists(path)
    dir(path) {
        closure()
        if(!dirExisted) {
            deleteDir()
        }
    }
}

My favorite solution so far:

withTempDir {
 // Do something in the dir,e.g. print the path
 echo pwd()
}

void withTempDir(Closure body) {
  // dir( pwd(tmp: true) ) { // Error: process apparently never started i
  dir( "${System.currentTimeMillis()}" ) {
    try {
      body()
    } finally {
      deleteDir()
    }
  }
}