使用Python加载CloudFormation YAML [英] Loading CloudFormation YAML using Python
问题描述
我有一组 YAML
AWS云形成模板,这些模板是我最近从 JSON
转换而来的。
I've got a set of YAML
AWS Cloud Formation Templates that I've recently converted from JSON
.
使用 JSON
时,我能够加载这些模板并使用 jinja
从中生成一些降价文档。我正在尝试对python中的 YAML
进行同样的操作。
When using JSON
I was able to load these templates and transform them using jinja
to generate some markdown documentation from them. I'm attempting to do the same with YAML
in python.
我在中使用了简写函数语法使用 YAML
标签的cloudformation模板。例如
I'm using the shorthand function syntax in the cloudformation templates which uses the YAML
Tags. eg
Properties:
MinSize: !Ref ClusterSize
MaxSize: !Ref ClusterSize
尝试使用 ruamel.yaml
包加载它们时,构造函数失败,因为它无法处理标签,因为它不了解标签。
When attempting to load these with the ruamel.yaml
package the Constructor fails because it is unable to handle the Tags, because it has no knowledge about them.
有没有一种方法可以解决此问题,以便能够加载 YAML
文档,以便我可以检索/查询输出和资源吗?
Is there a way I can work around this so that I'm able to load the YAML
document so that I can retrieve/query the Outputs and Resources?
推荐答案
您误认为了 ruamel.yaml
无法处理标签。但是,当然,您必须提供有关如何处理任何未知标签的信息,它无法猜测要使用!Ref
:
You're mistaken that ruamel.yaml
cannot handle tags. But of course you have to provide the information on how to handle any unknown tags, it cannot guess what kind of data you want to load with !Ref
:
import ruamel.yaml
yaml_str = """\
Properties:
MinSize: !Ref ClusterSize
MaxSize: !Ref ClusterSize
"""
class Blob(object):
def update(self, value):
self.value = value
def __str__(self):
return str(self.value)
def my_constructor(self, node):
data = Blob()
yield data
value = self.construct_scalar(node)
data.update(value)
ruamel.yaml.SafeLoader.add_constructor(u'!Ref', my_constructor)
data = ruamel.yaml.safe_load(yaml_str)
print('data', data['Properties']['MinSize'])
打印:
ClusterSize
如果您想摆脱许多不同的标签,并且不关心一切都是字符串,您也可以这样做:
If you want to get rid of many different tags, and don't care about "everything being a string" you can also do:
import ruamel.yaml
yaml_str = """\
Properties:
MinSize: !Ref ClusterSize
MaxSize: !Ref ClusterSize
SizeList:
- !abc 1
- !xyz 3
"""
def general_constructor(loader, tag_suffix, node):
return node.value
ruamel.yaml.SafeLoader.add_multi_constructor(u'!', general_constructor)
data = ruamel.yaml.safe_load(yaml_str)
print(data)
这给出:
{'Properties': {'SizeList': ['1', '3'], 'MinSize': 'ClusterSize', 'MaxSize': 'ClusterSize'}}
(请注意,标量 1
和 3
作为字符串而不是普通整数加载
(Please note that the scalars 1
and 3
are loaded as string instead of the normal integer)
这篇关于使用Python加载CloudFormation YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!