Created
November 29, 2016 06:35
-
-
Save SteveHoggNZ/d4a091e80e1e403a852ba7fa8a1dd8d7 to your computer and use it in GitHub Desktop.
CloudFormation / CustomResource / minimal Python Lambda function for logging resource update requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import json | |
import logging | |
import urllib2 | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
SUCCESS = 'SUCCESS' | |
FAILED = 'FAILED' | |
def lambda_handler(event, context): | |
logger.info("Received event. Full parameters: {}".format(json.dumps(event))) | |
response = { | |
"StackId": event["StackId"], | |
"RequestId": event["RequestId"], | |
"LogicalResourceId": event["LogicalResourceId"], | |
"Status": SUCCESS, | |
"Data": { | |
"Test": "true" | |
} | |
} | |
if event.get("PhysicalResourceId", False): | |
response["PhysicalResourceId"] = event["PhysicalResourceId"] | |
else: | |
response["PhysicalResourceId"] = event["LogicalResourceId"] + "-12345" | |
serialized = json.dumps(response) | |
logger.info("Responding with: %s" % (serialized)) | |
req = urllib2.Request( | |
event['ResponseURL'], data=serialized, | |
headers={'Content-Length': len(serialized), | |
'Content-Type': ''} | |
) | |
req.get_method = lambda: 'PUT' | |
try: | |
urllib2.urlopen(req) | |
logger.debug("Request to CFN API succeeded, nothing to do here") | |
except urllib2.HTTPError as e: | |
logger.error("Callback to CFN API failed with status %d" % e.code) | |
logger.error("Response: %s" % e.reason) | |
except urllib2.URLError as e: | |
logger.error("Failed to reach the server - %s" % e.reason) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on: https://serverlesscode.com/post/python-custom-resource-cloudformation/
Specifically: https://github.com/ryansb/cfn-wrapper-python/blob/master/cfn_resource.py