CloudBerry Lab Resources
Get started with cloud backup and management solutions
CloudBerry Explorer featured image

How to Automatically Invalidate Dynamic Objects in Amazon CloudFront Using AWS Lambda

Published: by on Post Type: Categories: CloudBerry Explorer

Learn how to leverage Amazon Lambda functionality to automate object invalidation from this step-by-step guide.

If you use Amazon CloudFront for content delivery, the webmaster can set up time frames, in which object in its exact state will be available for users. When this Time-To-Live (TTL) frame elapses, the network consults the origin server and replaces cached copy with the new version. Big TTL allows better performance, while doesn’t allow the webmaster to serve frequently updated content at once. Small TTL in its turn allows to serve updated content faster but reduces page performance (due to multiple cache misses). The solution is to invalidate cached objects in CloudFront edge locations manually (which can consume a lot of time) or automate the process.

How to Create an Amazon Lambda Function to Invalidate Objects in Amazon CloudFront

  • In AWS Console go to AWS Lambda, choose Create a Lambda function, it will show you a set of predefined examples. Skip it and specify a name for your function. Choose Python 2.7 in the Runtime list box.

You can use any other language supported by the service. We are using Python just to demonstrate the concept.

AWS-Lambda-function-code-entry example

  • Copy and paste the following code to the AWS Lambda function code:
from __future__ import print_function

import boto3
import time

def lambda_handler(event, context):
    for items in event["Records"]:
        path = "/" + items["s3"]["object"]["key"]
    print(path)
    client = boto3.client('cloudfront')
    invalidation = client.create_invalidation(DistributionId='E3U10PP27IQTKJ',
        InvalidationBatch={
            'Paths': {
                'Quantity': 1,
                'Items': [path]
        },
        'CallerReference': str(time.time())
    })
  • Define the permissions for your function by choosing Basic Execution IAM role in the Role list box. Use list permissions below to successfully execute the script.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
	{
        "Effect": "Allow",
        "Action": [
            "cloudfront:CreateInvalidation"
        ],
        "Resource": [
            "*"
        ]
    }
  ]
}
  • In Advanced settings choose the amount of memory should be dedicated for processing the code. Keep it 128 MB, as it’s enough.

Configuring-Lambda-function-IAM-role-and-timeout

  • Increase a Timeout for a function, if you have a lot of objects that need invalidation
  • Press Next and choose the Create function
  • In the function edit wizard, go to Event sources and press Add event source

cloudfront-invalidation-aws-lambda-event-sources-configuration

  • Choose S3 as your Event source, then choose your origin bucket and in the Event type, choose Object Created (All) and press Submit

cloudfront-invalidation-aws-lambda-add-event-source-configuration

Conclusion

Now you’ve enabled an AWS Lambda function that invalidates objects in Amazon CloudFront edge locations and synchronizes objects automatically. In practice this means the object will be delivered to the end user as soon as it is uploaded to the origin server, saving a lot of time for a webmaster.

Use CloudBerry Explorer to ensure the success of object invalidation by viewing CloudFront Invalidation List and also to invalidate objects in non-S3 origin distributions.

Know how to improve AWS CloudFront invalidation or our solution? Feel free to share your thoughts in the comment section belowю

Alexander N avatarAuthor
Alexander N
Alexander is the director of marketing at CloudBerry Lab and has been an important member of the company since its inception. He is an expert in IT-marketing and has extensive knowledge of cloud storage services. Alexander cooperates with cloud vendors, MSPs, VAR’s and communicates the market needs and trends to our team. View all posts
Published: by on Post Type: Categories: CloudBerry Explorer
Ratings:
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...