使用PyYAML库解析AWS CloudFormation模板

问题描述 投票:2回答:2

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

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

▶ aws cloudformation validate-template --template-body file://cloudformation.yml

但是当我尝试使用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

然后:

▶ 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

如何使用PyYAML或其他库来解析CloudFormation YAML文件?

amazon-web-services yaml amazon-cloudformation pyyaml
2个回答
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)

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


0
投票

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

安装库:

▶ pip install cfn_flip

然后,在模板中读取的最简单的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)

这个库没有真正记录,但是还有各种方法可以自定义值得探索的输出格式。

© www.soinside.com 2019 - 2024. All rights reserved.