silvermine / serverless-plugin-cloudfront-lambda-edge

Adds Lambda@Edge support to Serverless
MIT License
296 stars 41 forks source link

RFC: Environment variable based code injection #76

Open ryanolee opened 2 years ago

ryanolee commented 2 years ago

Intro:

Currently lambda@edge has no support for bundling environment variables along side code. It is commonly recommended when using lambda@edge to use custom headers on origin requests to pass these variables instead. This is often fairly finicky to set up and cannot be used from viewer-request events.

Proposal:

When generating the code bundles for the various lambda functions an option is given to inject environment variables into the process.env by adding a proper definition to the file so they can be set at runtime.

An example of how this might look can be seen below

functions:
  onViewerRequest:
    handler: src/handler.onViewerRequest
    memorySize: 128
    timeout: 5
    lambdaAtEdge:
      distribution: 'TestDistribution'
      eventType: 'viewer-request'
      pathPattern: '/preflight'
      injectEnv: true

a new (optional) option injectEnv would be added to the configuration for lambdaAtEdge. This would default to false and all existing installations of the library should remain uneffected.

When the injectEnv option is set to true the environment variables associated with the function would automatically be prepended (directly in code) to the package. This would effectively bypass the existing limitation.

Caveats

Given this deals with bundled code there are a few limitations to this approach:

POC:

For now a fairly basic POC has been put together to demonstrate how this might work #77

ryanolee commented 2 years ago

Hi @jthomerson , I would be grateful if you could share your opinions on if you think a feature like this would be a reasonable addition to the existing plugin. :rocket: Thanks in advance! -Ryan

khenriksson commented 2 years ago

+1 on this. I've recently had a need for using the environment variable in an edge function, this would be really helpful in that case.

rodrigogs commented 1 year ago

+1 on this. I tried the native Serverless method, but turns out that this plugin still much better.