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

2024-10-03 06:18:09 发布

您现在位置:Python中文网/ 问答频道 /正文

Python中的awsdk有一个函数get_template来获取Cloudformation模板。你知道吗

事实上,TemplateBody是字符串形式的返回,甚至没有"。这使得解析非常困难。你知道吗

您对如何正确解析它并在Python3.x中操作数据dict有什么建议吗?你知道吗

我试过yaml.loadjson.loads,但运气不好。你知道吗

Github这是一个问题,但似乎没有人照顾它


Tags: 数据函数字符串模板yamlgetloadtemplate
1条回答
网友
1楼 · 发布于 2024-10-03 06:18:09

试试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类型,而是类似dict的对象鲁阿迈尔.亚马尔包裹。您可以从result解析元素,例如

result['AWSTemplateFormatVersion']

它给了我们什么

2010-09-09

相关问题 更多 >