I use CloudFormation to configure my site’s resources. Because this Lambda function is small, I inline its source code in the template.
DON'T FORGET TO UPDATE THE FUNCTION VERSION TOO comment came from hard-to-debug missed updates.
It’s unfortunately not possible to configure CloudFront to always use the latest version of a Lambda function.
Instead we need to create a new
AWS::Lambda::Version each time, and not delete the old one with
(More on this in my previous post.)
The data formats are the same between the two languages, so the code is essentially a transliteration.
Python comes in at slightly fewer lines of code, but this is due to basic language differences: no need for braces or the
'use strict' incantation.
Second, I updated my CloudFront distribution to use the new function and deployed:
I thought this code was “simple enough” that there couldn’t be any bugs, given it was valid Python syntax.
As you can see from the name in the template, it took me six iterations to get the code correct. As CloudFront takes 30 painful minutes to update its configuration, this took some time. I ended up putting on a film to wait them out!
(The 2004 Van Helsing if you want to know!)
My site was down whilst I had the bad versions of my code in place.
One useful thing I only checked for after a couple iterations was the “Configure test event” button on the Lambda console. It turns out it comes with many CloudFront examples. One was exactly my use case, and if I’d used it from the start I would have finished in half the time.
If only I’d read the CloudFront manual section Testing and debugging.
If I were to try this again, I would keep the code in a separate file and test it with pytest. I’d start with the test event from the Lambda console and change it for different scenarios. I think I would have caught most of my mistakes with such unit testing. I’ve done similar before for boto3 based code.
Since the function was no longer in use it luckily didn’t another CloudFront update.
This was a slow exercise. CloudFront is getting more features, and I found debugging my Lambda@Edge function a bit less painful with the function metrics. But the slow iteration times still make it painful to change regularly.
Anyway, I hope this helps you work with Python on your Lambda@Edge functions,
Interested in Django or Python training? I'm taking bookings for workshops.
One summary email a week, no spam, I pinky promise.
- Scoring A+ for Security Headers on My Cloudfront-Hosted Static Website
- Scoring A+ for SSL Labs on My Cloudfront-Hosted Static Website
- Validating CloudFormation Templates With cfn-lint
© 2020 All rights reserved.