A Stacktape custom resource runs a Lambda function during stack create, update, and delete operations to provision infrastructure or services that Stacktape and CloudFormation don't natively support. Use custom resources to integrate third-party APIs, SaaS platforms, or custom provisioning logic into your deployment lifecycle — paired as a definition (the backing Lambda) and one or more instances (the invocations).
When to use
Custom resources are the right choice when you need to manage an external resource's lifecycle in sync with your Stacktape stack. Common scenarios:
- Third-party API setup — creating webhooks, API keys, or accounts in external services (Stripe, PagerDuty, Cloudflare) that should be torn down when you delete the stack.
- SaaS service provisioning — managing resources in external SaaS platforms (Datadog monitors, LaunchDarkly flags, PlanetScale databases) tied to your stack lifecycle.
- Custom infrastructure — provisioning infrastructure that CloudFormation doesn't support natively, such as DNS records in non-Route53 providers or certificates in external CAs.
- External database provisioning — creating databases or schemas in services outside AWS that need lifecycle management.
Custom resource handlers receive Create, Update, and Delete events as part of CloudFormation stack operations. Because custom resources participate in CloudFormation stack operations, design Create, Update, and Delete handlers to be idempotent and rollback-tolerant. This makes custom resources safer than one-off scripts for managing external state that should stay in sync with your stack.
When NOT to use
Use a deployment script instead if you need to run a command before or after deployment — database migrations, cache warming, or notification sends. Deployment scripts are simpler and don't require implementing the CloudFormation response protocol.
Use raw CloudFormation resources instead if the resource you need is a standard AWS resource type that Stacktape doesn't wrap. Raw CloudFormation is declarative and requires no Lambda code.
Use an AWS CDK construct instead if you want to compose multiple AWS resources with higher-level abstractions. CDK constructs generate CloudFormation at build time and don't require runtime Lambda logic.
| Custom resource | Deployment script | Raw CloudFormation | CDK construct | |
|---|---|---|---|---|
| Runs code during deploy | Yes (Lambda) | Yes (Lambda) | No | No (build-time only) |
| Manages external services | Yes | Yes | No | No |
| Stack-aware lifecycle | Create / Update / Delete | After deploy / before delete | Declarative | Declarative |
| CloudFormation response protocol | Required | Not needed | N/A | N/A |
How it works
Stacktape custom resources use a two-part model:
Custom resource definition (CustomResourceDefinition) — configures a backing Lambda function with its packaging, timeout, memory, and resource access. The definition itself doesn't provision anything — it defines the code that runs when instances are created, updated, or deleted.
Custom resource instance (CustomResourceInstance) — references a definition by name and passes resourceProperties to the backing Lambda. Each instance is an independent CloudFormation resource. When the stack is created, updated, or deleted, CloudFormation invokes the backing Lambda with the instance's properties and a RequestType of Create, Update, or Delete.
You can create multiple instances from a single definition, each with different properties. For example, one definition that manages DNS records could have separate instances for api.example.com and app.example.com.
- Deploy starts — CloudFormation processes the stack and encounters a custom resource instance.
- Lambda invoked — CloudFormation invokes the backing Lambda with RequestType and ResourceProperties from the instance.
- Handler runs — Your code creates, updates, or deletes the external resource based on RequestType.
- Response sent — The handler sends SUCCESS or FAILED back to CloudFormation via a pre-signed URL provided in the event. On failure, the stack operation fails.
Basic example
This example defines a custom resource definition that manages webhooks with an external service, and an instance that invokes it during stack operations. Both the definition and at least one instance are required — the definition alone doesn't provision anything.
Stacktape configuration:
The webhookProvider definition configures the backing Lambda. The timeout property controls the maximum execution time in seconds — the default is 10, but here it's set to 30 to allow time for the external API call. The environment property injects a secret using the $Secret directive. The apiWebhook instance references the definition by its resource name ('webhookProvider') and passes resourceProperties that the Lambda receives as event.ResourceProperties.
Lambda handler (src/webhook-provider.ts):
As part of the AWS CloudFormation custom resource protocol, the Lambda must send a response to the pre-signed URL from the event. Always wrap your logic in try/catch and send a response in both success and failure paths.
Writing the handler
The backing Lambda receives a CloudFormation custom resource event. As part of the AWS CloudFormation custom resource protocol, your handler must process the event and send a JSON response to a pre-signed S3 URL provided in the event. The response tells CloudFormation whether the operation succeeded or failed.
Event fields
| Field | Description |
|---|---|
RequestType | Create, Update, or Delete — the stack operation that triggered this invocation |
ResourceProperties | The resourceProperties key-value pairs from the custom resource instance config |
OldResourceProperties | Previous properties (only present on Update) |
PhysicalResourceId | Identifier returned by the previous Create or Update (not present on initial Create) |
ResponseURL | Pre-signed S3 URL where you must PUT the response |
StackId | CloudFormation stack ARN |
RequestId | Unique request identifier |
LogicalResourceId | The resource's logical name in the CloudFormation template |
Response format
Your handler must PUT a JSON response to ResponseURL:
Handler best practices
- Always respond. As part of the AWS CloudFormation custom resource protocol, a missing response causes CloudFormation to wait until its internal timeout and then fail the stack operation.
- Return a stable
PhysicalResourceId. Per CloudFormation behavior, if you return a different physical ID on an Update, CloudFormation interprets this as a resource replacement and sends a separate Delete event for the old physical ID. - Handle Delete gracefully. The Delete handler may run during rollbacks. If the resource was never fully created, your Delete handler should succeed silently rather than throw.
- Keep the
Dataobject small. AWS CloudFormation imposes a 4,096-byte limit on the custom resource response body.
Instances
A CustomResourceInstance references a definition by name and forwards its resourceProperties to the backing Lambda during stack operations. Each instance is an independent CloudFormation resource with its own Create/Update/Delete lifecycle.
| Property | Type | Description |
|---|---|---|
definitionName | string | Name of the CustomResourceDefinition resource in your config that provides the backing Lambda |
resourceProperties | { [name: string]: any } | Key-value pairs passed to the Lambda as event.ResourceProperties during create, update, and delete events |
Multiple instances can share one definition. This is useful when provisioning several similar external resources — DNS records for different subdomains, webhook registrations for different endpoints, or API configurations for different services. Each instance gets its own PhysicalResourceId and lifecycle.
In this example, dnsProvider defines the Lambda that manages DNS records. The timeout is set to 60 seconds — the default is 10. Increase it when external API calls or multi-step provisioning logic may need more time. Two instances — apiDns and appDns — each pass different resourceProperties to create records for different subdomains. Removing either instance from the config triggers a Delete event for that specific record.
When a value in resourceProperties changes between deployments, CloudFormation sends an Update event to the backing Lambda with both the new ResourceProperties and OldResourceProperties. When an instance is removed from the config, CloudFormation sends a Delete event.
Packaging
The packaging property on CustomResourceDefinition configures how the backing Lambda code is built and deployed. Custom resources use the same three Lambda packaging types as functions: js-bundle, buildpack and custom-artifact.
Building from source
js-bundle bundles a JavaScript or TypeScript handler. buildpack builds Python, Java, Go, Ruby, .NET and Rust handlers. Point either one at your handler file and Stacktape handles bundling, dependency installation and upload. You have less control over the exact contents of the deployment package. Use them unless you have a pre-existing build pipeline or need precise control over the deployment artifact.
The timeout is set to 60 seconds here — the default is 10 seconds. Increase it when external API calls or multi-step provisioning logic may need more time.
Custom artifact
The custom artifact mode lets you provide a pre-built zip or directory. Stacktape uploads it as-is (zipping directories automatically). This works with any Lambda runtime since you provide the complete deployment package — unlike js-bundle and buildpack, which handle only the languages listed above. Use custom artifact when you have a custom build pipeline, need dependencies that source-based packaging doesn't handle well, or want precise control over the deployment package contents. The tradeoff is that you are responsible for maintaining the build process, dependency resolution, and artifact structure yourself.
The handler property specifies the entry point in filepath:functionName format (e.g., index.js:handler). The timeout is set to 60 seconds — the default is 10. The memory property sets Lambda memory in MB (128–10,240). CPU scales proportionally — 1,769 MB equals 1 vCPU. If your custom resource handler does CPU-intensive work like data transformation, increase memory to get more CPU. See the Lambda function packaging docs for details on artifact structure and handler format.
Runtime
The runtime property sets the Lambda runtime to a supported AWS Lambda runtime identifier. When using js-bundle or buildpack, the runtime is auto-detected from the entry file extension, so you rarely need to set this explicitly. Set runtime manually when using custom artifact packaging (since there is no entry file for Stacktape to detect from) or when you need to pin a specific runtime version. See the API reference below for the full list of supported runtime values, and the Lambda buildpack docs for how runtime selects the language version.
Connecting to resources
CustomResourceDefinitionProps extends ResourceAccessProps, so a custom resource definition can use connectTo to grant IAM access, security-group access where applicable, and documented STP_[RESOURCE_NAME]_[PARAM] environment variables. This is useful when your provisioning logic needs to read from a database, write to a bucket, or interact with queues.
The backing Lambda receives STP_CONFIG_BUCKET_NAME and STP_CONFIG_BUCKET_ARN as environment variables, and Stacktape grants read/write/delete object permissions to the bucket. The timeout is set to 60 seconds — the default is 10.
Use iamRoleStatements for direct access to AWS services such as Rekognition, Textract, or Bedrock when connectTo does not cover the permission you need:
The iamRoleStatements property adds raw IAM policy statements to the Lambda's execution role. This gives you fine-grained control over permissions for any AWS service.
Outputs
Custom resources are not listed among Stacktape referenceable parameters. You cannot use $ResourceParam() to reference custom resource outputs. If you need to wire values returned by a custom resource's Data response field into other resources in your stack, you can use the overrides escape hatch to work at the CloudFormation layer directly. This is an advanced pattern — use it sparingly and only when you are comfortable working with raw CloudFormation.
API Reference
Custom resource definition
CustomResourceDefinitionPropsCustom resource instance
CustomResourceInstancePropsCustom Resources FAQ
Can I use connectTo with custom resources?
Yes. CustomResourceDefinitionProps extends ResourceAccessProps, so a custom resource definition can use connectTo to grant IAM permissions, security-group access where applicable, and inject STP_[RESOURCE_NAME]_[PARAM] environment variables into the backing Lambda. Your custom resource handler can then interact with databases, buckets, queues, and other stack resources during provisioning. See connecting resources for the full list of injected variables per resource type.
What happens if my custom resource Lambda fails or the stack rolls back?
If the Lambda sends a FAILED response or fails to respond before the timeout, CloudFormation marks the resource as failed and initiates rollback. During rollback, your Delete handler may run against a resource that was never fully created — so write it defensively: check whether the external resource exists before deleting it, and succeed silently if it's already gone. A Delete handler that throws here can leave the resource in a DELETE_FAILED state that requires manual cleanup.
How long can a custom resource Lambda run?
The maximum timeout is 900 seconds (15 minutes), matching the standard AWS Lambda limit. The default in Stacktape is 10 seconds. If your provisioning logic involves slow external APIs or multi-step setup, increase the timeout accordingly.
When should I use a custom resource vs a deployment script?
Use a custom resource when the external resource's lifecycle should be tied to your stack — created on deploy, updated on redeploy, deleted on stack delete. Custom resources participate in CloudFormation's lifecycle and rollback behavior. Use a deployment script for one-shot tasks that don't need lifecycle management: database migrations, cache warming, data seeding, or notifications. Deployment scripts don't require the CloudFormation response protocol and are simpler to write.
Can I create multiple instances from one definition?
Yes. The CustomResourceDefinition defines the Lambda code once. You can create multiple CustomResourceInstance resources that reference the same definition by name, each passing different resourceProperties. Each instance is an independent CloudFormation resource with its own Create/Update/Delete lifecycle. This avoids duplicating Lambda code when provisioning multiple similar external resources — like DNS records for different subdomains or webhook registrations for different endpoints.
Can custom resources return values for use elsewhere in the stack?
Custom resources can return data in the Data field of their CloudFormation response. However, custom resources are not listed among Stacktape referenceable parameters, so you cannot use $ResourceParam() to reference their outputs. For CloudFormation-level output wiring, use the overrides escape hatch if you are comfortable working at the CloudFormation layer.
Does AWS charge for custom resource Lambda invocations?
Custom resource Lambda invocations follow standard AWS Lambda pricing: per-request fee plus duration-based charges proportional to memory allocation. Since the Lambda only runs during stack operations (deploy, update, delete), costs are negligible for most teams — typically a few invocations per deployment. The Lambda is not invoked between deployments, so there is no ongoing compute cost.