python - 使用 Python 解析来自 AWS SDK 的 Cloudformation 字符串响应

标签 python aws-sdk aws-cloudformation boto3

Python 中的 AWS 开发工具包具有一个函数 get_template 来获取 Cloudformation 模板。

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

对于如何在 Python3.x 中正确解析它并以 dict 形式操作数据,您有什么建议吗?

我尝试过 yaml.loadjson.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.
...

我的代码中的结果不是字符串,甚至不是字典类型,但它是ruamel.yaml包的类似字典的对象。您可以从结果中解析元素,例如

result['AWSTemplateFormatVersion']

它给出的地方

2010-09-09

关于python - 使用 Python 解析来自 AWS SDK 的 Cloudformation 字符串响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57718450/

相关文章:

amazon-web-services - 无法从 API 网关向 SNS 主题发送大负载

azure-devops - 在 Azure DevOps Pipelines 中分配 AWS Cloudformation 输出变量

amazon-web-services - 使用 sam deploy 和 CloudFormation 时如何检测 ECR 镜像中的更改

python - 当某些字符串具有 UTF-8 字符时,pandas DataFrame.style.render

python - 使用递归在python中绘制模式

python - 禁用 PyYAML 值转换

json - 转到 AWS,从 DynamoDB 项目编码到 JSON,省略空值

python - 找不到文件错误 : [Errno 2] when packaging for PyPI

java - DynamoDB 对象集嵌套查询

node.js - 无法更新 Dynamodb 表,出现 ValidationException