python - 在 Python 中解析来自 AWS 开发工具包的 Cloudformation 字符串响应
问题描述
Python 中的 AWS 开发工具包具有get_template
获取 Cloudformation 模板的功能。
事实是,TemplateBody
它是作为字符串返回的,即使没有"
. 这使得解析非常困难。
您对如何像dict
Python3.x 一样正确解析和操作数据有什么建议吗?
我试过了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.
...
我的result
代码中的不是字符串,甚至不是 dict 类型,而是 ruamel.yaml 包的类似 dict 的对象。您可以从result
诸如解析元素
result['AWSTemplateFormatVersion']
它给出的地方
2010-09-09
推荐阅读
- lvm - LVM 无法回收空间
- javascript - Discord Bot:为文本字符串创建同义词
- scala - Scala 接受无参数函数和零参数函数作为重载
- angular - ionic ionchange 和 ngOnit 相同的方法,当我两次进入页面时,方法会调用 3 次,我该如何避免呢?
- go - go/kubernetes - runtime.notRegisteredErr
- python - 如何使用 cron 作业将事件插入谷歌日历?
- oracle - 在 Liquibase 中,如何向现有复合主键添加新列/字段
- python - 插入顺序模型层失败
- java - ANTLR4 在访客不工作时调用下一步
- javascript - 如何将计数传递给动态 json 对象