我可以使用 Groovy 以外的其他语言在 Jenkins Pipeline 中创建 'shared library' 吗?

Can I create 'shared library' in Jenkins Pipeline in other language than Groovy?

我有 python 脚本执行 REST 命令并处理结果。我希望这个脚本被不同的 Jenkins Pipelines 使用,我通过 Jenkins 官方文档找到的一种方法是使用 'Shared library' 和那个例子(还有我在网上找到的其他例子)他们使用 Groovy.

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

简短的回答是否定的。所有 Jenkins Pipeline 执行(现在)都是专门的 Groovy,它使用 Pipeline: Groovy plugin that uses the Groovy CPS 库执行以执行编译和运行时转换。 Jenkins Pipeline 生态系统与 Groovy 紧密相关。这在未来可能会改变,但现在不值得付出努力。

如果你真的想在共享库中使用Python代码,你可以做的是将它放在resources/文件夹中库,然后使用流水线步骤加载和执行它。你为什么要使用 Python 的用例没有说明(或 what problem you are trying to solve),所以下面是一个人为的例子:

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

    #!/usr/bin/env python
    print("Hello")
    
  • 共享库 Groovy全局变量: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')
    }
    
  • 在消费者中

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