如何在YAML中引用其他键值并实现字符串拼接?
YAML中实现值拼接与多值组合的解决方案
原生YAML本身只是一种数据序列化格式,没有内置的字符串拼接或多值组合能力——锚点别名只能直接复制值,确实满足不了你的需求。要实现你要的效果,得借助外部工具或者支持模板/变量的YAML扩展方案,下面是几种实用的方法:
1. 用yq命令行工具处理
yq是专门用来处理YAML的命令行工具,支持变量引用和字符串操作。假设你的原YAML文件叫input.yaml,执行下面的命令就能生成带Field2的目标YAML:
yq eval ' .Field2.NewKey1 = .Field1.Key1 + "_test" | .Field2.NewKey2 = .Field1.Key2 + "_test" | .Field2.NewKey3 = .Field1.Key1 + "_" + .Field1.Key2 ' input.yaml
执行后会直接输出包含Field2的完整YAML内容,你也可以加-i参数直接修改原文件。
2. 用Jinja2模板渲染
把需要生成的YAML写成Jinja2模板,再通过渲染得到最终内容。比如先写一个模板文件template.yaml:
Field1: Key1: A1 Key2: A2 Field2: NewKey1: {{ Field1.Key1 }}_test NewKey2: {{ Field1.Key2 }}_test NewKey3: {{ Field1.Key1 }}_{{ Field1.Key2 }}
然后用Python的Jinja2库渲染模板:
from jinja2 import Template with open('template.yaml', 'r') as f: template_content = f.read() template = Template(template_content) rendered_yaml = template.render(Field1={'Key1': 'A1', 'Key2': 'A2'}) print(rendered_yaml)
运行这段代码就能得到你想要的YAML结果。
3. 借助Ansible的YAML变量能力
如果你用Ansible,它的YAML语法支持变量引用和字符串拼接。在playbook或者变量文件里可以这么写:
vars: Field1: Key1: A1 Key2: A2 Field2: NewKey1: "{{ Field1.Key1 }}_test" NewKey2: "{{ Field1.Key2 }}_test" NewKey3: "{{ Field1.Key1 }}_{{ Field1.Key2 }}"
当Ansible加载这些变量时,会自动把拼接后的结果解析出来。
简单来说,原生YAML做不到这种计算,必须靠外部工具或者带扩展能力的YAML使用场景来实现。
内容的提问来源于stack exchange,提问作者Ling Guo
相关产品推荐
相关产品推荐

