A custom resource runs your Lambda function when the stack creates, updates or deletes it. Use it to manage something outside AWS together with the stack: a webhook in Stripe, a monitor in Datadog, a DNS record at another provider. It's created on deploy, updated when its properties change and removed when you delete the stack.
It has two parts. A custom-resource-definition is the Lambda function with your code. A custom-resource-instance
is one managed thing: it names a definition and passes it properties. One definition can serve many instances.
For a step that just runs once per deploy, such as a migration, a deployment script is simpler: it doesn't need the response protocol below. For an AWS resource type Stacktape doesn't have, use raw CloudFormation.
Basic example
export default defineConfig(() => { const webhookProvider = new CustomResourceDefinition({ packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/webhook-provider.ts' }), timeout: 60, environment: { EXTERNAL_API_KEY: $Secret('external-api-key') } }); const apiWebhook = new CustomResourceInstance({ definitionName: 'webhookProvider', resourceProperties: { callbackUrl: 'https://myapp.example.com/webhook' } }); return { resources: { webhookProvider, apiWebhook } };});The handler receives resourceProperties as event.ResourceProperties. The default timeout is 10 seconds, which is
short for calls to outside APIs; the maximum is 900.
The handler
CloudFormation calls the function with a RequestType of Create, Update or Delete, then waits until the function
PUTs a result to the ResponseURL in the event. The function must report FAILED when the outside API refuses the
request; fetch doesn't throw on a 4xx or 5xx response, so check the status yourself:
type Event = { RequestType: 'Create' | 'Update' | 'Delete'; ResourceProperties: { callbackUrl: string }; PhysicalResourceId?: string; ResponseURL: string; StackId: string; RequestId: string; LogicalResourceId: string;};const api = (path: string, init: RequestInit = {}) => fetch(`https://api.example.com${path}`, { ...init, headers: { Authorization: `Bearer ${process.env.EXTERNAL_API_KEY}`, 'Content-Type': 'application/json' } });export default async (event: Event) => { let physicalResourceId = event.PhysicalResourceId; let data: Record<string, string> = {}; let status: 'SUCCESS' | 'FAILED' = 'SUCCESS'; let reason = ''; try { if (event.RequestType === 'Create') { const response = await api('/webhooks', { method: 'POST', body: JSON.stringify({ url: event.ResourceProperties.callbackUrl }) }); if (!response.ok) throw new Error(`Create failed: ${response.status} ${await response.text()}`); const webhook = await response.json(); if (!webhook.id) throw new Error('Create response has no webhook id'); physicalResourceId = webhook.id; data = { webhookId: webhook.id }; } if (event.RequestType === 'Update') { const response = await api(`/webhooks/${physicalResourceId}`, { method: 'PUT', body: JSON.stringify({ url: event.ResourceProperties.callbackUrl }) }); if (!response.ok) throw new Error(`Update failed: ${response.status} ${await response.text()}`); data = { webhookId: physicalResourceId! }; } if (event.RequestType === 'Delete' && physicalResourceId?.startsWith('wh_')) { const response = await api(`/webhooks/${physicalResourceId}`, { method: 'DELETE' }); // Already gone counts as deleted. if (!response.ok && response.status !== 404) { throw new Error(`Delete failed: ${response.status} ${await response.text()}`); } } } catch (error) { status = 'FAILED'; reason = error instanceof Error ? error.message : String(error); } const result = await fetch(event.ResponseURL, { method: 'PUT', body: JSON.stringify({ Status: status, Reason: reason, // A failed Create has no id yet; reuse the request ID so CloudFormation gets a value. PhysicalResourceId: physicalResourceId ?? event.RequestId, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: data }) }); if (!result.ok) throw new Error(`Could not send the response to CloudFormation: ${result.status}`);};wh_ stands for the outside service's ID format. The check skips the API call when a failed Create never got a real
ID, for example during the rollback that follows it.
Rules that keep a stack out of trouble:
- Always respond. Without a response, CloudFormation waits about an hour and then fails the deploy.
- Keep the physical ID stable on Update. A different ID means "replaced": CloudFormation then sends a
Deletefor the old ID. - Make Delete tolerant. It also runs during rollbacks, sometimes for something that was never created. A missing
resource is a success. A Delete that fails leaves the resource in
DELETE_FAILED. - Keep the response under 4 KB. That limit covers the whole body, including
Data.
| Event field | Contains |
|---|---|
RequestType | Create, Update or Delete |
ResourceProperties | The instance's resourceProperties |
OldResourceProperties | The previous properties, on Update only |
PhysicalResourceId | The ID your function returned last time; absent on Create |
ResponseURL | Pre-signed URL for the result |
StackId, RequestId, LogicalResourceId | Copy them into the result |
Instances
Each instance is its own resource with its own lifecycle. Changing an instance's resourceProperties sends an Update
with the old and new properties; removing the instance from the config sends a Delete.
const apiDns = new CustomResourceInstance({ definitionName: 'dnsProvider', resourceProperties: { name: 'api.example.com', target: '203.0.113.10' }});const appDns = new CustomResourceInstance({ definitionName: 'dnsProvider', resourceProperties: { name: 'app.example.com', target: '203.0.113.20' }});Use the result elsewhere
Values in Data are attributes of the instance. Read them with
$CfResourceParam and the instance's logical ID, which is its name in PascalCase plus
CustomResource:
environment: { WEBHOOK_ID: $CfResourceParam('ApiWebhookCustomResource', 'webhookId') }stacktape synth writes the template to compiled-template.yaml, where you can confirm the logical ID.
Packaging and access
The definition takes the same packaging as a Lambda function: js-bundle,
buildpack or custom-artifact with a
handler in file:function format. runtime is detected from the entry file unless you set it.
connectTo gives the function access to resources in the stack and injects their parameters, for example
STP_CONFIG_BUCKET_NAME. For other AWS services, add iamRoleStatements. See
Connecting resources.
The function runs only during deploys and deletes, so it costs a few Lambda invocations per deploy.
Configuration reference
Custom resource definition
CustomResourceDefinitionProps7 properties- packagingRequired
How the Lambda function code is packaged and deployed.
- connectTostring[]
Give this resource access to other resources in your stack.
- environmentEnvironmentVar[]
Environment variables injected into the Lambda function. Use
$ResourceParam()for dynamic values. - iamRoleStatementsStpIamRoleStatement[]
Raw IAM policy statements for permissions not covered by
connectTo. - memorynumber
Memory in MB (128–10,240). CPU scales proportionally — 1,769 MB = 1 vCPU.
- runtimestring
Lambda runtime. Auto-detected from file extension if not specified.
26 allowed values:"dotnet10""dotnet6""dotnet7""dotnet8""java11""java17"Show all
"java21""java25""java8""java8.al2""nodejs18.x""nodejs20.x""nodejs22.x""nodejs24.x""provided.al2""provided.al2023""python3.10""python3.11""python3.12""python3.13""python3.14""python3.8""python3.9""ruby3.3""ruby3.4""ruby4.0" Max execution time in seconds. Max: 900.
Custom resource instance
CustomResourceInstanceProps2 propertiesName of the
custom-resource-definitionin your config that provides the backing Lambda.Key-value pairs passed to the Lambda function during create/update/delete events.
Next steps
- Deployment scripts: run code once per deploy without the protocol.
- Raw CloudFormation resources: add AWS resource types directly.
- Directives:
$CfResourceParam,$Secretand the others.