我正在尝试编辑一个yaml文件,但当我编写新文件时,整个文件结构都乱七八糟。
换行符是错误的,一些缩进也是错误的,它甚至因为某些原因删除了我的一些参数。下面是一个例子:
在此之前
AWSTemplateFormatVersion: "2010-09-09"
Metadata:
Generator: "user"
Description: "CloudFormation blah blah"
Parameters:
VPCEndpointServiceServiceName:
Description: VPCEndpointServiceServiceName
Type: String
Mappings:
PrivateLink:
EndPoint:
EndPointName: test
EndPointVpcId: vpc-123
SecurityGroupIds: sg-123
SubnetId1: subnet-123
SubnetId2: subnet-123
Resources:
EC2VPCEndpoint:
Type: "AWS::EC2::VPCEndpoint"
Properties:
VpcEndpointType: "Interface"
VpcId: !FindInMap [PrivateLink, EndPoint, EndPointVpcId]
ServiceName: !Ref VPCEndpointServiceServiceName
SubnetIds:
- !FindInMap [PrivateLink, EndPoint, SubnetId1]
- !FindInMap [PrivateLink, EndPoint, SubnetId2]
PrivateDnsEnabled: false
SecurityGroupIds:
- !FindInMap [PrivateLink, EndPoint, SecurityGroupIds]之后
AWSTemplateFormatVersion: '2010-09-09'
Metadata:
Generator: user
Description: CloudFormation blah blah
Parameters:
VPCEndpointServiceServiceName:
Description: VPCEndpointServiceServiceName
Type: String
Mappings:
PrivateLink:
EndPoint:
EndPointName: test
EndPointVpcId: vpc-123
SecurityGroupIds: sg-123
SubnetId1: subnet-123
SubnetId2: subnet-123
Resources:
EC2VPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcEndpointType: Interface
VpcId:
- PrivateLink
- EndPoint
- EndPointVpcId
ServiceName: VPCEndpointServiceServiceName
SubnetIds:
- - PrivateLink
- EndPoint
- SubnetId1
- - PrivateLink
- EndPoint
- SubnetId2
PrivateDnsEnabled: 'false'
SecurityGroupIds:
- - PrivateLink
- EndPoint
- SecurityGroupIds真正奇怪的是,它还删除了像!FindInMap和!Ref这样的参数。
下面是我的函数:
def editEndpointTemplate(endpoint_tempplate_path):
#read yaml file
with open(endpoint_tempplate_path) as file:
data = yaml.load(file, Loader=yaml.BaseLoader)
data['Mappings']['PrivateLink']['EndPoint']['EndPointName'] = "New Name"
#write yaml file and overwrite old one.
with open(endpoint_tempplate_path, 'w') as file:
yaml.dump(data, file, sort_keys=False)我想完全保留文件的原样,因为我所做的只是更新一些密钥。
我对按字母排序的文件也有问题,但一个简单的sort_keys=False解决了这个问题。我认为PyYaml的任何其他属性都可以解决这个问题,但我搞不清楚。
任何帮助都将不胜感激。
发布于 2021-02-18 16:09:47
已找到解决方法。我没有使用PyYaml或cfn-tools,而是使用了ruamel.yaml。
import sys
from ruamel.yaml import YAML
def editEndpointTemplate(endpoint_template_path):
yaml = YAML()
yaml.indent(mapping=3)
#Load yaml file
with open(endpoint_template_path) as fp:
data = yaml.load(fp)
#Change data
data['Mappings']['PrivateLink']['EndPoint']['EndPointName'] = service_name
#Dump it back to the same file
# yaml.dump(data, sys.stdout)
with open(endpoint_template_path, 'w') as fp:
yaml.dump(data, fp)即使在编辑之后,新的YAML文件也会像我的模板一样被保留。
https://stackoverflow.com/questions/66240803
复制相似问题