且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以将groovy脚本从相对目录导入Jenkinsfile吗?

更新时间:2023-12-05 18:07:40

加载共享Groovy代码的***方法是通过

The best-supported way to load shared groovy code is through shared libraries.

如果您有一个这样的共享库:

If you have a shared library like this:

simplest-jenkins-shared-library master % cat src/org/foo/Bar.groovy
package org.foo;

def awesomePrintingFunction() {
  println "hello world"
}

将其添加到源代码管理中,在jenkins作业中甚至在全局中进行配置(这是使用管道时通过Jenkins UI进行的唯一操作之一),如以下屏幕截图所示:

Shove it into source control, configure it in your jenkins job or even globally (this is one of the only things you do through the Jenkins UI when using pipeline), like in this screenshot:

然后使用它,例如:

pipeline {
  agent { label 'docker' }
  stages {
    stage('build') {
      steps {
        script {
          @Library('simplest-jenkins-shared-library')
          def bar = new org.foo.Bar()
          bar.awesomePrintingFunction()
        }
      }
    }
  }
}

该版本的控制台日志中的输出当然包括:

Output from the console log for this build would of course include:

hello world

还有许多其他方式来编写共享库(例如使用类)和使用它们(例如定义vars,以便您可以以超级流畅的方式在Jenkinsfiles中使用它们).您甚至可以将非常规文件加载为资源.有关这些扩展用例,请查看共享库文档.

There are lots of other ways to write shared libraries (like using classes) and to use them (like defining vars so you can use them in Jenkinsfiles in super-slick ways). You can even load non-groovy files as resources. Check out the shared library docs for these extended use-cases.