Sub topic 22
Custom resources
This chapter assumes you can write a template with Resources and Outputs, use !GetAtt and !Ref, and read stack events. It also assumes you know basic Lambda and IAM.
When a custom resource fits
A custom resource lets a stack run your own code during create, update and delete. CloudFormation treats it like any other resource. It has dependencies, a logical ID, and attributes you read with !GetAtt. Use one when the work cannot be expressed as a built-in resource type. Common cases are:
- Looking up a value that no intrinsic function returns, such as the latest AMI ID from a catalog.
- Calling an API that has no CloudFormation resource type.
- Emptying an S3 bucket before the stack deletes it.
- Configuring a third-party system as part of a deployment.
Check first whether a native resource type, a transform, or the CloudFormation registry already covers the need. Custom resources are code you must write, secure, monitor and keep running.
How the protocol works
A custom resource has a type name that begins with Custom:: (for example Custom::RandomSuffix). You can also use AWS::CloudFormation::CustomResource. It must have a ServiceToken property, which is the ARN of a Lambda function or an SNS topic. Every other property is passed to your code as ResourceProperties.
CloudFormation sends an event with a RequestType of Create, Update or Delete. It also includes a pre-signed S3 ResponseURL. Your code does its work and then sends an HTTP PUT with a JSON body to that URL. The stack operation waits until that response arrives.
The request types map to stack operations as follows:
| RequestType | Sent when | Your code should |
|---|---|---|
| Create | The resource is added to the stack | Create the thing and return a `PhysicalResourceId` |
| Update | Any property under the resource changes | Apply the change. Returning a different `PhysicalResourceId` makes CloudFormation treat it as a replacement |
| Delete | The resource is removed, the stack is deleted, or a replacement finishes | Clean up, and always report SUCCESS if there is nothing left to clean |
A working example
This template defines a Lambda function and a custom resource that returns a stable random string. The function code is inline, so the cfnresponse module is available to it. That module exists only for inline ZipFile code in Python and Node.js. Packaged functions need their own response code.
AWSTemplateFormatVersion: "2010-09-09"
Description: Lambda-backed custom resource that returns a random suffix
Resources:
FunctionRole:
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
SuffixFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: index.handler
Role: !GetAtt FunctionRole.Arn
Timeout: 30
Code:
ZipFile: |
import uuid
import cfnresponse
def handler(event, context):
try:
request_type = event["RequestType"]
if request_type == "Delete":
# Nothing to clean up, but a response is still required.
cfnresponse.send(event, context, cfnresponse.SUCCESS,
{}, event["PhysicalResourceId"])
return
if request_type == "Create":
physical_id = uuid.uuid4().hex
else:
physical_id = event["PhysicalResourceId"]
length = int(event["ResourceProperties"]["Length"])
data = {"Suffix": physical_id[:length]}
cfnresponse.send(event, context, cfnresponse.SUCCESS,
data, physical_id)
except Exception as exc:
cfnresponse.send(event, context, cfnresponse.FAILED,
{"Error": str(exc)},
event.get("PhysicalResourceId", "failed"))
RandomSuffix:
Type: Custom::RandomSuffix
Properties:
ServiceToken: !GetAtt SuffixFunction.Arn
Length: 8
Outputs:
Suffix:
Description: Value returned by the custom resource
Value: !GetAtt RandomSuffix.SuffixLength reaches the function as the string "8", because custom resource properties are always strings. The function converts it. Because the physical ID is reused on update, the suffix does not change when you edit Length.
Failure modes and gotchas
- No response means a long hang. If the function crashes or never calls the response URL, CloudFormation waits for the custom resource timeout, which is one hour by default. The stack then fails and rolls back. Wrap the handler in a try/except that always reports FAILED, and set the
ServiceTimeoutproperty to a value close to the function's real runtime. - Delete must respond. If a Delete handler throws or stays silent, the stack ends in
DELETE_FAILED. This is the most common custom resource problem, and it often follows a failed Create, because Delete is still invoked during rollback. Make Delete tolerate resources that were never created. - Physical ID changes mean replacement. If an Update returns a new
PhysicalResourceId, CloudFormation sends a Delete for the old ID after the update succeeds. - Response size. The response body is limited to 4096 bytes. Return identifiers, not large payloads.
- Secrets in Data. Values you return are visible in the console and API unless you hide them. Do not return secrets through
DatawithoutNoEchohandling. - Ordering. The custom resource runs after anything it references. If it needs a resource it does not reference, add
DependsOn. - Idempotency. CloudFormation can retry or replay events, so write handlers that give the same result when run twice.
Exercise
A stack with a Lambda-backed custom resource is stuck in UPDATEINPROGRESS for nearly an hour. The Lambda logs show an unhandled exception. What happened, and what two changes to the function prevent it?
Show answer
The function crashed before sending a response to the pre-signed ResponseURL, so CloudFormation waited for the timeout (one hour by default). Wrap the handler in try/except and send a FAILED response on any exception, and set the ServiceTimeout property on the custom resource to a shorter value that matches the function's expected runtime.
Exercise
Your Update handler returns a new PhysicalResourceId every time it runs. What does CloudFormation do with the old one, and why can this be a problem?
Show answer
CloudFormation treats the new ID as a replacement. After the update succeeds, it sends a Delete request for the old physical ID. If the handler's Delete logic removes real infrastructure, an ordinary property change can destroy it. Return the existing PhysicalResourceId on Update unless you intend a replacement.