Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vishnumitraha/e10cdc25a7d64fa0a89010ce5b889b47 to your computer and use it in GitHub Desktop.
Save vishnumitraha/e10cdc25a7d64fa0a89010ce5b889b47 to your computer and use it in GitHub Desktop.

AWS Lambda Function for CloudFront Invalidation

Code Breakdown

1. Import Statements

import boto3
import time
  • boto3: AWS SDK for Python, used to interact with AWS services
  • time: Used to generate a unique caller reference for CloudFront invalidation

2. Lambda Handler Function

def lambda_handler(event, context):
  • Standard AWS Lambda function signature
  • Receives two parameters:
    • event: Contains trigger information (in this case, S3 event)
    • context: Runtime information about the Lambda execution

3. CloudFront Client Initialization

client = boto3.client('cloudfront')
distribution_id = 'YOUR_CLOUDFRONT_DISTRIBUTION_ID'
  • Creates a boto3 client for CloudFront
  • distribution_id is the unique identifier for the CloudFront distribution

4. Event Record Processing

for record in event['Records']:
    path = "/" + record['s3']['object']['key']
    print(f"Invalidating path: {path}")
  • Iterates through S3 event records
  • Extracts the object key and prepends a "/" to create a CloudFront path
  • Logs the path being invalidated

5. CloudFront Invalidation

invalidation = client.create_invalidation(
    DistributionId=distribution_id,
    InvalidationBatch={
        'Paths': {
            'Quantity': 1,
            'Items': [path]
        },
        'CallerReference': str(time.time())
    }
)
  • Creates an invalidation request for the specific CloudFront distribution
  • Paths: Specifies which objects to invalidate
    • Quantity: Number of paths to invalidate
    • Items: List of paths to invalidate
  • CallerReference: Unique identifier to prevent duplicate invalidations
    • Uses current timestamp as a unique reference

6. Invalidation Confirmation

print(f"Invalidation created: {invalidation['Invalidation']['Id']}")
  • Logs the unique ID of the created invalidation

Use Case

This Lambda function is typically triggered by S3 object uploads/updates to automatically invalidate the corresponding CloudFront cache, ensuring immediate content updates.

Key Considerations

  • Replace 'YOUR_CLOUDFRONT_DISTRIBUTION_ID' with your actual distribution ID
  • Ensure Lambda has appropriate IAM permissions for CloudFront invalidation
  • Be mindful of CloudFront invalidation limits and potential costs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment