• TechOps

    Need clarity?
    Chat with our experts now

    • Web Hosting SupportWeb Hosting Support
    • Helpdesk Support

      Skilled and professional 24/7 helpdesk support

    • Product Support

      Boost your product support with our expertise

    • Managed ServicesManaged Services
    • Server Management

      Don't let server issues slow you down. Let us manage them for you

    • Server Monitoring

      Safeguard your server health with our comprehensive monitoring solutions

    • Staff AugmentationStaff Augmentation
    • Hire an Admin

      Transform your business operations with our expert administrative support

    • Hire a Team

      Augment your workforce with highly skilled professional from our diverse talent pool

  • CloudOps

    Confused?
    Discuss with our sales team now.

    • Author ProfileAWS
      Well Architected Review
    • Author ProfileFinOps As a Service

      FinOps As a Service

    • Migrate

      Upgrade the journey: Migrate & Modernize seamlessly

    • Modernize

      Effortless CloudOps mastery for seamless cloud management

    • Optimize

      Efficient CloudOps: Boosting performance through optimization

    • Manage

      Simplify compliance complexities with our dedicated service

  • DevOps

    How Supportsages
    is creating an
    impact?

    View Casestudies
    • Author Profile24/7 DevOps As a Service

      Round-the-clock DevOps for uninterrupted efficiency

    • Author ProfileCI/CD Pipeline

      Automated CI/CD pipeline for seamless deployments

    • Author ProfileInfrastructure As a Code

      Crafting infrastructure with ingenious code

    • Author ProfileDevSecOps

      Integrated security in continuous DevOps practices

    • Author ProfileHire DevOps Engineers

      Level up your team with DevOps visionaries

    • Author ProfileConsulting Services

      Navigate success with expert DevOps consulting

  • SecOps

    Expert SecOps Services
    for any Scale

    • Author ProfileVAPT

      Vulnerability Assessment and Penetration Testing

    • Author ProfileSource Code Review

      Ensuring source code security and safe practices to reduce risks

    • Author ProfileSecurity Consultation

      On demand services for improving server security

    • Author ProfileSystem Hardening

      Reduced vulnerability and proactive protection

    • Author ProfileManaged SOC

      Monitors and maintains system security. Quick response on incidents

    • Author ProfileCompliance as a Service

      Regulatory compliance, reduced risk

  • Insights

    Explore our latest
    insights and resources

    Blog

    Explore our latest articles and insights

    Case Studies

    Read about our client success stories

  • Contact Us

  • About
  • Certifications
  • Life at Supportsages
  • Events
  • Contact
  • Careers
  • Blog

  • Dedicated Support Team
  • Quasi-dedicated Support Team
  • Hire a DevOps Engineer
  • Hire a Billing Support Staff
  • Per-ticket Support Plan
  • Managed Services

  • Microsoft Azure Expert
  • AWS Cloud Expert
  • Hire a developer
SS

SupportSages

Bites of wisdom @ work


Copyright © 2008 - 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

Clearing AWS CloudFront Cache: AWS Lambda, Python

Arya P B

  • 3 min read
Clearing AWS CloudFront Cache: AWS Lambda, Python

Generating audio, please wait...

Managing cache invalidation is crucial for delivering updated content to users. AWS CloudFront, a popular Content Delivery Network (CDN), allows you to clear cached content by creating an invalidation. This tutorial demonstrates how to create an AWS Lambda function to automate CloudFront cache invalidation using Boto3, the AWS SDK for Python.

Implementation

1. Set Up Environment Variables

First, set up an environment variable DISTRIBUTION_ID which holds the ID of your CloudFront distribution. This can be done in the Lambda console under the "Configuration" tab or through the AWS CLI.

2. Lambda Function code:

import boto3
import json
import os
from datetime import datetime

def lambda_handler(event, context):
    cloudfront = boto3.client('cloudfront'),
    
    distribution_id = os.getenv('DISTRIBUTION_ID')
    
    if not distribution_id:
        return {
            'statusCode': 400,
            'body': json.dumps('Environment variable DISTRIBUTION_ID not set')
        }
    
    try:
        response = cloudfront.create_invalidation(
            DistributionId=distribution_id,
            InvalidationBatch={
                'Paths': {
                    'Quantity': 1,
                    'Items': ['/*']
                },
                'CallerReference': str(context.aws_request_id)
            }
        )
        
        # Convert datetime objects to strings recursively in the response
        def convert_datetime(obj):
            if isinstance(obj, datetime):
                return obj.isoformat()
            elif isinstance(obj, dict):
                return {k: convert_datetime(v) for k, v in obj.items()}
            elif isinstance(obj, list):
                return [convert_datetime(i) for i in obj]
            else:
                return obj

        return {
            'statusCode': 200,
            'body': json.dumps(convert_datetime(response))
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps(str(e))
        }

3. Explanation of the Code

  • Environment Variable Check: The function first checks if the DISTRIBUTION_ID environment variable is set. If not, it returns a 400 status code with an error message.
  • Creating Invalidation: The cloudfront.create_invalidation method is called to create an invalidation for the specified distribution. The invalidation path is set to /* to clear the entire cache.
  • Handling Response: The response from the create_invalidation call contains datetime objects. A helper function convert_datetime is used to recursively convert these datetime objects to strings for JSON serialization.
  • Error Handling: If any exception occurs during the process, the function catches it and returns a 500 status code with the error message.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "cloudfront:CreateInvalidation"
            ],
            "Resource": "*"
        }
    ]
}

This policy allows the Lambda function to create invalidations in any CloudFront distribution.

Testing the Function

Invoke the function manually or set up a trigger (e.g., an API Gateway, S3 event, etc.) to test if it invalidates the CloudFront cache as expected.

Conclusion

By following these steps, you have automated the process of invalidating AWS CloudFront cache using a Lambda function. This ensures that your users always get the most up-to-date content. Feel free to extend this function to handle specific paths or integrate it into your deployment pipeline for automatic cache invalidation on updates.

Optimize your content delivery process by implementing this automated CloudFront cache invalidation solution today! Follow the steps in this tutorial to ensure your users always receive the latest content, enhancing their overall experience.

  • DevOps

Looking for AWS Experts?

We provide top-of-the-line custom AWS setup services tailored to your needs.

Clearing AWS CloudFront Cache: AWS Lambda, Python

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • AWS
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Posts by Arya P B

Athena