AWS CloudFormation CGT (Custom Resource Generator Templates) allows you to automate the provisioning of AWS resources that are not natively supported by standard CloudFormation resource types. By using a Lambda function as a backend provider, you can execute custom logic during the stack creation, update, or deletion phases, effectively extending the capabilities of Infrastructure as Code (IaC) to include third-party API calls, complex configuration scripts, or legacy system integrations.

What You'll Need

  • An active AWS Account with administrative permissions or a specific IAM role allowing CloudFormation and Lambda management.
  • The AWS Management Console or the AWS CLI installed and configured on your local machine.
  • A basic understanding of JSON or YAML for template authoring.
  • A defined logic for what the custom resource needs to achieve (e.g., calling an external API to register a domain or configuring a software setting inside an EC2 instance).

Step-by-Step

  1. Define the Custom Resource Logic
    Before touching the CloudFormation template, you must create the logic that will handle the resource lifecycle. This is typically done via an AWS Lambda function. The function must be written to handle three specific event types: Create, Update, and Delete. Ensure your code includes a mechanism to send a response signal back to the CloudFormation pre-signed S3 URL; if the function finishes without sending this signal, the CloudFormation stack will hang for several hours before timing out.
  2. Create the Lambda Execution Role
    Navigate to the IAM console and create a role for your Lambda function. This role needs basic execution permissions (CloudWatch Logs) and any specific permissions required to perform the custom action (such as permissions to modify a different AWS service or access a specific secret in Secrets Manager). Note that labels and permission names may differ slightly depending on your AWS region or account version.
  3. Deploy the Lambda Function
    Upload your code to the Lambda console. Ensure the handler is correctly mapped and the timeout is set appropriately for the task. If your custom resource involves calling a slow external API, increase the timeout from the default 3 seconds to something more substantial, like 30 seconds or 1 minute, to prevent the function from timing out before it can signal success back to CloudFormation.
  4. Author the CloudFormation Template
    In your YAML or JSON template, define a resource of type Custom::MyResourceName. The Custom:: prefix is mandatory; it tells CloudFormation that this is not a native AWS resource and requires a provider. Under the Properties section, you must include a ServiceToken. The value of the ServiceToken must be the ARN (Amazon Resource Name) of the Lambda function you created in step 3.
  5. Pass Parameters to the Custom Resource
    Add any necessary configuration data under the Properties section of your custom resource. These values are passed to the Lambda function as part of the ResourceProperties object in the event payload. For example, if you are using the custom resource to create a user in a third-party SaaS tool, you would pass the Username and Email as properties here.
  6. Deploy the Stack
    Upload your template via the CloudFormation console or use the command aws cloudformation create-stack --stack-name my-custom-stack --template-body file://template.yaml. Monitor the Events tab in the console. You will see the resource move from CREATE_IN_PROGRESS to CREATE_COMPLETE once your Lambda function sends the success signal.
  7. Verify the Output
    If your custom resource generates a value (like an ID or a URL from an external system), have your Lambda function include that value in the Data field of the response signal. You can then reference this value in other parts of your CloudFormation template using the Fn::GetAtt intrinsic function.

Common Mistakes

The most frequent error when implementing custom resources is failing to send the response signal. CloudFormation does not automatically know if your Lambda function succeeded or failed; it waits for a PUT request to a specific S3 URL provided in the event object. If your code crashes or reaches a timeout without sending this request, the entire stack will remain in CREATE_IN_PROGRESS until the AWS default timeout is reached, which can take hours and block subsequent deployments.

Another common mistake is neglecting the Delete event. Many developers focus entirely on the Create logic. However, when a stack is deleted, CloudFormation sends a Delete request to the Lambda function. If your code does not explicitly handle the Delete event and send a success signal back, the stack deletion will hang, forcing you to manually delete the resource or use the "skip" option, which can leave orphaned resources in your environment.

Hardcoding the ServiceToken is also a common pitfall. In a professional environment, you should use parameters or references to ensure that the same template can be deployed across Development, Staging, and Production accounts without manually editing the ARN of the Lambda function every time.

Tips

To make your custom resources more robust, implement a try-catch-finally block in your Lambda code. Place the response signal logic inside the finally block to ensure that regardless of whether the operation succeeded or failed, a signal is sent back to CloudFormation. This prevents the dreaded "hanging stack" scenario.

Use the PhysicalResourceId property wisely. When an Update event occurs, CloudFormation compares the PhysicalResourceId of the old resource with the new one. If you return a new ID, CloudFormation treats it as a replacement: it will create the new resource first and then send a Delete request for the old one. If you return the same ID, it is treated as an in-place update.

For complex logic, consider using the AWS CloudFormation Registry to create a formal Resource Provider rather than a simple Custom Resource. While more complex to set up, the Registry provides better versioning and integration with the AWS ecosystem.

Troubleshooting

If your stack is stuck in CREATE_IN_PROGRESS, the first step is to check the CloudWatch Logs for your Lambda function. Look for execution errors, timeouts, or permission denied messages. If the logs show that the function executed successfully but the stack is still hanging, verify that your code is actually sending the HTTP PUT request to the ResponseURL provided in the event payload.

If you encounter a Permission Denied error in the logs, check the IAM role assigned to the Lambda function. Ensure it has the necessary permissions to interact with the services or APIs it is calling. If the Lambda is calling an internal AWS service, ensure the policy is not too restrictive.

If you need to force a stack to finish when it is hanging, you can attempt to delete the stack. If the deletion also hangs, you can choose the option to "retain" the custom resource. This tells CloudFormation to ignore the resource and proceed with deleting the rest of the stack. Warning: This will leave the actual resource (the one created by your Lambda) active in your environment, and you will have to delete it manually.

Frequently Asked Questions

What happens if the Lambda function fails?

If the Lambda function sends a signal with a status of FAILED, CloudFormation will mark the resource as failed and initiate a stack rollback, deleting any other resources created during that session.

Can I use a custom resource to call an API outside of AWS?

Yes, this is one of the primary use cases. As long as the Lambda function has internet access (via a VPC NAT Gateway or by being outside a VPC), it can make HTTP requests to any external API.

Is there a limit to how many custom resources I can have?

There is no specific limit on the number of custom resources, but you are subject to the standard CloudFormation resource limit per template and the concurrency limits of your Lambda functions.

How do I pass data from a custom resource to another resource?

The Lambda function should include the data in the Data field of the response. You can then access this in the template using Fn::GetAtt [ResourceName, AttributeName].

Do custom resources cost extra?

CloudFormation itself is free for AWS resources. However, you pay for the AWS Lambda executions and any other AWS services your custom logic invokes based on standard pricing.