Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a temporary directory for specific steps in Jenkins pipeline

Is there a Jenkins pipeline step that will create and run a block of steps in a directory?

I know that the dir step runs the steps in the block in a specific directory:

// not in /tmp/jobDir
dir ('/tmp/jobDir') {
    // these steps get run in /tmp/jobDir
}
// once again not in /tmp/jobDir

My question is if there is a step in Pipeline or in a plugin that let's me run this codeblock, but /tmp/jobDir is created at the start of the block, and is removed at the end of the block.

Something like:

// /tmp/jobDir does not exist
dir ('/tmp/jobDir') {
    // /tmp/jobDir now exists
    // these steps get run in /tmp/jobDir
}
// /tmp/jobDir has been removed

Does such a step or plugin exist?

like image 434
jpyams Avatar asked Jan 02 '18 22:01

jpyams


People also ask

How do I create a directory in Jenkins pipeline?

Just use a file operations plugin. Just for the directory creation it is easier to use the pipeline's dir { }. However mentioning of this plugin is also interesting, because it can perform many other file operations on a node.

How do I create a temporary working directory?

Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

What are @TMP folders in Jenkins?

tmp" under Jenkins workspace? These folders are temporary int-dir used by Jenkins Coverity jobs, when the int-dir is not explicitly set in job configuration. These folders are generally deleted automatically after the job finishes, but will be left if the job failed or interrupted.


1 Answers

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()
    }
  }
}
like image 177
schnatterer Avatar answered Oct 15 '22 23:10

schnatterer