Python 中的 AWS 开发工具包具有一个函数 get_template
来获取 Cloudformation 模板。
事实是 TemplateBody
是作为字符串返回的,甚至没有 "
。这使得解析非常困难。
对于如何在 Python3.x 中正确解析它并以 dict
形式操作数据,您有什么建议吗?
我尝试过 yaml.load
、json.loads
但没有任何运气。
关于 Github这是一个问题,但似乎没有人解决它
最佳答案
尝试ruamel.yaml
包。这是我的测试代码,
import boto3
import sys
from ruamel.yaml import YAML
session = boto3.session.Session(region_name='<region>')
client = session.client('cloudformation')
response = client.get_template(StackName='<stackname>')
yaml = YAML()
result = yaml.load(response['TemplateBody'])
yaml.dump(result, sys.stdout)
结果是
AWSTemplateFormatVersion: '2010-09-09'
Description: >
AWS CloudFormation template to create a new VPC
or use an existing VPC for ECS deployment
in Create Cluster Wizard. Requires exactly 1
Instance Types for a Spot Request.
Parameters:
EcsClusterName:
Type: String
Description: >
Specifies the ECS Cluster Name with which the resources would be
associated
Default: default
EcsAmiId:
Type: String
Description: Specifies the AMI ID for your container instances.
EcsInstanceType:
Type: CommaDelimitedList
Description: >
Specifies the EC2 instance type for your container instances.
Defaults to m4.large
Default: m4.large
ConstraintDescription: must be a valid EC2 instance type.
...
我的代码中的结果
不是字符串,甚至不是字典类型,但它是ruamel.yaml包的类似字典的对象。您可以从结果
中解析元素,例如
result['AWSTemplateFormatVersion']
它给出的地方
2010-09-09
关于python - 使用 Python 解析来自 AWS SDK 的 Cloudformation 字符串响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57718450/