2016-04-22 88 views
0

我有一個需要在模板內重複多次的結構,唯一的區別是可以與"Fn::Join":一起使用的變量。CloudFormation模板導入其他模板

我希望這樣一個解決方案:

"Import" : [ 
     { 
     "Path":"s3://...", 
     "Parameters":[ 
      {"Key":"name", "Value":"foobar"} 
     ] 
    ] 

不CloudFormation支持這個還是有一些工具來做到這簡單?

回答

2

使用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爲堆棧名稱加前綴並且後綴爲隨機字符串,因此不會將存儲桶命名爲foobar。真實姓名可以在CloudFormation的輸出部分中看到。

更多對流層的例子:https://github.com/cloudtools/troposphere/tree/master/examples