Loading CloudFormation YAML using Python

限于喜欢 提交于 2019-12-06 06:31:53

问题


I've got a set of YAML AWS Cloud Formation Templates that I've recently converted from JSON.

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.

I'm using the shorthand function syntax in the cloudformation templates which uses the YAML Tags. eg

Properties:
  MinSize: !Ref ClusterSize
  MaxSize: !Ref ClusterSize

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.

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?


回答1:


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'])

prints:

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)

which gives:

{'Properties': {'SizeList': ['1', '3'], 'MinSize': 'ClusterSize', 'MaxSize': 'ClusterSize'}}

(Please note that the scalars 1 and 3 are loaded as string instead of the normal integer)



来源:https://stackoverflow.com/questions/41089065/loading-cloudformation-yaml-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!