0

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?

Harshit Goel
  • 175
  • 1
  • 3
  • 13
  • how about calling the readYaml step on it? If you surround it with a try-catch you can check if it could be parsed – smelm Oct 12 '20 at 11:41
  • I tried : datas = readYaml (file: 'demo.yaml') . In input multiline parameter, I gave some text which was not formatted in yaml, but still above readYaml function returned the output text. It should have thrown exception if the format of yaml is not correct. Isn't it? – Harshit Goel Oct 12 '20 at 13:55

1 Answers1

0

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.

zett42
  • 25,437
  • 3
  • 35
  • 72
  • If i have to validate say any spec file that is being loaded through a parameter in Jenkins job and validate it against a schema validation file which i already have in my repo, how do i write this code then? I want any spec file that i put in my parameter to be validated first before my job is run and if it violates the validation, it should throw error in my logger. – Pallab Feb 07 '21 at 04:35