Home > other >  How to loop through a YAML list file in Groovy/Jenkins
How to loop through a YAML list file in Groovy/Jenkins

Time:08-08

I have a YAML file template which is set out out like so:

cars:
    - brand: bmw 
      fuel: petrol
      transmission: manual
    - brand: mercedes
      fuel: diesel
      transmission: auto
    - brand: audi
      fuel: electric
      transmission: semi-auto

I am trying to write a function for a Jenkins pipeline that reads through the YAML file, picks up the brand, fuel and transmission value of each array set, and execute commands based on these variables for each set, I assume it would have to be some kind of loop.

I have tried using readYaml however it doesn’t seem to pick up the first “brand” in this case and get errors, not sure if this YAML layout is ideal for my use case

I have tried:

def cars = readYaml file = cars.yaml 
def brand = cars[brand]

Expecting echo brand to return a list of brand names, which I can then use to look up the fuel and transmission values of that brand. However I get this error

groovy.lang.MissingPropertyException: No such property: mkp for class: WorkflowScript

Any ideas?

CodePudding user response:

The proper syntax is

def data = readYaml file: "cars.yaml"
def brand = data.cars[0].brand

You can find the definition (and examples) in the pipeline utility steps documentation.

  • Related