oleber
oleber

Reputation: 1079

CloudFormation template import other templates

I have a structure that needs to be repeated multiple times inside a template, the only difference is a variable that could be used with "Fn::Join":.

I would expect a solution like this:

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

Does CloudFormation supports this or is there some tool to do this simple?

Upvotes: 0

Views: 726

Answers (1)

Raf
Raf

Reputation: 10107

Use troposphere. It allows to write python code which generates CloudFormation templates - never again will have to write JSON directly. Say hello to comments, loops, type checking and more advanced programming constructs if necessary.

This snippet will generate a template for 2 S3 buckets by looping through bucket_names list:

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 template:

{
    "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. the buckets will not be named foo and bar due to CloudFormation prefixing stack name and postfixing a random string. The real names can be seen in the outputs section of CloudFormation.

More troposphere examples: https://github.com/cloudtools/troposphere/tree/master/examples

Upvotes: 1

Related Questions