How to validate if a multiline string is a valid YAML or not?

2.6k views Asked by At

I have a scripted Jenkins pipeline where I am using a multiline string parameter with name CUSTOM_YAML.

enter image description here

While building the job, I am giving the input of that parameter as yaml text and convert it to a .yaml file :

writeFile file: 'demo.yaml', text: params.DEMO_YAML

Now, I want to validate if the format of this yaml file (demo.yaml) is correct or not.

Note : Like there are multiple tools to do this manually (e.g https://codebeautify.org/yaml-validator ) where we can paste the text and click on validate and . But how can I achieve this in my Jenkins pipeline?

1

There are 1 answers

1
zett42 On

You could use the build-in readYaml step to do basic syntax validation. For checking data validity, you could use assertions.

If all you need to do is fail the build on any error, you are already done. Errors will be logged automatically when readYaml or assert fails. If you need to handle errors specially or want to improve assertion error messages, wrap the code in try/catch (caveat: assertions must be catched as AssertionError).

node {
    def CUSTOM_YAML = '''\
        foo: "bar"
        baz:
        - "baz1"
        - "baz2"
    '''
     
    try {
        // Parse the YAML. Does basic syntax checking.
        def config = readYaml text: CUSTOM_YAML
     
        // Validate YAML data.
        assert config.foo == 'bar'     
        assert config.baz.size() >= 2
    }
    catch( Exception e ){
        // Handle syntax error        
    }
    catch( AssertionError e ){
        // Handle data validation error (assert's)        
    }
}

This is an example of a scripted pipeline. If you have a declarative pipeline, you can put the code into steps{script{ /*the code*/ }} block.