使用PyYAML库解析AWS CloudFormation模板 [英] Parse an AWS CloudFormation template with the PyYAML library
问题描述
我正在使用需要读取AWS CloudFormation YAML模板的PyYAML库编写自定义Python应用程序。
I am writing a custom Python application using the PyYAML library that needs to read in AWS CloudFormation YAML templates.
我知道模板是有效的CloudFormation模板,因为我使用validate-template测试了它们:
I know the templates are valid CloudFormation templates, because I tested them using validate-template:
▶ aws cloudformation validate-template --template-body file://cloudformation.yml
但是,当我尝试使用PyYAML库读取它们时,像这样的错误:
When I try to read them using the PyYAML library, however, I get errors like:
yaml.scanner.ScannerError:此处不允许映射值
yaml.scanner.ScannerError: mapping values are not allowed here
和
无法确定标签!Sub的构造函数
could not determine a constructor for the tag "!Sub"
等。
通过示例,我尝试以下AWS示例模板:
By way of example, I try this AWS example template:
▶ curl -s \
https://raw.githubusercontent.com/awslabs/aws-cloudformation-templates/master/aws/services/CloudFormation/FindInMap_Inside_Sub.yaml \
-o FindInMap_Inside_Sub.yaml
然后:
▶ python
Python 2.7.15 (default, Nov 27 2018, 21:40:55)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>> yaml.load(open('FindInMap_Inside_Sub.yaml'))
这会导致:
yaml.constructor.ConstructorError: could not determine a constructor for the tag '!FindInMap'
in "FindInMap_Inside_Sub.yaml", line 89, column 45
如何解析CloudFormation YAML
推荐答案
是否可以使用 cfn_tools 随 aws-cfn-template-flip 项目。
安装该库:
▶ pip install cfn_flip
然后在模板中读取的最简单的Python可能是:
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.
这篇关于使用PyYAML库解析AWS CloudFormation模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!