Home > database >  Python AWS CDK Custom resource only executes the first time
Python AWS CDK Custom resource only executes the first time

Time:12-09

I have wired up a Python 3.8 lambda function as a custom resource in a cdk stack. The stack ran and triggered off the lambda execution. However on subsequent updates to the stack it does nothing to call the lambda custom resource.

This is the lambda

def lambda_handler(event, context):
   print('lambda executed')
   print('request: {}'.format(json.dumps(event)))
   return { 'PhysicalResourceId': "1234" }

This is how it is wired up in the stack

from constructs import Construct
from aws_cdk import (
    Stack,
    custom_resources as cr,
    aws_lambda as _lambda,
    CustomResource
)

cust_res_lambda = _lambda.Function(
   self, 'crLambda',
   runtime=_lambda.Runtime.PYTHON_3_8,
   code=_lambda.Code.from_asset('my-resources'),
   handler='lambda.lambda_handler',
   function_name='cr_Lambda'
)
        
res_provider = cr.Provider(
   self,'crProvider',
   on_event_handler= cust_res_lambda
)
            
CustomResource(self, 'cust_res',service_token= res_provider.service_token,properties={"curr_account":"4563563","curr_region":"us-east-1", "res_id": ''})

Why isn't the custom resource lambda getting called the second time I deploy the cdk stack?

CodePudding user response:

TL;DR Because your resource hasn't changed.

docs: When you associate a Lambda function with a custom resource, the function is invoked whenever the custom resource is created, updated, or deleted.

In other words, CloudFormation (which lurks behind the CDK abstraction) will invoke your Lambda when the Custom Resource is added to the stack, deleted from the stack, or has its properties changed.1

So, if you want your flavour2 of CR Lambda to be invoked on every deploy, include a timestamp as a property. The timestamp value will change each deploy, causing the CR Lambda to fire with an update event.


  1. This behaviour mimics how CloudFormation treats "regular" resources. If your template is deployed a second time with, say, an unchanged S3 bucket configuration, CloudFormation won't touch it.
  2. Consider the Trigger construct, a higher-level CR implementation that's easier to work with. It has a executeOnEveryDeployment option.
  • Related