首页 > 解决方案 > 在 Python 中解析来自 AWS 开发工具包的 Cloudformation 字符串响应

问题描述

Python 中的 AWS 开发工具包具有get_template获取 Cloudformation 模板的功能。

事实是,TemplateBody它是作为字符串返回的,即使没有". 这使得解析非常困难。

您对如何像dictPython3.x 一样正确解析和操作数据有什么建议吗?

我试过了yaml.loadjson.loads但没有任何运气。

Github上有一个关于这个的问题,但似乎没有人关心它

标签: pythonaws-sdkamazon-cloudformationboto3

解决方案


试试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

推荐阅读