我可以将groovy脚本从相对目录导入Jenkinsfile吗? [英] Can I import a groovy script from a relative directory into a Jenkinsfile?

查看:424
本文介绍了我可以将groovy脚本从相对目录导入Jenkinsfile吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的项目:

I've got a project structured like this:

/
/ Jenkinsfile 
/ build_tools /
              / pipeline.groovy # Functions which define the pipeline
              / reporting.groovy # Other misc build reporting stuff
              / dostuff.sh # A shell script used by the pipeline
              / domorestuff.sh # Another pipeline supporting shell-script

是否可以在/build_tools中导入groovy文件,以便我可以在Jenkinsfile中使用这2个文件中的函数?

Is it possible to import the groovy files in /build_tools so that I can use functions inside those 2 files in my Jenkinsfile?

理想情况下,我想拥有一个Jenkins文件,看起来像这样(伪代码):

Ideally, I'd like to have a Jenkins file that looks something like this (pseudocode):

from build_tools.pipeline import build_pipeline
build_pipeline(project_name="my project", reporting_id=12345)

我遇到的问题是如何在伪代码的第1行上编写与该假装import语句等效的工作方式.

The bit I'm stuck on is how you write a working equivalent of that pretend import statement on line #1 of my pseudocode.

PS.我为什么这样做:build_tools文件夹实际上是许多项目共享的git子模块.我试图使每个项目都可以使用一组通用的构建工具,以阻止每个项目维护者重新发明轮子.

PS. Why I'm doing this: The build_tools folder is actually a git submodule shared by many projects. I'm trying to give each project access to a common set of build tooling to stop each project maintainer from reinventing this wheel.

推荐答案

加载共享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.

这篇关于我可以将groovy脚本从相对目录导入Jenkinsfile吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆