Skip to content

Instantly share code, notes, and snippets.

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

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.

Step 1: Create an AWS Lambda Function

  1. Access the AWS Management Console and navigate to AWS Lambda.
  2. Click on Create function.
  3. Choose Author from scratch.
    • Function name: Give your function a meaningful name.
    • Runtime: Select Python 3.x
  4. Click on Create function.

Step 2: Add Function Code

  1. 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

  1. Make sure to replace YOUR_CLOUDFRONT_DISTRIBUTION_ID with your actual CloudFront distribution ID (you can find this in the CloudFront console).

Step 3: Set Permissions for the Lambda Function

  1. Go to the Configuration tab of your Lambda function.
  2. Under Permissions, click on the role name linked to your Lambda function.
  3. 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": "*"
        }
    ]
}

Step 4: Configure S3 Event Trigger

  1. Navigate to your S3 bucket (Your Bucket).
  2. Go to the Properties tab and scroll down to Event notifications.
  3. 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.
  4. Save the changes.

Step 5: Test Your Setup

  1. Upload a new file to your S3 bucket.
  2. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment