You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Pipeline编辑YAML时如何保留多行值的|符号

解决Jenkins流水线中修改YAML时保留多行块标量(|)的问题

你当前的写法会把fruits.yaml对应的多行字符串解析成Map对象,赋值回去时writeYaml会直接将Map序列化为嵌套的YAML结构,自然丢失了原有的块标量符号|。以下是两种可行的解决方法:

方法一:手动生成带块标量格式的字符串

def firstFile = readYaml file: "firstFile.yaml"
// 解析内部的fruits.yaml内容为Map
def secondFile = readYaml text: firstFile.stringData.'fruits.yaml'
// 修改目标字段
secondFile.fruits.small.berries.color = 'purple'
// 将修改后的Map转回YAML字符串
def updatedFruitsContent = writeYaml data: secondFile, returnText: true
// 包装成带|的块标量格式,注意匹配缩进
firstFile.stringData.'fruits.yaml' = "|\n    ${updatedFruitsContent.replace('\n', '\n    ')}"
// 写入最终文件
writeYaml overwrite: true, file: 'firstFile.yaml', data: firstFile

方法二:用SnakeYAML精准控制输出格式

Jenkins的YAML工具底层依赖SnakeYAML,直接调用它的API可以更精准控制格式:

import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml

def firstFile = readYaml file: "firstFile.yaml"
def secondFile = readYaml text: firstFile.stringData.'fruits.yaml'
secondFile.fruits.small.berries.color = 'purple'

// 配置输出为块风格,设置缩进
def dumperOpts = new DumperOptions()
dumperOpts.defaultFlowStyle = DumperOptions.FlowStyle.BLOCK
dumperOpts.indent = 4
def yaml = new Yaml(dumperOpts)

// 生成格式化后的YAML字符串
def updatedFruitsContent = yaml.dump(secondFile).trim()
// 拼接块标量符号和对应缩进
firstFile.stringData.'fruits.yaml' = "|\n    ${updatedFruitsContent.replace('\n', '\n    ')}"

writeYaml overwrite: true, file: 'firstFile.yaml', data: firstFile

两种方法的核心逻辑一致:先修改内部YAML内容,再将其重新序列化为字符串,最后手动添加块标量符号|和匹配的缩进,确保外层YAML能识别这是一个多行字符串块。

内容的提问来源于stack exchange,提问作者Shawney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:36:35