我在 Jenkins 管道中遇到了一个问题,在使用
java.io.NotSerializableException
时,我得到了 XmlUtil.serialize
。
代码片段:
de updateFile() {
def file = readFile(file: filePath)
def xml = new XmlSlurper().parseText(file)
... update XML
def modifiedXml = XmlUtil.serialize(xml)
writeFile(file: filePath, text: modifiedXml)
}
pipeline {
agent {
label 'agent-1'
}
stages {
stage('Update File') {
steps {
updateFile()
}
}
}
}
错误信息
导致:java.io.NotSerializedException:groovy.util.slurpersupport.NodeChild
我正在另一台服务器上作为 Jenkins 代理运行它。我也尝试了
@NonCPS
,但它也不起作用。那么有人可以帮我解决这个问题吗?预先感谢。
根据 https://www.jenkins.io/doc/book/pipeline/cps-method-mismatches/,你 不得在
@NonCPS
-ed 方法中使用管道步骤——这可能是
这个解决方案对你来说失败的原因。
但是,问题确实与我的CPS改造有关 思考。但是,您可以解决这个问题,甚至无需使用
@NonCPS
。将与 XML 相关的操作移至单独的函数中
会成功的。以下确实可以正常工作:
import groovy.xml.XmlUtil
filePath = 'test.xml'
def updateFile2(file) {
def xml = new XmlSlurper().parseText(file)
//... update XML
// e.g.
// xml.bar = 'baz'
def modifiedXml = XmlUtil.serialize(xml)
return modifiedXml
}
def updateFile() {
def file = readFile(file: filePath)
def modifiedXml = updateFile2(file)
writeFile(file: filePath, text: modifiedXml)
}
pipeline {
agent {
label 'agent-1'
}
stages {
stage('Update File') {
steps {
updateFile()
}
}
}
}
显然,当您混合管道步骤时,CPS 转换会失败 和同一函数中的 XML 方法;将调用放入不同的函数可以避免这个问题。
我看到你说
@NonCPS
不起作用,所以我的建议是创建一个单独的 bash 脚本并在管道内执行它,所以这里是示例代码,
write_to_xml.sh
if [ "$#" -ne 1 ]; then
echo "Error: XML file not found!"
echo "Usage: $0 <path_to_xml_file>"
exit 1
fi
xml_file="$1"
cat > "$xml_file"
正在筹备中,
def updateFile() {
def file = readFile(file: filePath)
def xml = new XmlSlurper().parseText(file)
... update XML
return XmlUtil.serialize(xml)
}
pipeline {
agent {
label 'agent-1'
}
stages {
stage('Update File') {
steps {
script {
def modifiedXml = updateFile()
sh “””
chmod +x write_to_xml.sh
echo '${modifiedXml}' | ./write_to_xml.sh path/to/the/xml/file
"""
}
}
}
}
}
希望这对您有帮助!