2 回答
TA贡献1810条经验 获得超4个赞
在 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
TA贡献1854条经验 获得超8个赞
您也可以尝试对流层库。它支持所有 AWS 服务(由 AWS CloudFormation 支持),并且在 Python 中创建 CloudFormation 模板确实更加 Pythonic。
我已为您的 CloudFormation 模板粘贴了对流层代码。你也可以尝试一下:
from troposphere import Template, Parameter, Sub
from troposphere.sqs import Queue
def 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。
添加回答
举报