我有一个需要在模板中重复多次的结构,唯一的区别是可以与"Fn::Join":
一起使用的变量。
我希望有这样的解决方案:
"Import" : [
{
"Path":"s3://...",
"Parameters":[
{"Key":"name", "Value":"foobar"}
]
]
CloudFormation是否支持此功能,还是有一些工具可以做到这一点?
答案 0 :(得分: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前缀堆栈名称和后缀随机字符串,因此不会将桶命名为foo
和bar
。真实姓名可以在CloudFormation的输出部分看到。
更多对流层示例:https://github.com/cloudtools/troposphere/tree/master/examples