简体   繁体   English

在 Jenkins Groovy 管道中合并两个 yaml 文件

[英]Merging two yaml files in a Jenkins Groovy pipeline

In my Jenkins pipeline, I've got a yaml file that I need to apply to multiple environments, and separate environment specific yaml files that I'd like to inject or merge into the default file and write as a new file.在我的 Jenkins 管道中,我有一个需要应用于多个环境的 yaml 文件,以及我想注入或合并到默认文件中并作为新文件写入的单独环境特定的 yaml 文件。

I've looked at readYaml and writeYaml here: https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/ But I'm not finding a good way of merging multiple files.我在这里查看了 readYaml 和 writeYaml: https ://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/ 但我没有找到合并多个文件的好方法。

A simple example of what I'd like to achieve is here:我想要实现的一个简单示例如下:

# config.yaml
config: 
   num_instances: 3
   instance_size: large
# dev-overrides.yaml
config:
    instance_size: small
# dev-config.yaml (desired output after merging dev-overrides.yaml in config.yaml)
config
    num_instances: 3
    instance_size: small

The Jenkins implementation of readYaml uses SnakeYAML as processor and supports YAML 1.1. readYaml的 Jenkins 实现使用SnakeYAML作为处理器并支持 YAML 1.1。 You could possibly use the merge operator to accomplish your goal.您可以使用合并运算符来实现您的目标。 But the merge operator has been removed in YAML 1.2.但合并运算符已在 YAML 1.2 中删除。 Thus I would not advise using this feature even it's currently available.因此,即使目前可用,我也不建议使用此功能。

I would instead merge the objects with some Groovy code like this:我会将对象与一些 Groovy 代码合并,如下所示:

Map merge(Map... maps) {
    Map result = [:]
    maps.each { map ->
        map.each { k, v ->
            result[k] = result[k] instanceof Map ? merge(result[k], v) : v
        }
    }

    result
}


def config = readYaml text: """
config: 
   num_instances: 3
   instance_size: large
"""

def configOverrides = readYaml text: """
config:
    instance_size: small
"""

// Showcasing what the above code does:
println "merge(config, configOverrides): " + merge(config, configOverrides)
// => [config:[num_instances:3, instance_size:small]]
println "merge(configOverrides, config): " + merge(configOverrides, config)
// => [config:[instance_size:large, num_instances:3]]

// Write to file
writeYaml file: 'dev-config.yaml', data: merge(config, configOverrides)

Inspired by https://stackoverflow.com/a/27476077/1549149灵感来自https://stackoverflow.com/a/27476077/1549149

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM