在 Python 中解析来自 AWS SDK 的 Cloudformation 字符串响应

Parse Cloudformation string response from AWS SDK in Python

Python 中的 AWS SDK 具有获取 Cloudformation 模板的函数get_template

事实是 TemplateBody 是一个 return 作为字符串,甚至没有 "。这使得解析非常困难。

对于如何正确解析它并像 Python3.x 中的 dict 那样操作数据,您有什么建议吗?

我试过 yaml.loadjson.loads 但 w/o 运气不好。

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不是string,更不是dict类型,而是ruamel.yaml包的类dict对象。您可以解析 result 中的元素,例如

result['AWSTemplateFormatVersion']

它给出的地方

2010-09-09