Below pipeline codes works well:
pipeline {
agent {
label "test_agent"
}
stages {
stage("test") {
steps {
script {
sh "echo 'number=${BUILD_NUMBER}' >log"
if (fileExists('log')) {
load 'log'
retVal = "${number}"
}
echo "${retVal}"
}
}
}
}
}
However, when I tried to put the logic of read file to a lib(named getNumber.groovy
) and call it in pipeline, like this:
getNumber.groovy
def call() {
def retVal
if (fileExists('log')) {
load 'log'
retVal = "${number}"
}
return retVal
}
This is how the pipeline (test.groovy) call this lib:
@Library('lib') _
pipeline {
agent {
label "test_agent"
}
stages {
stage("test") {
steps {
script {
sh "echo 'number=${BUILD_NUMBER}' >log"
def retVal = getNumber()
echo "${retVal}"
}
}
}
}
}
It always fail with below error:
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: number for class: getNumber
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:34)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
Any suggestion? How to fix it if I want to encapsulate the logic in a lib?
[Edit] If I change this segment
load 'log'
retVal = "${number}"
to this:
def matcher = readFile('log') =~ '^number=(.+)'
retVal=matcher ? matcher[0][1] : null
it works. But I just curious why the previous one can't work.