cfnresponse

1.1.5 · active · verified Thu Apr 16

cfnresponse is a micro Python package designed to simplify sending responses from AWS Lambda functions acting as custom resources back to AWS CloudFormation. It abstracts the HTTP call to the pre-signed S3 URL provided by CloudFormation, ensuring that stack operations (create, update, delete) complete successfully or fail gracefully. The current version is 1.1.5, and releases are infrequent, primarily for updates related to AWS Lambda runtime environments or underlying HTTP client changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a typical AWS Lambda handler function for a CloudFormation custom resource using cfnresponse. It handles 'Create', 'Update', and 'Delete' request types, sends a success or failure response back to CloudFormation, and includes basic error handling. The `physical_resource_id` is crucial for tracking the resource lifecycle.

import json
import cfnresponse

def handler(event, context):
    print("Received event: " + json.dumps(event))

    # Default to SUCCESS
    status = cfnresponse.SUCCESS
    reason = None
    physical_resource_id = event.get('PhysicalResourceId', context.log_stream_name)
    response_data = {}

    try:
        if event['RequestType'] == 'Create':
            # Implement creation logic here
            response_data['Message'] = 'Resource created successfully!'
            # Often a unique ID for the resource is set as PhysicalResourceId
            physical_resource_id = 'my-unique-resource-id'
        elif event['RequestType'] == 'Update':
            # Implement update logic here
            response_data['Message'] = 'Resource updated successfully!'
        elif event['RequestType'] == 'Delete':
            # Implement deletion logic here
            response_data['Message'] = 'Resource deleted successfully!'

    except Exception as e:
        status = cfnresponse.FAILED
        reason = f'Lambda function failed: {str(e)}'
        response_data['Error'] = str(e)
        print(f"Error: {e}")

    finally:
        cfnresponse.send(event, context, status, response_data, physical_resource_id, reason=reason)
        # Note: Any code after cfnresponse.send is generally not executed as the Lambda terminates.

view raw JSON →