【问题标题】:Parse Cloudformation string response from AWS SDK in Python在 Python 中解析来自 AWS 开发工具包的 Cloudformation 字符串响应
【发布时间】:2020-01-03 05:15:03
【问题描述】:

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

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

您对如何正确解析它并在 Python3.x 中将数据操作为dict 有任何建议吗?

我尝试过使用yaml.loadjson.loads,但没有任何运气。

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

【问题讨论】:

    标签: python aws-sdk amazon-cloudformation boto3


    【解决方案1】:

    试试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 不是字符串,甚至不是字典类型,而是 ruamel.yaml 包的类字典对象。您可以从result 中解析元素,例如

    result['AWSTemplateFormatVersion']
    

    它提供的地方

    2010-09-09
    

    【讨论】:

    • 我已经尝试过了,但它不起作用我得到了一个 str,因为 CF 模板是一个 YAML,所以当它是一个 YAML 时返回一个字符串。
    • Str 是为了什么?我的result?或response['TemplateBody']response['TemplateBody'] 根据 boto3 的定义以字符串形式返回..
    • 我的回答稍作修改,希望对你有所帮助。
    • 我尝试了您的确切方法,现在可以了。有趣的是,当我转储响应然后加载文件时,我得到的不是dict-like,而是str。想知道转储过程中会出现什么问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2014-09-03
    • 2020-03-14
    相关资源
    最近更新 更多