使用troposphere。它允许编写生成 CloudFormation 模板的 python 代码——再也不需要直接编写 JSON。如有必要,请向 cmets、循环、类型检查和更高级的编程结构问好。
这个 sn-p 将通过循环 bucket_names 列表为 2 个 S3 存储桶生成一个模板:
from troposphere import Output, Ref, Template
from troposphere.s3 import Bucket, PublicRead
t = Template()
# names of the buckets
bucket_names = ['foo', 'bar']
for bucket_name in bucket_names:
s3bucket = t.add_resource(Bucket(bucket_name, AccessControl=PublicRead,))
t.add_output(
Output(
bucket_name + "Bucket",
Value=Ref(s3bucket),
Description="Name of %s S3 bucket content" % bucket_name
)
)
print(t.to_json())
CloudFormation 模板:
{
"Outputs": {
"barBucket": {
"Description": "Name of bar S3 bucket content",
"Value": {
"Ref": "bar"
}
},
"fooBucket": {
"Description": "Name of foo S3 bucket content",
"Value": {
"Ref": "foo"
}
}
},
"Resources": {
"bar": {
"Properties": {
"AccessControl": "PublicRead"
},
"Type": "AWS::S3::Bucket"
},
"foo": {
"Properties": {
"AccessControl": "PublicRead"
},
"Type": "AWS::S3::Bucket"
}
}
}
注意由于 CloudFormation 前缀堆栈名称和后缀随机字符串,存储桶将不会命名为 foo 和 bar。真实姓名可以在 CloudFormation 的输出部分看到。
更多对流层示例:https://github.com/cloudtools/troposphere/tree/master/examples