import boto3
import time
boto3
: AWS SDK for Python, used to interact with AWS servicestime
: Used to generate a unique caller reference for CloudFront invalidation
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
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
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
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 invalidateQuantity
: Number of paths to invalidateItems
: List of paths to invalidate
CallerReference
: Unique identifier to prevent duplicate invalidations- Uses current timestamp as a unique reference
print(f"Invalidation created: {invalidation['Invalidation']['Id']}")
- Logs the unique ID of the created invalidation
This Lambda function is typically triggered by S3 object uploads/updates to automatically invalidate the corresponding CloudFront cache, ensuring immediate content updates.
- 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