Last active
March 4, 2020 13:34
-
-
Save rluisr/6175c291d3a790b430da9666c0eebadd to your computer and use it in GitHub Desktop.
Associate lambda function with CloudFront. Get latest version from lambda.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"