To automate invalidations for your CloudFront distribution associated with the S3 bucket follow these step-by-step instructions. This setup will utilize an AWS Lambda function triggered by S3 events to automatically invalidate the CloudFront cache whenever new content is uploaded.
- Access the AWS Management Console and navigate to AWS Lambda.
- Click on Create function.
- Choose Author from scratch.
- Function name: Give your function a meaningful name.
- Runtime: Select Python 3.x
- Click on Create function.
- In the function code editor, replace the default code with the following Python code:
import boto3
import time
def lambda_handler(event, context):
client = boto3.client('cloudfront')
distribution_id = 'YOUR_CLOUDFRONT_DISTRIBUTION_ID' # Replace with your distribution ID
for record in event['Records']:
path = "/" + record['s3']['object']['key']
print(f"Invalidating path: {path}")
invalidation = client.create_invalidation(
DistributionId=distribution_id,
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': [path]
},
'CallerReference': str(time.time())
}
)
print(f"Invalidation created: {invalidation['Invalidation']['Id']}")
Code Breakdown for more understanding Click Here
- Make sure to replace
YOUR_CLOUDFRONT_DISTRIBUTION_ID
with your actual CloudFront distribution ID (you can find this in the CloudFront console).
- Go to the Configuration tab of your Lambda function.
- Under Permissions, click on the role name linked to your Lambda function.
- In the IAM console, attach a new policy with the following permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"cloudfront:CreateInvalidation"
],
"Resource": "*"
}
]
}
- Navigate to your S3 bucket (
Your Bucket
). - Go to the Properties tab and scroll down to Event notifications.
- Click on Create event notification:
- Name: Give it a name
- Event types: Select
All object create events
. - Destination: Choose
Lambda Function
and select your newly created Lambda function.
- Save the changes.
- Upload a new file to your S3 bucket.
- You can also check the CloudFront console under Invalidations to see if the invalidation popup there.
By following these steps, you will have set up an automated process that invalidates cached content in your CloudFront distribution whenever new content is uploaded to your S3 bucket, ensuring that users always receive the latest version of your static site.