Home > Net >  Getting YAML value from a variable Groovy
Getting YAML value from a variable Groovy

Time:11-05

I have a YAML file with this structure

key1: value 1 
key2:
  - value 21
  - value 22
key3:
  - key31: value 311
    key32: value 321
    key33: value 331

And I need to access value 331, so I have this code:

@Grab('org.yaml:snakeyaml:1.26')
import org.yaml.snakeyaml.Yaml

 // parse the yaml 
def yaml = new Yaml().load(new FileReader("file.yaml"))
def var1 = "key3"
def var2 = "key33"

println yaml.key3.key33 // this is getting value 331
println yaml.$var1.$var2 // this is getting null

Is there any other way to get this value with given variables?

Note this is part of a Jenkins pipeline.

Thank you so much.

CodePudding user response:

This should work for you. You can simply use readYaml step to read the YAML file within the Jenkins Pipeline

def yaml = readYaml file: 'file.yaml'                

def var1 = "key3"
def var2 = "key33"
println yaml.key3.key33 
println yaml."$var1"."$var2" 

As you can see above I have surrounded your dynamic variables with double quotes, which will tell Jenkins to interpolate them.

  • Related