简体   繁体   中英

How to read YAML dict in Jenkins (Groovy)

I have a YAML file:

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?

When I run "println(scan_path.size())" I just get 1, and

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

just returns "dotnet, ServiceCatalog"

You can use snakeyaml library for parsing yaml files.

Similar question is already answered here .

Another tutorial how you can use snakeyaml.

The solution that ended up working for me was changing my YAML config to read like this:

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.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
see: Jenkins Pipeline: How do I use the sh module when traversing a map?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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