简体   繁体   English

如何在 Jenkins (Groovy) 中阅读 YAML 字典

[英]How to read YAML dict in Jenkins (Groovy)

I have a YAML file:我有一个 YAML 文件:

project_name: my-project
project_version: 1.0
scan_path: 
    javascript: Core
    dotnet: Deadbolt
    dotnet: ServiceCatalog

Which I am reading in Jenkins with我在詹金斯读的

data = readYaml file: "Jenkins/config.yml
scan_path = data[scan_path]

however when I check the map it only ever has the last element.但是,当我检查地图时,它只有最后一个元素。

Is my YAML file formatted incorrectly?我的 YAML 文件格式是否不正确?

When I run "println(scan_path.size())" I just get 1, and当我运行“println(scan_path.size())”时,我只得到 1,并且

scan_path.each { k, v ->
                echo "${k}, ${v}"

just returns "dotnet, ServiceCatalog"只返回“dotnet,ServiceCatalog”

You can use snakeyaml library for parsing yaml files. 您可以使用snakeyaml库来解析yaml文件。

Similar question is already answered here . 类似的问题已在这里得到解答。

Another tutorial how you can use snakeyaml. 另一个教程如何使用snakeyaml。

The solution that ended up working for me was changing my YAML config to read like this: 最终为我工作的解决方案是将我的YAML配置更改为如下所示:

project_name: project_name
project_version: 1.0
scan_path: 
  - application: dotnet
    path: Core
  - application: dotnet
    path: Brickburn
  - application: dotnet
    path: ServiceCatalo

Which I saved into a variable 我保存到变量中

data = readYaml file: "Jenkins/config.yml
scan_path = data[scan_path]

And accessed like this: 像这样访问:

scan_path.each { e ->
                echo "Translating ${e.getAt('application')} application 
${e.getAt('path')}"
}

The issue here is that scan_path is a map so to access its key you use scan_path.key and to access its values (in this case a list of maps) use scan_path.value.这里的问题是 scan_path 是一个映射,因此要访问其键,您使用 scan_path.key 并访问其值(在本例中为映射列表)使用 scan_path.value。

scan_path.value.each { k, v ->
    echo "${k}, ${v}"
}

I prefer this instead:我更喜欢这个:

scan_path.value.each { application ->
    echo "${application.key}, ${application.value}"
}

Note: if you use for (x in y){echo "x.key, x.value"} you may get errors注意:如果你使用 for (x in y){echo "x.key, x.value"} 你可能会得到错误
see: Jenkins Pipeline: How do I use the sh module when traversing a map?请参阅: Jenkins Pipeline:遍历地图时如何使用 sh 模块?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM