简体   繁体   English

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

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

I have the following setup:我有以下设置:

(Stripped out) Jenkinsfile: (剥离)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: my-custom-library/resources/com/org/scripts/print-hello.sh:

#!/bin/bash

echo "Hello, $1"

my-custom-library/vars/printHello.groovy:我的自定义库/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))
}

I expect Hello, Jenkins , but it throws the following exception:我希望Hello, Jenkins ,但它抛出以下异常:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (java.lang.String) values: [Jenkins] groovy.lang.MissingMethodException:无方法签名:java.lang.String.call() 适用于参数类型:(java.lang.String) 值:[Jenkins]

Possible solutions: wait(), any(), wait(long), split(java.lang.String), take(int), each(groovy.lang.Closure)可能的解决方案:wait()、any()、wait(long)、split(java.lang.String)、take(int)、each(groovy.lang.Closure)

So, is it possible to do something like described above, without mixing Groovy and Bash code?那么,是否可以在不混合 Groovy 和 Bash 代码的情况下执行上述操作?

Yes, check out withEnv是的,使用Env查看

The example they give looks like;他们给出的例子看起来像;

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

More applicable to you:更适用于您:

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

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

Prints:印刷:

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

Using that, you can pass it in using a scoped named variable, something like使用它,您可以使用作用域命名变量传递它,例如

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM