使用 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"'


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


茅侃侃
浏览 83回答 2
2回答

蝴蝶不菲

在 YAML 中,以 开头的不带引号的值!表示自定义类型。您永远无法yaml.dump使用简单的字符串值生成它。您将需要创建一个自定义类和一个关联的表示器才能获得您想要的输出。例如:import yamlclass 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 dongParameters:  Environment:    Description: Environment for Deployment    Type: StringResources:  Queue:    Properties:      DelaySeconds: 0      MaximumMessageSize: 262144      MessageRetentionPeriod: 1209600      QueueName: !Sub '${Environment}-Queue'      ReceiveMessageWaitTimeSeconds: 0      VisibilityTimeout: 150    Type: AWS::SQS::Queue

哔哔one

您也可以尝试对流层库。它支持所有 AWS 服务(由 AWS CloudFormation 支持),并且在 Python 中创建 CloudFormation 模板确实更加 Pythonic。我已为您的 CloudFormation 模板粘贴了对流层代码。你也可以尝试一下:from troposphere import Template, Parameter, Subfrom troposphere.sqs import Queuedef get_cfn_template():    template = Template()    template.set_version("2010-09-09")    template.set_description("ding dong")    template.add_parameter(Parameter(        "Environment",        Type="String",        Description="Environment for Deployment"    ))    template.add_resource(        Queue(            'Queue',            DelaySeconds=0,            MaximumMessageSize=262144,            MessageRetentionPeriod=1209600,            QueueName=Sub("${Environment}-Queue"),            ReceiveMessageWaitTimeSeconds=0,            VisibilityTimeout=150        )    )    return template.to_json()print get_cfn_template()输出{    "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": {                    "Fn::Sub": "${Environment}-Queue"                },                "ReceiveMessageWaitTimeSeconds": 0,                "VisibilityTimeout": 150            },            "Type": "AWS::SQS::Queue"        }    }}Troposphere 也可以将您的代码转换为 YAML。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python