使用PyYAML库解析AWS CloudFormation模板

nix*_*ind 3 yaml amazon-web-services pyyaml aws-cloudformation

我正在使用需要在AWS CloudFormation YAML模板中读取的PyYAML库编写自定义Python应用程序。

我知道模板是有效的CloudFormation模板,因为我使用validate-template测试了它们:

? aws cloudformation validate-template --template-body file://cloudformation.yml
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用PyYAML库读取它们时,出现如下错误:

yaml.scanner.ScannerError:此处不允许映射值

无法确定标签“!Sub”的构造函数

和别的。

作为示例,我尝试以下AWS示例模板:

? curl -s \
    https://raw.githubusercontent.com/awslabs/aws-cloudformation-templates/master/aws/services/CloudFormation/FindInMap_Inside_Sub.yaml \
    -o FindInMap_Inside_Sub.yaml
Run Code Online (Sandbox Code Playgroud)

然后:

? 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'))
Run Code Online (Sandbox Code Playgroud)

这导致:

yaml.constructor.ConstructorError: could not determine a constructor for the tag '!FindInMap'
  in "FindInMap_Inside_Sub.yaml", line 89, column 45
Run Code Online (Sandbox Code Playgroud)

如何使用PyYAML之类的库解析CloudFormation YAML文件?

Ale*_*vey 11

可以使用aws-cfn-template-flip项目附带的cfn_tools库。

安装库:

? pip install cfn_flip
Run Code Online (Sandbox Code Playgroud)

那么在模板中读取的最简单的 Python 可能是:

#!/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))
Run Code Online (Sandbox Code Playgroud)

这个库并没有真正记录在案,但其中也有各种方法可用于自定义值得探索的输出格式。


Jes*_*ooa 5

他们的aws-cfn-template-flip项目是将cfn模板与json和yaml相互转换的一个很好的起点。示例签出yaml_loader.py脚本。它显示了如何添加yaml构造函数。在底部,您将看到:

CfnYamlLoader.add_constructor(TAG_MAP, construct_mapping)
CfnYamlLoader.add_multi_constructor("!", multi_constructor)
Run Code Online (Sandbox Code Playgroud)

您可能会对construct_mapping那里的方法感兴趣。从那里,您可以查看代码的工作方式。