Photo by Émile Perron on Unsplash

All AWS Serverless developers should know (Fn::Transform + AWS::Include)

George Mao
Jan 21 · 2 min read

Developers often ask “What’s the best way to define and deploy APIs to API Gateway?

For the most part, API developers should use Swagger or OpenAPI. These are popular specifications that describe how an API should be deployed. If you’re automating these deployments, chances are you are using SAM or CloudFormation to deploy these API definitions.

Swagger and OpenAPI specs are static. So how do you instruct your CloudFormation script (or SAM) to import a static file AND allow dynamic values to pass into your Swagger/OpenAPI specs to resolve at runtime?

For example you probably want a dynamic value for the AWS Region, AWS account number, or pass a logical ID from the CloudFormation template into the API spec.

Fn::Transform + AWS::Include to the rescue!

Let’s say you created a Lambda function using SAM. The logical name you choose is ${LambdaFunction}. CloudFormation will create the function with a name in this format: [StackName]-[$LambdaFunction]-[some unique id]. You need to pass this dynamically generated value into your API spec so you can build a Lambda integration for your backend.

Here’s how you define a Lambda backend integration.
In your Swagger snippet, you can use AWS CloudFormation Psuedo Parameters or pass in anything from the parent Cloudformation script. In this case we’re using a dynamic AWS region with ${AWS::Region} and passing in the generated Lambda function Arn with ${LambdaFunction.arn}

Link it all together with the Fn::Transform and AWS::Include directives. This instructs CloudFormation to pull the Swagger template from S3, then dynamically evaluate all items before inserting into the final template that is executed.

Remember, you can use any Pseudo parameter or Intrinsic function in and pass values from CloudFormation/SAM into your Swagger templates. See here for the CloudFormation reference guide.

George Mao

Written by

AWS Serverless Specialist. I’ll post short, high value tips & tricks for all things Serverless. Ping me if you want to talk about anything :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade