Jenkins 共享库:是否可以将参数传递给作为 'libraryResource' 导入的 shell 脚本?

Jenkins Shared Libraries: is it possible to pass arguments to shell scripts imported as 'libraryResource'?

我有以下设置:

(剥离)Jenkinsfile:

@Library('my-custom-library') _

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                printHello name: 'Jenkins'
            }
        }
    }
}

my-custom-library/resources/com/org/scripts/print-hello.sh:

#!/bin/bash

echo "Hello, "

my-custom-library/vars/printHello.groovy:

def call(Map parameters = [:]) {
    def printHelloScript = libraryResource 'com/org/scripts/print-hello.sh'
    def name = parameters.name
    //the following line gives me headaches
    sh(printHelloScript(name))
}

我期望 Hello, Jenkins,但它抛出以下异常:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (java.lang.String) values: [Jenkins]

Possible solutions: wait(), any(), wait(long), split(java.lang.String), take(int), each(groovy.lang.Closure)

那么,是否可以在不混合 Groovy 和 Bash 代码的情况下执行上述操作?

是的,查看 withEnv

他们给出的例子看起来像;

node {
  withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
  }
}

更适合你:

// resources/test.sh
echo "HI here we are - $PUPPY_DOH --"

// vars/test.groovy
def call() {
   withEnv(['PUPPY_DOH=bobby']) {
    sh(libraryResource('test.sh'))
  }
}

打印:

[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] libraryResource
[Pipeline] sh
+ echo HI here we are - bobby --
HI here we are - bobby --
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }

使用它,您可以使用范围命名变量传递它,例如

def call(Map parameters = [:]) {
    def printHelloScript = libraryResource 'com/org/scripts/print-hello.sh'
    def name = parameters.name
    withEnv(['NAME=' + name]) { // This may not be 100% syntax here ;)
    sh(printHelloScript)
}

// print-hello.sh
echo "Hello, $name"