我正在尝试对Jenkins管道中的对象列表进行排序。我在本地或Jenkins内部运行代码得到的结果不同:
pipeline {
agent any
stages {
stage('default'){
steps {
script {
@NonCPS
def nonCpsTest = {
def list = [
['CreationDate': '200'],
['CreationDate': '300'],
['CreationDate': '100'],
]
def rval = list.sort { it['CreationDate'] }
echo "Rval=$rval"
echo "List=$list"
}
nonCpsTest()
}
}
}
}
}
当我使用groovy shell(groovysh
)在本地执行此脚本时,结果是
groovy:000> list = [[ 'CreationDate':200 ], [ 'CreationDate':300 ], [ 'CreationDate':100 ]]
===> [[CreationDate:200], [CreationDate:300], [CreationDate:100]]
groovy:000> rval = list.sort { it['CreationDate'] }
===> [[CreationDate:100], [CreationDate:200], [CreationDate:300]]
groovy:000> list
===> [[CreationDate:100], [CreationDate:200], [CreationDate:300]]
groovy:000> list == rval
===> true
在Jenkins服务器上我正在关注
[Pipeline] {
[Pipeline] stage
[Pipeline] { (default)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Rval=300
[Pipeline] echo
List=[[CreationDate:200], [CreationDate:300], [CreationDate:100]]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Jenkins工作流使列表无论如何都是不可变的,或者覆盖sort
方法,如果是这样,如何在Jenkins管道代码中进行列表排序?
答案 0 :(得分:4)
您将nonCpsTest
声明为变量并且它引用了闭包的问题,因此@NonCPS
在这种情况下不起作用
以下变体可以正常工作:
@NonCPS
def nonCpsTest() {
def list = [
['CreationDate': '200'],
['CreationDate': '300'],
['CreationDate': '100'],
]
def rval = list.sort{ it['CreationDate'] }
echo "Rval=$rval"
echo "List=$list"
}
node{
nonCpsTest()
}