Skip to content

Instantly share code, notes, and snippets.

@rluisr
Last active March 4, 2020 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rluisr/6175c291d3a790b430da9666c0eebadd to your computer and use it in GitHub Desktop.
Save rluisr/6175c291d3a790b430da9666c0eebadd to your computer and use it in GitHub Desktop.
Associate lambda function with CloudFront. Get latest version from lambda.
#!/usr/bin/env bash
set -eu
readonly CF_ID=<CloudFront ID>
readonly CF_PATH="/*" # purging by URL
readonly LAMBDA_ARN="<Lambda ARN>"
CF_CONFIG=$( aws cloudfront get-distribution-config --id ${CF_ID} | jq '.DistributionConfig' )
CF_ETAG=$( aws cloudfront get-distribution-config --id ${CF_ID} | jq -r '.ETag' )
LAMBDA_VERSION=$( aws lambda list-versions-by-function --function-name ${LAMBDA_ARN} --region us-east-1 | jq -r '.Versions[-1].Version' )
echo ${CF_CONFIG} | jq ".DefaultCacheBehavior.LambdaFunctionAssociations.Items[0].LambdaFunctionARN = \"${LAMBDA_ARN}:${LAMBDA_VERSION}\"" > update.json
aws cloudfront update-distribution --id ${CF_ID} --distribution-config file://update.json --if-match ${CF_ETAG}
aws cloudfront create-invalidation --distribution-id ${CF_ID} --paths "${CF_PATH}"
echo "finish"
Copy link

ghost commented Aug 14, 2019

This is purely genius!

I cannot believe how hard it is to achieve that nowadays... No support for Lambda@Edge on neither https://www.terraform.io/ nor https://serverless.com/

Thanks a million for that gist!

PS: using jq@1.6, I had to use the --raw-output flag for the versioned ARN to be properly formatted:

"arn:aws:lambda:us-east-1:{ACCOUNT_ID}:function:{FUNCTION_NAME}:1"

Instead of:

"arn:aws:lambda:us-east-1:{ACCOUNT_ID}:function:{FUNCTION_NAME}":"1"

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