2 minutes
Invalidating CloudFront Distribution using Lambda function
AWS CloudFront Distribution may serve outdated content from Amazon S3. CloudFront caches response from S3 for 24 hours [Default TTL
of 86,400 seconds]. One way to push the updated S3 content to the distribution is by Invalidating the S3 objects. This can be done via AWS console by navigating to the CloudFront Distribution -> Invalidation Tab -> Create Invalidation button
or via AWS CLI using below command:
$ aws cloudfront create-invalidation --distribution-id XXXXXXXXXX --paths /\*
The same can also be achieved in an automated way using an AWS Lambda function.
In AWS Console, navigate to Lamda -> Functions -> Create Functions
. Choose Author from Scratch
. Input the function name, Runtime is Python 2.7. In the Execution role, Create a new role with basic Lambda permissions if you don’t have it yet then click Create Function.
In the Function Configuration tab, click the function name in the Designer window. Scroll down and paste below code in the .py window. Make sure to update <change_with_distribution_id>
with your own distribution Id.
from __future__ import print_function
import boto3
import time
def lambda_handler(event, context):
path = []
for items in event["Records"]:
path.append("/")
print(path)
client = boto3.client('cloudfront')
invalidation = client.create_invalidation(DistributionId='<change_with_distribution_id>',
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': path
},
'CallerReference': str(time.time())
})
Go back to the Designer window and click Add Trigger
. Select S3
, then select your bucket name where your static files are stored. In the event type, select All Object create events
.
Click Save to save all your changes.
To test the function, upload new version of your static files in your S3 bucket. The S3 trigger will be invoked and this will call the Lambda function to create Invalidation in your CloudFront distribution.