Sub topic 21
Transforms, AWS::Serverless and macros
This chapter assumes you can write a template with Parameters, Resources and Outputs, use Ref and Fn::GetAtt, and run stack operations from the AWS CLI. It covers how CloudFormation rewrites a template before it provisions anything, and when to use that feature.
What a transform does
A transform is a processing step that CloudFormation runs on your template before it creates or updates resources. The step takes the template you wrote and returns a larger, expanded template. CloudFormation then provisions the expanded version.
You request a transform with the top-level Transform section. You can also invoke one on a single fragment with Fn::Transform.
Three kinds of transform exist:
- AWS::Serverless-2016-10-31 is the AWS Serverless Application Model (SAM) transform. It is hosted by AWS.
- AWS::Include inserts a snippet from an S3 object into your template.
- Macros are transforms you build yourself. A macro is backed by a Lambda function in your account.
The AWS::Serverless transform
SAM is a shorthand for serverless applications. Declaring Transform: AWS::Serverless-2016-10-31 lets you use resource types such as AWS::Serverless::Function, AWS::Serverless::Api and AWS::Serverless::SimpleTable. One short SAM resource expands into several standard resources.
The template below declares one function with an HTTP event. It is complete as shown. The inline code avoids needing a packaging step.
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: A function exposed through an HTTP API
Resources:
HelloFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.12
Handler: index.handler
InlineCode: |
def handler(event, context):
return {"statusCode": 200, "body": "hello"}
Events:
HelloApi:
Type: HttpApi
Properties:
Path: /hello
Method: get
Outputs:
ApiUrl:
Description: Invoke URL for the API
Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/hello"From these few lines, CloudFormation generates an AWS::Lambda::Function, an IAM execution role, an AWS::ApiGatewayV2::Api with a route and integration, a stage and a Lambda permission. The generated API has the logical ID ServerlessHttpApi, which the output refers to.
Deploy it with the AWS CLI. A template with a transform that creates IAM roles needs capability acknowledgements, and the SAM transform needs CAPABILITY_AUTO_EXPAND:
aws cloudformation deploy \
--template-file sam.yaml \
--stack-name hello-sam \
--capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPANDAWS::Include
AWS::Include pulls a snippet from S3 into the place where you call it. This helps when several templates share the same block, such as a common set of tags or a policy document.
Resources:
AppBucket:
Type: AWS::S3::Bucket
Fn::Transform:
Name: AWS::Include
Parameters:
Location: s3://amzn-s3-demo-bucket/snippets/bucket-props.yamlThe snippet file holds the keys that are merged into the resource. Use it for sharing text, not for logic. There are no parameters passed to the snippet.
Macros
A macro lets you define your own template processing. You build it from two parts:
- A Lambda function that receives a template fragment and returns a modified fragment.
- An
AWS::CloudFormation::Macroresource that registers the function under a name.
Once registered in an account and Region, any template there can use the macro name in Transform or Fn::Transform.
The registration looks like this:
Resources:
MacroFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: index.handler
Role: !GetAtt MacroRole.Arn
Code:
ZipFile: |
def handler(event, context):
fragment = event["fragment"]
for res in fragment.get("Resources", {}).values():
if res.get("Type") == "AWS::S3::Bucket":
tags = res.setdefault("Properties", {}).setdefault("Tags", [])
tags.append({"Key": "managed-by", "Value": "cloudformation"})
return {
"requestId": event["requestId"],
"status": "success",
"fragment": fragment,
}
MacroRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
TagMacro:
Type: AWS::CloudFormation::Macro
Properties:
Name: AddManagedByTag
FunctionName: !GetAtt MacroFunction.ArnA template then uses it with Transform: AddManagedByTag. The function adds a tag to every bucket before CloudFormation sees the template.
The Lambda function receives an event with these fields:
| Field | Meaning |
|---|---|
| `region` | The Region where the macro runs |
| `accountId` | The account that owns the stack |
| `fragment` | The template content to process |
| `transformId` | The name of the macro being invoked |
| `params` | Parameters passed to `Fn::Transform`, if any |
| `requestId` | An ID to copy into the response |
| `templateParameterValues` | The values of the template's parameters |
The response must return the same requestId, a status of success (any other value is a failure), and the processed fragment.
Scope: whole template or fragment
Where you put the transform sets how much the macro sees.
- A top-level
Transformpasses the entire template to the macro. - An inline
Fn::Transformpasses only the fragment that contains it, which is the sibling keys of that call.
Transforms listed at the top level run in the order you list them. Each one receives the output of the previous one. A transform inside a fragment runs before top-level ones.
Common errors and gotchas
- Missing capability. A stack operation fails with an "InsufficientCapabilitiesException" error when a macro or SAM transform is used without
CAPABILITY_AUTO_EXPAND. - Macro not found. The macro must exist in the same account and Region as the stack. Creating a stack in another Region fails until you register it there.
- Same-template use. You cannot use a macro in the same template that creates it. Deploy the macro first, in its own stack.
- Size limits. Macro processing is not exempt from template size limits. The expanded template must also be valid.
- Debugging. The template you wrote is not the one that was deployed. Use
aws cloudformation get-template --template-stage Processed --stack-name NAMEto read the expanded version.Originalreturns what you submitted. - Reviewing changes. A change set shows resources that came from the expansion. Review it before executing, since a small edit in a SAM resource can alter several generated resources.
- Macro failures. If the Lambda function times out or returns a non-success status, the stack operation fails before any resource is touched.
Choosing between options
| Need | Use |
|---|---|
| Shorter syntax for Lambda, API Gateway or DynamoDB | `AWS::Serverless` |
| The same static snippet in many templates | `AWS::Include` |
| Custom logic that rewrites the template, such as loops or defaults | A macro |
| An action that runs during the stack lifecycle, such as calling an API | A custom resource |
| One template reused as a unit | A nested stack |
The difference from custom resources matters. A macro changes the template before deployment and leaves nothing running afterward. A custom resource is a real resource in the stack that runs code on create, update and delete.
Exercise
A teammate's stack creation fails with InsufficientCapabilitiesException. The template starts with Transform: AWS::Serverless-2016-10-31 and defines one AWS::Serverless::Function. Which capabilities should you pass, and how can you read the template that CloudFormation actually deployed?
Show answer
Pass CAPABILITYIAM, because the expansion creates an IAM execution role, and CAPABILITYAUTOEXPAND, because the template needs a transform expanded. With aws cloudformation deploy, add `--capabilities CAPABILITYIAM CAPABILITYAUTOEXPAND. After the stack exists, run aws cloudformation get-template --stack-name NAME --template-stage Processed` to see the expanded template with the generated role, API and permission resources.
Exercise
You write a macro that adds a tag to every S3 bucket. You put the AWS::CloudFormation::Macro resource and a bucket in one template, and the template uses the macro by name. Why does it fail, and what is the fix?
Show answer
A macro must already be registered before a template can use it, and a template cannot use a macro that it creates itself. Deploy the macro in its own stack in the same account and Region first. Then deploy the bucket template, which refers to the macro name in its Transform section.