【发布时间】:2021-05-20 06:35:03
【问题描述】:
我正在尝试编辑一个 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 的任何其他属性都可以解决此问题,但无法解决。
任何帮助将不胜感激。
【问题讨论】:
-
@KrishnaChaurasia 谢谢。这确实是迄今为止我发现的最接近的东西。虽然结构仍然不一样:(