Last active
March 7, 2024 13:45
-
-
Save mikebroberts/09e8c8b4aaac6e26149c4622fd492414 to your computer and use it in GitHub Desktop.
CloudFront Functions Demo with CloudFormation
This file contains hidden or 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
Description: CloudFront Functions Demo | |
# This example shows how to use CloudFront, CloudFront Functions, and CloudFormation. | |
# In this simple example we setup CloudFront so that on any request we redirect to another site. | |
# While basic, this example can be expanded to provide typical redirect scenarios, based | |
# on the event passed to the function. | |
# This example written by Mike Roberts (https://twitter.com/mikebroberts), Symphonia. | |
# For more ideas about using AWS more effectively,see our blog at https://blog.symphonia.io/ | |
Parameters: | |
RedirectDomainName: | |
Type: String | |
Default: www.google.com | |
Outputs: | |
# Go to the value of this output in a browser, and you'll be redirected to the domain specified in RedirectDomainName | |
CloudfrontDomainName: | |
Value: !GetAtt CloudFrontDistribution.DomainName | |
Resources: | |
CloudFrontDistribution: | |
Type: AWS::CloudFront::Distribution | |
Properties: | |
# This example doesn't set custom aliases, but those can be added in the usual way | |
DistributionConfig: | |
Enabled: true | |
DefaultCacheBehavior: | |
TargetOriginId: redirectOrigin | |
ViewerProtocolPolicy: 'redirect-to-https' | |
# "Managed-CachingDisabled" from https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html | |
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad | |
FunctionAssociations: | |
- EventType: viewer-request | |
FunctionARN: !GetAtt RedirectFunction.FunctionMetadata.FunctionARN | |
# CloudFront requires at least one origin, even though we're always going to redirect | |
Origins: | |
- DomainName: !Ref RedirectDomainName | |
Id: redirectOrigin | |
CustomOriginConfig: | |
OriginProtocolPolicy: match-viewer | |
RedirectFunction: | |
Type: AWS::CloudFront::Function | |
Properties: | |
AutoPublish: true | |
FunctionCode: !Sub | | |
function handler(event) { | |
return { | |
statusCode: 302, | |
statusDescription: 'Found', | |
headers: { | |
location: { value: 'https://${RedirectDomainName}/' } | |
} | |
} | |
} | |
FunctionConfig: | |
Comment: !Sub 'Redirect to ${RedirectDomainName}' | |
Runtime: cloudfront-js-1.0 | |
Name: !Sub "${AWS::StackName}-redirectFunction" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OK thanks. I have started investigating the
AWS-CLI
cloudfront create-function
command where you can now reference an external JS file like this: