Snippets

JimD AWS Codedeploy/Cloudfront

Created by JimD
from __future__ import print_function

import json
import boto3

print('Loading function')
websites = {'codedeployName': 'cloudfrontDistro'}  # codedeploy app name & CF Distro name


def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    message = event['Records'][0]['Sns']['Message']
    parsed_message = json.loads(message)
    application = parsed_message['applicationName']
    deploymentId = parsed_message['deploymentId']
    invalidate_cache(application, deploymentId)
    output = "Application: " + application + ", deployment: " + deploymentId + " cache invalidation submitted."
    print(output)
    return output


def invalidate_cache(application, deploymentId):
    if application in websites:
        client = boto3.client('cloudfront')
        response = client.create_invalidation(
            DistributionId=websites.get(application),
            InvalidationBatch={
                'Paths': {
                    'Quantity': 1,
                    'Items': [
                        '/*',
                    ]
                },
                'CallerReference': deploymentId
            }
        )
        print("Response:" + response)

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.