How to Read a YAML or JSON Config in a Jenkins Pipeline
readYaml and readJSON (Pipeline Utility Steps plugin) parse a file or string into a Groovy map you can drive the build from.
Install Pipeline Utility Steps, then call readYaml(file: '...') or readJSON(file: '...'). The result is a normal Groovy map/list you can index to configure stages.
Steps
- Install the Pipeline Utility Steps plugin.
- Call
readYaml(file: 'config.yml')(orreadJSON). - Index the returned map to read values into the build.
Jenkinsfile
Jenkinsfile
pipeline {
agent any
stages {
stage('Configure') {
steps {
script {
def cfg = readYaml(file: 'ci/config.yml')
def services = cfg.services
echo "Deploying ${services.join(', ')} to ${cfg.environment}"
}
}
}
}
}Gotchas
- Maps and lists from readYaml are not serializable across a CPS step; read inside one script block.
- Use
text:instead offile:to parse a string you already have in a variable.
Related guides
How to Guard a Stage With fileExists in JenkinsRun a Jenkins step only when a file is present using the fileExists step inside a when expression or an if, s…
How to Build Dynamic Parallel Branches in JenkinsGenerate Jenkins parallel branches at runtime by building a map of closures and passing it to the parallel st…