Skip to content

Instantly share code, notes, and snippets.

@SlootSantos
Created June 30, 2020 16:55
Show Gist options
  • Save SlootSantos/88734d842186a1d13f527eea91227dc1 to your computer and use it in GitHub Desktop.
Save SlootSantos/88734d842186a1d13f527eea91227dc1 to your computer and use it in GitHub Desktop.
func createCloudfrontDistro(s *session.Session, functionARN string) {
cdnHandler := cloudfront.New(s)
config := &cloudfront.CreateDistributionInput{
DistributionConfig: &cloudfront.DistributionConfig{
CallerReference: aws.String(bucketNameOrigin),
Comment: aws.String(bucketNameOrigin),
Enabled: aws.Bool(true),
Origins: &cloudfront.Origins{ // here we tell cloudfront that we want to use a Bucket as origin
Quantity: aws.Int64(1),
Items: []*cloudfront.Origin{
{
S3OriginConfig: &cloudfront.S3OriginConfig{
OriginAccessIdentity: aws.String(""), // this would have a value if you chose to use an access ID to restrict bucket access
},
Id: aws.String("ORIGIN_ID"),
DomainName: aws.String(bucketNameOrigin + ".s3.amazonaws.com"),
},
},
},
DefaultCacheBehavior: &cloudfront.DefaultCacheBehavior{
MinTTL: aws.Int64(10),
Compress: aws.Bool(true),
TargetOriginId: aws.String("ORIGIN_ID"),
ViewerProtocolPolicy: aws.String("redirect-to-https"),
LambdaFunctionAssociations: &cloudfront.LambdaFunctionAssociations{ // this is where we add Lambda@Edge to our CDN
Items: []*cloudfront.LambdaFunctionAssociation{
{
LambdaFunctionARN: aws.String(functionARN),
IncludeBody: aws.Bool(false),
EventType: aws.String("origin-request"), // you can change the event type according to your needs
},
},
Quantity: aws.Int64(1),
},
ForwardedValues: &cloudfront.ForwardedValues{ // we don't do anything here, but we need to define the nullish config here
QueryString: aws.Bool(false),
Cookies: &cloudfront.CookiePreference{
Forward: aws.String("none"),
},
},
TrustedSigners: &cloudfront.TrustedSigners{
Quantity: aws.Int64(0),
Enabled: aws.Bool(false),
},
},
},
}
_, err := cdnHandler.CreateDistribution(config)
if err != nil {
panic("Could not create CDN" + err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment