Parse an AWS CloudFormation template with the PyYAML library

心已入冬 提交于 2019-11-28 11:43:29

Their aws-cfn-template-flip project that converts cfn templates to/from json and yaml is a good starting point. Example check out the yaml_loader.py script. It shows how it's adding yaml constructors. At the bottom, you'll see:

CfnYamlLoader.add_constructor(TAG_MAP, construct_mapping)
CfnYamlLoader.add_multi_constructor("!", multi_constructor)

You'll probably be interested in the construct_mapping method there. From there, you can look how the code works.

It is possible to use the cfn_tools library that ships with the aws-cfn-template-flip project.

Install the library:

▶ pip install cfn_flip

Then the simplest Python to read in the template might be:

#!/usr/bin/env python

import yaml
from cfn_tools import load_yaml, dump_yaml

text = open('./FindInMap_Inside_Sub.yaml').read()
data = load_yaml(text)

print dump_yaml(data)

This library is not really documented but there are also various methods in there for customising the formatting of the output worth exploring.

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