使用 PyYAML 库解析 AWS CloudFormation 模板 [英] Parse an AWS CloudFormation template with the PyYAML library

查看:26
本文介绍了使用 PyYAML 库解析 AWS CloudFormation 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用需要读取 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 模板,因为我使用验证模板测试了它们:

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

如何使用 PyYAML 等库解析 CloudFormation YAML 文件?

推荐答案

可以使用 cfn_tools 库,随 aws 一起提供-cfn-template-flip 项目.

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

安装库:

▶ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆