我有以下设置:
(剔除)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, $1"
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:没有方法的签名: java.lang.String.call()适用于参数类型: (java.lang.String)值:[Jenkins]
可能的解决方案:wait(),any(),wait(long), split(java.lang.String),take(int),each(groovy.lang.Closure)
那么,可以在不混合Groovy和Bash代码的情况下进行上述操作吗?
答案 0 :(得分:1)
是,请查看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"