Lambda@Edge with an existing cloudfront distirbution

Hello!
I’m trying to attached a lambda@edge managed by serverless framework to cloudfront distribution managed by terraform.
More details:
Terraform creates a cloudfront (xxx.cloudfront.net).
I have a lambda at edge function in serverless and I want to attach it to the existing xxx.cloudfront.netdistribution. The below example somehow creates a new distribution:
service: serverless-geo-routing

provider:
  name: aws
  runtime: nodejs10.x

functions:
  lamboGeoLocationQa:
    handler: functions/handler.lamboQa
    events:
      - cloudFront:
          eventType: origin-request
          origin: https://xxx.cloudfront.net

Any ideas on how to do it? Might be a very simple solution, I’m just not that familiar with serverless.
Thanks a lot!

1 Like

I’m facing the same issue where I have a Lambda Edge and I need to attach it to an existing CF Distribution :confused:Have you found something about this?

1 Like

Hi,

This creates only new distribution. It does not attach the Lambda@Edge to existing distribution.

events:
      - cloudFront:
          eventType: origin-request
          origin: https://xxx.cloudfront.net

Relationship between Lambda@Edge function and CloudFront distribution is in definition of the CloudFront distribution.

So first you need to deploy the Lambda@Edge function with necessary permissions and then you need to point CloudFront to exact version of the function.

Steps:

  1. Install plugin: npm install --save-dev @silvermine/serverless-plugin-cloudfront-lambda-edge.
    It attaches necessary permissions, so CloudFront can invoke the Lambda@Edge function.

plugins:
  - '@silvermine/serverless-plugin-cloudfront-lambda-edge'

provider:
  name: aws
  runtime: nodejs10.x

functions:
  lamboGeoLocationQa:
    handler: functions/handler.lamboQa
  1. Deploy the serverless service - serverless deploy
  2. Run serverless info -v and in the output find ARN of version of the lamboGeoLocationQa lambda function.
  3. Put ARN of the version of lamboGeoLocationQa function to Terraform - https://www.terraform.io/docs/providers/aws/r/cloudfront_distribution.html#lambda-function-association
  4. Re-deploy Terraform

When you change source code of lamboGeoLocationQa you will have to repeat the steps 3-6.

I am curious if anybody has found a way to not create a Cloudfront distribution when using Lambda@Edge handlers in Serverless framework? It makes deployments very slow if you have a pre-existing distribution.

Yeah seems like you cannot. I have pre-existing CF distribution already :confused: