Использование troposphere. Это позволяет писать код python, который генерирует шаблоны CloudFormation - никогда больше не придется писать JSON напрямую. При необходимости поздороваться с комментариями, циклами, проверкой типов и более сложными конструкциями программирования.
Этот фрагмент кода генерирует шаблон для 2 S3 ведрами проходом по bucket_names
списка: шаблон
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"
}
}
}
нотабене ведра не будут называться foo
и bar
из-за того, что CloudFormation префиксное имя стека и постфиксация случайной строки. Реальные имена можно увидеть в разделе выходов CloudFormation.
Другие примеры тропосферы: https://github.com/cloudtools/troposphere/tree/master/examples