为Jenkins管道

时间:2018-01-02 22:29:50

标签: jenkins jenkins-pipeline

是否有一个Jenkins管道步骤会在目录中创建并运行一系列步骤?

我知道dir步骤会在特定目录中运行块中的步骤:

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

我的问题是,如果管道或插件中有一个步骤让我运行此代码块,但/tmp/jobDir是在块的开头创建的,并在结束时删除块。

类似的东西:

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

这样的步骤或插件是否存在?

3 个答案:

答案 0 :(得分:6)

不完全是。有deleteDir step删除了当前目录,因此你可以这样做:

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

如果这种情况经常发生,你也可以自己动手:

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

并像这样使用它:

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

修改:如果您只想删除新创建的目录,可以使用fileExists

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

答案 1 :(得分:2)

如何创建临时路径,然后通过dir子句使用它。看来对我有用。

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

我不确定这是创建一个临时目录还是为工作区使用一个唯一的临时目录。 docs说“ a”,但眼见为实。

答案 2 :(得分:0)

到目前为止,我最喜欢的解决方案:

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()
    }
  }
}
相关问题