python - 使用 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"'
我该如何解决?任何的想法?请帮忙!!
解决方案
在 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
推荐阅读
- javascript - Nativescript 代码背后 - 将 GridLayout 动态添加到 ScrollView
- c# - 如何使用 VSTS Git API for C# 获取给定提交 ID 的所有拉取请求 ID(来自合并的提交)
- sql - 尽管使用 distinct 在 sas 中获取重复值,但如何删除它们?
- node.js - 将我的客户端 Heroku 应用程序连接到我的服务器应用程序时出现问题
- apache-kafka - Kafka Streams:是否可以使用不同的时间戳进行删除而不是流处理?
- python - 如何根据传入的数据播放 WAV 文件的某些部分?
- playframework - 播放框架配置 - 带有扩展的缓存控制
- google-sheets - 对不同用户的 Google 电子表格 URL 使用 SpreadsheetApp.openByUrl() 和 set()* 方法
- javascript - 用于在 Google 表格中拆分查询参数的 Google App 脚本
- visual-studio - 禁用/重新启用 xaml 设计器后,Visual Studio 2017 无法构建空白应用程序?