Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CloudFormation Templating Custom Resource
# NOTE: there is a 4k CustomResource response limit, so keep all templates well under that
AWSTemplateFormatVersion: 2010-09-09
Description: 'CloudFormation Templating Custom Resource'
Resources:
TemplateFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Action: ['sts:AssumeRole']
Effect: Allow
Principal:
Service: [lambda.amazonaws.com]
TemplateFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import cfnresponse
from string import Template
import hashlib
def handler(event, context):
try:
props = event['ResourceProperties']
vars = props['Vars']
# TODO: replace with your templating language of choice
templ = Template(props['Template'])
rendered = templ.safe_substitute(vars)
responseData = {}
if len(templ.template) < 1900:
responseData['Template'] = templ.template # 4K response limit
responseData['Rendered'] = rendered
resourceID = hashlib.sha256(rendered).hexdigest()
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, resourceID)
except Exception as e:
print e
cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
Description: Python string.Template rendering for CloudFormation
Handler: index.handler
Role: !GetAtt TemplateFunctionRole.Arn
Runtime: 'python2.7'
Example:
Type: Custom::Template
Version: 1.0
Properties:
ServiceToken: !GetAtt TemplateFunction.Arn
Template: |
This is an example of string.Template '$value'
Vars:
value: '$deferred'
ExampleRecursion:
Type: Custom::Template
Version: 1.0
Properties:
ServiceToken: !GetAtt TemplateFunction.Arn
Template: !GetAtt Example.Rendered
Vars:
deferred: some other value
Outputs:
FunctionArn:
Description: CF Templating Function ARN
Value: !GetAtt TemplateFunction.Arn
Export:
Name: CFTemplater
ExampleIn:
Value: !GetAtt Example.Template
ExampleOut:
Value: !GetAtt Example.Rendered
ExampleRecursionIn:
Value: !GetAtt ExampleRecursion.Template
ExampleRecursionOut:
Value: !GetAtt ExampleRecursion.Rendered
ExampleIn This is an example of string.Template '$value'
ExampleOut This is an example of string.Template '$deferred'
ExampleRecursionIn This is an example of string.Template '$deferred'
ExampleRecursionOut This is an example of string.Template 'some other value'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment