[英]Groovy LinkedHashMap returned from a Jenkins shared library is converted to String
我在 Jenkins 共享库中有一个 function,它构建并返回一个 map object( class java.util.LinkedHashMap
):
#!/usr/bin/env groovy
def call(Map config) {
script {
echo "Building nested map"
def MAP_VAR = [:]
MAP_VAR.put("one", [:])
MAP_VAR.put("two", [:])
MAP_VAR.get("one").put("a", "b")
MAP_VAR.get("two").put("c", "d")
echo "Returning: ${MAP_VAR}"
echo "Type: ${MAP_VAR.getClass()}"
return MAP_VAR
}
}
当这个 function 运行日志 output 显示:
Returning: [one:[a:b], two:[c:d]]
Type: class java.util.LinkedHashMap
但是当我调用 function 并将返回值分配给一个变量时,它最终是一个字符串( class java.lang.String
):
#!/usr/bin/env groovy
library identifier: 'library@main',
changelog: false,
retriever: modernSCM([ $class: 'GitSCMSource',
remote: 'git@github.com:org/repo.git',
credentialsId: 'credentials' ])
pipeline {
agent none
stages {
stage('Get map') {
agent any
steps {
script {
env.MAP_VAR = getMapVar()
}
}
}
stage('Check map') {
agent any
steps {
script {
echo "Value: ${env.MAP_VAR}"
echo "Type: ${env.MAP_VAR.getClass()}"
}
}
}
}
}
output 显示:
Value: {one={a=b}, two={c=d}}
Type: class java.lang.String
最终,我试图在 Jenkinsfile 中的多个阶段访问地图的属性。 如果我试试这个:
echo "Value: ${env.MAP_VAR['one']}"
我得到:
groovy.lang.MissingPropertyException: No such property: one for class: java.lang.String
我试过了:
def env.MAP_VAR = getMapVar()
但这导致:
WorkflowScript: 59: unexpected token: def @ line 59, column 21.
def env.MAP_VAR = getMapVar()
^
我也试过:
def Map env.MAP_VAR = getMapVar()
但这导致:
WorkflowScript: 60: unexpected token: Map @ line 60, column 25.
def Map env.MAP_VAR = getMapVar()
^
如何从 function 获取 Map/LinkedHashMap 作为 Map/LinkedHashMap(这将允许我访问 map 内容的属性/值)并将其分配给可在所有阶段使用的全局变量?
def env.MAP_VAR = getMapVar()
这将不起作用,因为您试图在env
map 中定义密钥MAP_VAR
。
def Map env.MAP_VAR = getMapVar()
这也不起作用,因为您试图将env
map 中的MAP_VAR
键定义为def
和MAP
。 这类似于做类似String Integer my_var_name = something()
env.MAP_VAR = getMapVar()
您将返回值作为字符串存储在env
环境变量 map 中。给定代码,Jenkins output 是准确的。
为了实现你想要做的事情,你可以将它存储为一个变量,它会很好地工作。 在下面的示例中,变量进入 Groovy 的脚本绑定并将在下一阶段可用。 您还可以在管道块外定义def MAP_VAR
以获得相同的结果。
#!/usr/bin/env groovy
library identifier: 'library@main',
changelog: false,
retriever: modernSCM([ $class: 'GitSCMSource',
remote: 'git@github.com:org/repo.git',
credentialsId: 'credentials' ])
pipeline {
agent none
stages {
stage('Get map') {
agent any
steps {
script {
MAP_VAR = getMapVar()
}
}
}
stage('Check map') {
agent any
steps {
script {
echo "Value: ${MAP_VAR}"
echo "Type: ${MAP_VAR.getClass()}"
}
}
}
}
}
这将打印
Value: [one:[a:b], two:[c:d]]
Type: class java.util.LinkedHashMap
在第二阶段,
echo "${MAP_VAR['one']}"
将 output
[a:b]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.