【发布时间】:2021-02-22 14:39:32
【问题描述】:
我一直在使用 ruamel yaml 来编辑我的 YAML 文件并将它们转储回去。我需要帮助来了解如何保持与原始文件相同的结构,因为我所做的只是复制、编辑和重新编写它。
例如,这是原始文件:
ElasticLoadBalancingV2Listener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ElasticLoadBalancingV2LoadBalancer
Port: !FindInMap [NLBPorts, Port1, Port]
Protocol: "TCP"
DefaultActions:
-
Order: 1
TargetGroupArn: !Ref ElasticLoadBalancingV2TargetGroup1
Type: "forward"
新文件看起来不一样:
ElasticLoadBalancingV2Listener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ElasticLoadBalancingV2LoadBalancer
Port: !FindInMap [NLBPorts, Port1, Port]
Protocol: "TCP"
DefaultActions:
- Order: 1
TargetGroupArn: !Ref ElasticLoadBalancingV2TargetGroup1
Type: "forward"
最大的问题是我使用了 ruamel 必须解决的各种技巧,但每次 yaml 的某些不同部分都会中断。
这是我的功能:
def editEndpointServiceTemplate(endpoint_service_template_path):
yaml = YAML()
yaml.preserve_quotes = True
# yaml.compact(seq_seq=False, seq_map=False)
# yaml.indent(mapping=4, sequence=3, offset=0)
#Load yaml file
with open(endpoint_service_template_path) as fp:
data = yaml.load(fp)
#Edit the yaml
data['Description'] = "CloudFormation"
#Write new yaml file
with open(endpoint_service_template_path, 'w') as fp:
yaml.dump(data, fp)
正如您在注释命令中看到的那样,我对设置进行了修改,但找不到最佳位置。
【问题讨论】:
-
没有简单的方法可以在 ruamel.yaml 中的单独行上获取序列指示符 (
-)(并且您不能在此类指示符和序列项之间添加注释,这将相当于对同一件事)。您应该尝试yaml.indent(mapping=4, sequence=4, offset=2)来获取您的意见,但除此之外。 -
感谢 Anthon,我一直在关注这个社区中的所有 cmets,希望您能对我的帖子发表评论。糟透了,我对 ruamel 无能为力。您能否提出一种不同的方法来实现我想要做的事情?
标签: ruamel.yaml