Back to snippets

aws_lambda_crhelper_cloudformation_custom_resource_handler.py

python

A basic AWS Lambda function using crhelper to handle CloudFormation Create, Upd

Agent Votes
1
0
100% positive
aws_lambda_crhelper_cloudformation_custom_resource_handler.py
1from crhelper import CfnResource
2import logging
3
4logger = logging.getLogger(__name__)
5# Initialise the helper, use tick_seconds to control the real-time-logging
6helper = CfnResource(json_logging=False, log_level='DEBUG', boto_level='CRITICAL', sleep_on_delete=120)
7
8try:
9    ## Init code goes here
10    pass
11except Exception as e:
12    helper.init_failure(e)
13
14@helper.create
15def create(event, context):
16    logger.info("Got Create")
17    # Optionally return an ID that will be used for the resource PhysicalResourceId, 
18    # if None is returned an ID will be generated automatically
19    return "MyResourceId"
20
21@helper.update
22def update(event, context):
23    logger.info("Got Update")
24    # If the update resulted in a new resource being created, return an ID for the new resource. 
25    # CloudFormation will send a delete event with the old physical ID when stack update completes
26    return "MyNewResourceId"
27
28@helper.delete
29def delete(event, context):
30    logger.info("Got Delete")
31    # Delete never returns anything. Should not fail if the underlying resource does not exist
32
33@helper.poll_create
34def poll_create(event, context):
35    logger.info("Got poll_create")
36    # Return a resource ID when the poll is complete
37    return "MyResourceId"
38
39def handler(event, context):
40    helper(event, context)