Leveraging Custom Resources in AWS CloudFormation
Tags: aws, awcommunity, cloudformation, cdk
Published: 2024-03-03 12:44:00

---
title: Leveraging Custom Resources in AWS CloudFormation
published: true
description: Leveraging Custom Resources in AWS CloudFormation
tags: #AWS #awcommunity #cloudformation #cdk
cover_image: https://cdn-images-1.medium.com/v2/resize:fit:800/1*YWTyx6YZXwOEVLiUo9dp9Q.png
# Use a ratio of 100:42 for best results.
published_at: 2024-03-03 13:44 +0100
---

AWS CloudFormation is a powerful AWS infrastructure-as-code service, it enables you to define and provision AWS infrastructure resources in a declarative way using JSON or YAML templates. These templates describe the desired state of the AWS environment, including resources such as VPCs, EC2 instances, S3 buckets, Step Functions, Lambda functions, and more. CloudFormation automates the provisioning and management of these resources, making it easier to deploy and maintain complex AWS architectures.

### Limitations of CloudFormation

While CloudFormation is an efficient tool for managing AWS resources, it does have some limitations. One major limitation is its inability to directly interact with external systems or perform actions beyond the scope of AWS services. This can be restrictive when needing to integrate with external APIs and databases or perform custom actions during stack creation or updates.

### Introducing Custom Resource

To overcome the limitations of CloudFormation, AWS provides Custom Resources. Custom Resources allow you to extend CloudFormation's capabilities by incorporating custom logic or integrating with external systems during stack creation, update, or deletion. Essentially, Custom Resources enables you to define and manage AWS resources that are not natively supported by CloudFormation.

### Other Use Cases of Custom Resource

Custom Resources can be utilized for various use cases, including:

1. **Integration with External Systems**: Execute custom logic or interact with external APIs, databases, or services during stack operations.
2. **Dependency Management**: Manage dependencies between AWS resources that are not directly supported by CloudFormation.
3. **Configuration Management**: Dynamically configure resources based on parameters or conditions not directly supported by CloudFormation.
4. **Data Transformation**: Perform data transformations or enrichments during resource creation or updates.

### CloudFormation for Creating Custom Resource

```yaml
Resources:
  MyCustomResource:
    Type: Custom::MyCustomResource
    Properties:
      ServiceToken: arn:aws:lambda:REGION:ACCOUNT_ID:function:MyCustomResourceFunction
      ResourceName: MyResource
```


### CDK Code for Creating a Custom Resource

```typescript
import * as cdk from '@aws-cdk/core';
import * as lambda from '@aws-cdk/aws-lambda';
import * as cr from '@aws-cdk/custom-resources';

export class MyCustomResourceStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Define the Lambda function for the Custom Resource
    const myLambdaFunction = new lambda.Function(this, 'MyCustomResourceHandler', {
      runtime: lambda.Runtime.NODEJS_20_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('lambda'),
    });

    // Define the Custom Resource Provider
    const myProvider = new cr.Provider(this, 'MyCustomResourceProvider', {
      onEventHandler: myLambdaFunction,
    });

    // Create the Custom Resource
    new cdk.CustomResource(this, 'MyCustomResource', {
      serviceToken: myProvider.serviceToken,
      properties: {
        // Custom properties for the resource if needed
      },
    });
  }
}
```
### When to Use AwsCustomResource and Provider

AWS CDK offers two primary mechanisms for implementing Custom Resources: `AwsCustomResource` and `Provider`.

**AwsCustomResource**: It provides a means to extend CloudFormation's capabilities by integrating custom AWS-specific logic seamlessly into the stack operations. You can use this when you have simple Custom Resource requirements and prefer a more streamlined, high-level abstraction. It's suitable for quick implementations and scenarios where simplicity outweighs advanced customization.

**Provider**: When the necessity arises to communicate with external systems or services beyond the AWS ecosystem, the Provider mechanism is utilized. It allows for the integration with external APIs or services through the use of Lambda functions or SDKs. With Providers, custom logic can be efficiently managed to orchestrate interactions with external systems as part of the CloudFormation stack operations.



### Conclusion

Custom Resources offers a powerful way to extend the capabilities of AWS CloudFormation beyond its native functionalities. By leveraging Custom Resources, developers can integrate with external systems, perform custom actions, and manage dependencies more effectively within CloudFormation templates. Whether it's executing AWS API calls or interacting with external services, Custom Resources provides the flexibility needed to orchestrate complex AWS environments seamlessly.

Read more on Custom Resource:
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.custom_resources.AwsCustomResource.html

https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.custom_resources.Provider.html

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-customresource.html#cfn-cloudformation-customresource-servicetoken