使用troposphere。它允許編寫生成CloudFormation模板的Python代碼 - 不再需要直接編寫JSON。如果有必要,向評論,循環,類型檢查和更高級的編程構造說聲問候。
這個片段將通過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"
}
}
}
N.B.由於CloudFormation爲堆棧名稱加前綴並且後綴爲隨機字符串,因此不會將存儲桶命名爲foo
和bar
。真實姓名可以在CloudFormation的輸出部分中看到。
更多對流層的例子:https://github.com/cloudtools/troposphere/tree/master/examples
來源
2016-04-22 09:23:55
Raf