我正在尝试使用 ruamel.yaml 使用 python 动态修改 AWS CloudFormation 模板。我添加了以下代码以使 safe_load 与 CloudFormation 函数(例如 !Ref
)一起使用。但是,当我将它们转储出来时,那些带有 !Ref (或任何其他函数)的值将用引号引起来。 CloudFormation 无法识别这一点。
参见下面的示例:
import sys, json, io, boto3
import ruamel.yaml
def funcparse(loader, node):
node.value = {
ruamel.yaml.ScalarNode: loader.construct_scalar,
ruamel.yaml.SequenceNode: loader.construct_sequence,
ruamel.yaml.MappingNode: loader.construct_mapping,
}[type(node)](node)
node.tag = node.tag.replace(u'!Ref', 'Ref').replace(u'!', u'Fn::')
return dict([ (node.tag, node.value) ])
funcnames = [ 'Ref', 'Base64', 'FindInMap', 'GetAtt', 'GetAZs', 'ImportValue',
'Join', 'Select', 'Split', 'Split', 'Sub', 'And', 'Equals', 'If',
'Not', 'Or' ]
for func in funcnames:
ruamel.yaml.SafeLoader.add_constructor(u'!' + func, funcparse)
txt = open("/space/tmp/a.template","r")
base = ruamel.yaml.safe_load(txt)
base["foo"] = {
"name": "abc",
"Resources": {
"RouteTableId" : "!Ref aaa",
"VpcPeeringConnectionId" : "!Ref bbb",
"yourname": "dfw"
}
}
ruamel.yaml.safe_dump(
base,
sys.stdout,
default_flow_style=False
)
输入文件是这样的:
foo:
bar: !Ref barr
aa: !Ref bb
输出如下:
foo:
Resources:
RouteTableId: '!Ref aaa'
VpcPeeringConnectionId: '!Ref bbb'
yourname: dfw
name: abc
请注意,“!Ref VpcRouteTable”用单引号引起来。 CloudFormation 不会识别这一点。有没有办法配置转储器,以便输出如下:
foo:
Resources:
RouteTableId: !Ref aaa
VpcPeeringConnectionId: !Ref bbb
yourname: dfw
name: abc
我尝试过的其他事情:
- pyyaml 库,工作原理相同
- 使用 Ref::代替 !Ref,可以实现 相同
最佳答案
本质上,您调整加载器,以加载标记(标量)对象,就好像它们是映射一样,其中标记是键,值是标量。但是您没有做任何事情来区分从此类映射加载的 dict 与从普通映射加载的其他字典,也没有任何特定代码来表示此类映射以“取回标签” 。
当您尝试使用标签“创建”标量时,您只需创建一个以感叹号开头的字符串,并且需要转储引号以将其与真实标记节点区分开来。
使这一切变得模糊的是,您的示例通过分配给 base["foo"]
来覆盖加载的数据,因此您可以从 safe_load
派生出唯一的东西,以及之前的所有代码,它不会引发异常。 IE。如果省略以 base["foo"] = {
开头的行,您的输出将如下所示:
foo:
aa:
Ref: bb
bar:
Ref: barr
其中 Ref: bb
与普通转储的字典无法区分。如果您想探索这条路线,那么您应该创建一个子类 TagDict(dict)
,并让 funcparse
返回该子类,还添加一个 该子类的代表者
从键重新创建标签,然后转储值。一旦有效(往返等于输入),您可以执行以下操作:
"RouteTableId" : TagDict('Ref', 'aaa')
如果您这样做,除了删除未使用的库之外,还应该更改代码以关闭代码中的文件指针 txt
,因为这可能会导致问题。您可以使用 with
语句优雅地完成此操作:
with open("/space/tmp/a.template","r") as txt:
base = ruamel.yaml.safe_load(txt)
(我还会省略 "r"
(或在其前面加一个空格);并将 txt
替换为更合适的变量名称,表明这是一个(输入)文件指针)。
您的 funcnames
中还有两次 'Split'
条目,这是多余的。
通过使用匹配任何标签并具有三种基本类型来覆盖标量、映射和序列的多构造函数
,可以实现更通用的解决方案。
import sys
import ruamel.yaml
yaml_str = """\
foo:
scalar: !Ref barr
mapping: !Select
a: !Ref 1
b: !Base64 A413
sequence: !Split
- !Ref baz
- !Split Multi word scalar
"""
class Generic:
def __init__(self, tag, value, style=None):
self._value = value
self._tag = tag
self._style = style
class GenericScalar(Generic):
@classmethod
def to_yaml(self, representer, node):
return representer.represent_scalar(node._tag, node._value)
@staticmethod
def construct(constructor, node):
return constructor.construct_scalar(node)
class GenericMapping(Generic):
@classmethod
def to_yaml(self, representer, node):
return representer.represent_mapping(node._tag, node._value)
@staticmethod
def construct(constructor, node):
return constructor.construct_mapping(node, deep=True)
class GenericSequence(Generic):
@classmethod
def to_yaml(self, representer, node):
return representer.represent_sequence(node._tag, node._value)
@staticmethod
def construct(constructor, node):
return constructor.construct_sequence(node, deep=True)
def default_constructor(constructor, tag_suffix, node):
generic = {
ruamel.yaml.ScalarNode: GenericScalar,
ruamel.yaml.MappingNode: GenericMapping,
ruamel.yaml.SequenceNode: GenericSequence,
}.get(type(node))
if generic is None:
raise NotImplementedError('Node: ' + str(type(node)))
style = getattr(node, 'style', None)
instance = generic.__new__(generic)
yield instance
state = generic.construct(constructor, node)
instance.__init__(tag_suffix, state, style=style)
ruamel.yaml.add_multi_constructor('', default_constructor, Loader=ruamel.yaml.SafeLoader)
yaml = ruamel.yaml.YAML(typ='safe', pure=True)
yaml.default_flow_style = False
yaml.register_class(GenericScalar)
yaml.register_class(GenericMapping)
yaml.register_class(GenericSequence)
base = yaml.load(yaml_str)
base['bar'] = {
'name': 'abc',
'Resources': {
'RouteTableId' : GenericScalar('!Ref', 'aaa'),
'VpcPeeringConnectionId' : GenericScalar('!Ref', 'bbb'),
'yourname': 'dfw',
's' : GenericSequence('!Split', ['a', GenericScalar('!Not', 'b'), 'c']),
}
}
yaml.dump(base, sys.stdout)
输出:
bar:
Resources:
RouteTableId: !Ref aaa
VpcPeeringConnectionId: !Ref bbb
s: !Split
- a
- !Not b
- c
yourname: dfw
name: abc
foo:
mapping: !Select
a: !Ref 1
b: !Base64 A413
scalar: !Ref barr
sequence: !Split
- !Ref baz
- !Split Multi word scalar
请注意,序列和映射已正确处理,并且也可以创建它们。然而没有检查:
- 您提供的标签确实有效
- 与标签关联的值属于该标签名称的正确类型(标量、映射、序列)
- 如果您希望 GenericMapping 的行为更像
dict
,那么您可能希望它是dict
的子类(而不是Generic
)并提供适当的__init__
(同上GenericSequence
/list
)
当作业更改为更接近您的作业时:
base["foo"] = {
"name": "abc",
"Resources": {
"RouteTableId" : GenericScalar('!Ref', 'aaa'),
"VpcPeeringConnectionId" : GenericScalar('!Ref', 'bbb'),
"yourname": "dfw"
}
}
输出是:
foo:
Resources:
RouteTableId: !Ref aaa
VpcPeeringConnectionId: !Ref bbb
yourname: dfw
name: abc
这正是您想要的输出。
关于Python ruamel.yaml 转储带引号的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996060/