首页 > 解决方案 > 使用 Python 创建 YAML:Cloudformation 模板

问题描述

您好我正在尝试使用 Python 创建 Cloudformation 模板。我正在使用yaml图书馆这样做。

这是我的代码:

import yaml

dict_file =     {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "ding dong",
    "Parameters": {
        "Environment":{
            "Description": "Environment for Deployment",
            "Type": "String"
        }
    },
    "Resources":{
        "Queue": {
            "Type": "AWS::SQS::Queue",
            "Properties":{
                "DelaySeconds": 0,
                "MaximumMessageSize": 262144,
                "MessageRetentionPeriod": 1209600,
                "QueueName": '!Sub "${Environment}-Queue"',
                "ReceiveMessageWaitTimeSeconds": 0,
                "VisibilityTimeout": 150
            }
        }
    }
}

with open(r'TopicName.yml', 'w') as file:
    documents = yaml.dump(dict_file, file, sort_keys=False)

问题在于 Cloudformation 标签,!Sub如您在 key 中看到的那样"QueueName"!Sub需要在生成的 yaml 中的引用之外。由此产生的 yaml 看起来像这样QueueName: '!Sub "${LSQRegion}-TelephonyLogCall-Distributor"'

我该如何解决?任何的想法?请帮忙!!

标签: pythonpython-3.xamazon-web-services

解决方案


在 YAML 中,以开头的不带引号的值!表示自定义类型。您永远无法yaml.dump从简单的字符串值生成它。您将需要创建一个自定义类和一个关联的表示器来获得您想要的输出。例如:

import yaml


class Sub(object):
    def __init__(self, content):
        self.content = content

    @classmethod
    def representer(cls, dumper, data):
        return dumper.represent_scalar('!Sub', data.content)


dict_file = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "ding dong",
    "Parameters": {
        "Environment": {
            "Description": "Environment for Deployment",
            "Type": "String"
        }
    },
    "Resources": {
        "Queue": {
            "Type": "AWS::SQS::Queue",
            "Properties": {
                "DelaySeconds": 0,
                "MaximumMessageSize": 262144,
                "MessageRetentionPeriod": 1209600,
                "QueueName": Sub("${Environment}-Queue"),
                "ReceiveMessageWaitTimeSeconds": 0,
                "VisibilityTimeout": 150,
            },
        }
    },
}


yaml.add_representer(Sub, Sub.representer)
print(yaml.dump(dict_file))

这将输出:

AWSTemplateFormatVersion: '2010-09-09'
Description: ding dong
Parameters:
  Environment:
    Description: Environment for Deployment
    Type: String
Resources:
  Queue:
    Properties:
      DelaySeconds: 0
      MaximumMessageSize: 262144
      MessageRetentionPeriod: 1209600
      QueueName: !Sub '${Environment}-Queue'
      ReceiveMessageWaitTimeSeconds: 0
      VisibilityTimeout: 150
    Type: AWS::SQS::Queue


推荐阅读