简体   繁体   中英

Parse Cloudformation string response from AWS SDK in Python

The AWS SDK in Python has a function get_template to get a Cloudformation template.

The fact is the TemplateBody is a return as string and even without " . This makes the parsing pretty hard.

Do you have any suggestions on how to properly parse it and manipulate the data as dict in Python3.x?

I've tried with yaml.load , json.loads but w/o any luck.

on Github theere is an issue about this but no one seems to take care of it

Try ruamel.yaml package. This is my test code,

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)

and the result is

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

The result in my code is not string and even not dict type but it is a dict-like object of ruamel.yaml package. You can parse the element from the result such as

result['AWSTemplateFormatVersion']

where it gives

2010-09-09

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM