我可以使用Groovy以外的其他语言在Jenkins Pipeline中创建“共享库"吗?

问题描述:

我有执行REST命令并处理结果的python脚本.我希望该脚本可被不同的Jenkins Pipelines使用,我通过Jenkins官方文档发现的一种方式是使用共享库",而这些示例(以及我在网上找到的其他示例)也使用Groovy.

I have python script which does a REST command and processes the result. I want this script to be used by different Jenkins Pipelines, one way I found through Jenkins official documentation is to use 'Shared library' and that examples(also others example which I found online) they use the Groovy.

我的问题是,是否可以用Groovy以外的其他语言创建共享库?对于前. python?

My question is, is it possible to create a shared lib in other language than Groovy? For ex. python?

简短答案为否.所有Jenkins Pipeline执行(现在)都是专门的Groovy,可通过 管道执行:Groovy 插件,该插件使用 Groovy CPS 库执行编译和运行时转换.詹金斯管道生态系统与Groovy紧密相关.将来可能会改变,但是现在不值得付出努力.

Short answer is no. All Jenkins Pipeline execution (right now) is specialized Groovy that is executed with the Pipeline: Groovy plugin that uses the Groovy CPS library to perform the compilation and runtime transformations. The Jenkins Pipeline ecosystem is very heavily tied to Groovy. That may change in the future, but is not what worth the effort right now.

如果您确实想在共享库中使用Python代码,则可以做的是将其放入库的resources/文件夹中,然后使用管道步骤进行加载和执行.没有说明您为什么要使用Python的用例(或您正在尝试的问题解决),因此下面是一个人为的示例:

What you can do, if you really want to use Python code in a Shared Library, is to put it in the resources/ folder of the library and then load and execute it with pipeline steps. Your use case for why you want to use Python is not stated (or what problem you are trying to solve), so below is a contrived example:

  • 在您的共享库中:resources/com/mkobit/sharedlib/my_file.py

#!/usr/bin/env python
print("Hello")

  • 共享库 Groovy全局变量:vars/mkobitVar.groovy

  • Shared Library Groovy global variable: vars/mkobitVar.groovy

    def runMyPython() {
      final pythonContent = libraryResource('com/mkobit/sharedlib/my_file.py')
      // There are definitely better ways to do this without having to write to the consumer's workspace
      writeFile(file: 'my_file.py', text: pythonContent)
      sh('chmod +x my_file.py && ./my_file.py')
    }
    

  • 在消费者中

  • In a consumer

    @Library('mkobitLib') _
    
    node('python') {
       mkobitVar.runMyPython()
    }