gpt4 book ai didi

amazon-web-services - 使用 PyYAML 库解析 AWS CloudFormation 模板

转载 作者:行者123 更新时间:2023-12-04 08:07:17 25 4
gpt4 key购买 nike

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

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

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

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

yaml.scanner.ScannerError: mapping values are not allowed here

could not determine a constructor for the tag "!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 文件?

最佳答案

可以使用 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))

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

关于amazon-web-services - 使用 PyYAML 库解析 AWS CloudFormation 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50914422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com