是否可以将jenkins管道编译到jar中以供共享库使用?

时间:2020-06-06 15:20:21

标签: jenkins groovy jenkins-pipeline

这是我的问题,我想将jenkins管道编译到jar中以供共享库导入和使用,以便保护我的jenkins管道源代码。

众所周知,共享库可以使用第三方库,我编写了自己的第三方库并编译到jar中,然后使共享库导入和使用它,但是我不知道如何使用jenkins管道步骤在我自己的第三方库中。

这就是我所做的:

  1. 我创建自己的用groovy语言编写的第三方库,并将其编译为jar,源代码如下:
// src/main/groovy/DemoLibrary.groovy

// I want this library to run jenkins pipeline step
package com.example

import org.jenkinsci.plugins.workflow.steps.durable_task.ShellStep

class DemoLibrary {
    // this function can run command in jenkins master node
    // runShell(script: script, cwd: cwd)
    // return: process
    def runShell(args) {
        def cmd = args.script
        if (args.cwd && args.cwd != "") {
            cmd = "cd ${args.cwd} && ${cmd}"
        }
        def cmds = ['bash', '-c', cmd]
        def proc = cmds.execute()
        proc.waitFor()
        if (proc.exitValue() != 0) {
            throw new Exception("[ERROR] run shell error: ${proc.err.text}")
        }
        return proc
    }

    // i want this function to call jenkins "sh" step, but i don't know how to get StepContext in shared library
    // runStepShell(script: script, context: context)
    // return: stepExecution
    def runStepShell(args) {
        def shellStep = new ShellStep(args.script)
        def stepExecution = shellStep.start(args.context)
        retrun stepExecution
    }
}
  1. 我创建共享库,源代码如下:
// vars/demoLibrary.groovy

@Grab('com.example:demo-library:0.1.0')

@Field demoLib = new DemoLibrary()

def demoStage() {
    docker.image("alpine:latest").inside("--user 1000:1000") {
        def script = "hostname"
        // run step "sh" can show the hostname of the docker container
        sh script: script
        // but run runShell show the hostname of the jenkins master
        def proc = demoLib.runShell(script: script)
        echo "${proc.text}"

        // how can i get the docker stepContext to make my third-party library to run jenkins sh step?
        demoLib.rrunStepShell(script: script, context: context)
    }
}

是否可以在自己的第三方库中调用jenkins步骤?这让我困扰了好几天。谢谢

0 个答案:

没有答案