-
-
Notifications
You must be signed in to change notification settings - Fork 249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add environment variable support to Lambda@Edge functions #334
feat: Add environment variable support to Lambda@Edge functions #334
Conversation
📝 WalkthroughWalkthroughThe pull request introduces environment variable support to Lambda@Edge functions. In the Terraform example, an Changes
Possibly related PRs
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
examples/complete/lib/index.js (1)
9-9
: Add error handling for the environment variable.The code directly uses
process.env.MY_RESPONSE_HEADER
without checking if it's defined. While this works for the example, in production code you might want to add a fallback value.Consider adding a fallback value:
- headers['x-my-response-header'] = [{ key: 'X-My-Response-Header', value: process.env.MY_RESPONSE_HEADER }]; + headers['x-my-response-header'] = [{ key: 'X-My-Response-Header', value: process.env.MY_RESPONSE_HEADER || 'Default Value' }];modules/lambda@edge/variables.tf (1)
16-17
: Update documentation to clarify Lambda@Edge environment variable limitations.The documentation correctly references the Lambda function resource, but it would be helpful to reference the Lambda@Edge specific limitations for environment variables.
- `runtime`, `handler`, `memory_size`, `environment` and `timeout` correspond to the attributes of the same name in the [lambda_function](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) - resource. See [here](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-edge-function-restrictions.html) for Lambda@Edge function restrictions. + `runtime`, `handler`, `memory_size`, `timeout` and `environment` correspond to the attributes of the same name in the [lambda_function](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) + resource. Note that for Lambda@Edge functions, environment variables are only accessible when the function is created in the US East (N. Virginia) region. + See [here](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-edge-function-restrictions.html) for additional Lambda@Edge function restrictions.modules/lambda@edge/README.md (1)
75-75
: Clarify Module-Level Environment Input DescriptionThe module-level
environment
input (line 75) is described as an "ID element" used for region or role identification. With the introduction of function-level environment variable configuration, this description could be misinterpreted. It would be beneficial to clarify that this input is distinct from the per-function environment variables—perhaps by expanding the description or using a different naming convention if appropriate.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
examples/complete/lambda-at-edge.tf
(1 hunks)examples/complete/lib/index.js
(1 hunks)modules/lambda@edge/README.md
(1 hunks)modules/lambda@edge/main.tf
(1 hunks)modules/lambda@edge/variables.tf
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`examples/complete/*.tf`: This is framework for testing and ...
examples/complete/*.tf
: This is framework for testing and standards are very relaxed, plus certain things need to be certain ways for testing. Exclude from review unless you find misspelling or similar error in comments or serious errors in code.
examples/complete/lambda-at-edge.tf
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Summary
🔇 Additional comments (3)
examples/complete/lambda-at-edge.tf (1)
49-53
: LGTM! Environment variable configuration looks good.The addition of the environment block with the
MY_RESPONSE_HEADER
variable is correctly implemented and aligns with the PR's objective.modules/lambda@edge/variables.tf (1)
34-36
: LGTM! The environment variable structure is correctly defined.The environment variable structure follows the standard Terraform pattern for Lambda functions.
modules/lambda@edge/README.md (1)
76-76
: Good Addition of Function-Specific Environment Variable SupportThe updated
functions
input now includes the newenvironment
attribute set as an optional object with avariables
map. This clearly enables the configuration of environment variables for individual Lambda@Edge functions. Please ensure that the examples (e.g., inexamples/complete/lambda-at-edge.tf
andexamples/complete/lib/index.js
) are updated to demonstrate how to use this new capability.
dynamic "environment" { | ||
for_each = each.value.environment != null ? [each.value.environment] : [] | ||
content { | ||
variables = environment.value.variables | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Verify Lambda@Edge environment variable functionality.
The dynamic block implementation is correct. However, it's important to note that Lambda@Edge has specific limitations regarding environment variables.
Consider adding a comment in the code to document the limitations of environment variables with Lambda@Edge, especially the region-specific behavior.
dynamic "environment" {
for_each = each.value.environment != null ? [each.value.environment] : []
content {
variables = environment.value.variables
}
}
+# Note: Lambda@Edge functions can only access environment variables when deployed in US East (N. Virginia)
+# as functions are replicated globally but environment variables are only included from that region.
🌐 Web query:
Does Lambda@Edge support environment variables? Are there any limitations?
💡 Result:
AWS Lambda@Edge does not natively support environment variables, as confirmed by AWS documentation and multiple sources[1][2][7][8]. This limitation applies to all Lambda@Edge functions regardless of their trigger type (viewer or origin events).
Key Limitations and Workarounds
1. No Native Environment Variables
Lambda@Edge functions cannot use AWS Lambda's standard environment variable system[7][8]. This restriction exists because Lambda@Edge replicates functions globally, making environment variables (which are region-specific) incompatible with the edge architecture.
2. Common Workarounds
To inject configuration data:
- Code Modification: Bake variables directly into the code during deployment (e.g., using Terraform or build tools like Rollup)[4][3].
- CloudFront Headers: Pass values via CloudFront origin custom headers[3].
- External Services: Fetch configurations dynamically from services like AWS SSM Parameter Store or Secrets Manager[2][8].
- Custom Solutions: Use tools like the Lambda@Edge Environment Variable Injector to inject variables into the deployment package[1].
3. Additional Constraints
- Memory/Timeout: Viewer-triggered functions (e.g.,
viewer-request
) are limited to 128MB memory and 5-second execution, while origin-triggered functions allow up to 3008MB and 30 seconds[7][9]. - Code Size: Viewer-triggered functions have a 1MB deployment package limit, whereas origin-triggered functions allow 50MB[7][8].
- Body Size Limits: Viewer requests truncate body data at 40KB, while origin requests allow 1MB[7].
Example Workflow
A typical workaround involves modifying the Lambda code to read configurations from injected files. For example:
// Load environment variables from an injected file
const env = require('./env.js');
console.log(env.TheBest); // Outputs "TheBest, TheBest, TheBest"[2]
This approach requires modifying deployment pipelines to insert variables into the code package before uploading to AWS[1][4].
Summary
While Lambda@Edge lacks native environment variable support, developers can use code injection, external services, or third-party tools to simulate similar functionality. However, these methods require additional infrastructure management and may introduce security trade-offs (e.g., hardcoding values)[1][4][8].
Citations:
- 1: https://github.com/DV8FromTheWorld/LambdaEdge-Variable-Injector
- 2: https://jimmydqv.com/cloudfront-serverless-auth/
- 3: https://docs.developers.optimizely.com/full-stack-experimentation/docs/aws-lambda-at-edge
- 4: https://m1ke.me/2020/05/handling-environment-variables-in-lambda-edge/
- 5: https://answers.netlify.com/t/why-does-11-environment-variables-exceed-the-aws-lambda-limit/56194
- 6: https://forum.serverless.com/t/lambda-edge-environment-variables-in-a-serverless-project/11786
- 7: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-edge-function-restrictions.html
- 8: https://dev.to/aws-builders/dynamically-configure-your-lambda-edge-functions-2pkp
- 9: https://repost.aws/questions/QUyd5NLqZ-Q0qFwCk7e3TAZg/lambda-edge-unable-to-increase-memory-size
- 10: https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
Action Required: Update Documentation for Lambda@Edge Environment Variables
The dynamic block implementation is technically correct for handling an optional environment configuration. However, AWS Lambda@Edge does not natively support environment variables. This means that although the block is syntactically valid, any defined environment variables will not be applied to the function.
- Location:
modules/lambda@edge/main.tf
, Lines 89-94 - Required Change: Add a comment clarifying that Lambda@Edge does not support native environment variables and suggest considering alternative approaches (e.g., baking configuration into code).
Proposed Diff:
dynamic "environment" {
for_each = each.value.environment != null ? [each.value.environment] : []
content {
variables = environment.value.variables
}
}
+# Note: AWS Lambda@Edge does not natively support environment variables.
+# Any environment variable settings configured here will be ignored at runtime.
+# Consider alternative approaches (e.g., injecting configuration into your deployment package)
+# for managing runtime settings.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
dynamic "environment" { | |
for_each = each.value.environment != null ? [each.value.environment] : [] | |
content { | |
variables = environment.value.variables | |
} | |
} | |
dynamic "environment" { | |
for_each = each.value.environment != null ? [each.value.environment] : [] | |
content { | |
variables = environment.value.variables | |
} | |
} | |
# Note: AWS Lambda@Edge does not natively support environment variables. | |
# Any environment variable settings configured here will be ignored at runtime. | |
# Consider alternative approaches (e.g., injecting configuration into your deployment package) | |
# for managing runtime settings. |
It turned out that Lambda@Edge does not support env variables (docs), which makes this PR pointless. |
what
Allow configuration of environment variables for Lambda@Edge functions via the
environment
argument.why
Currently, the only option to provide dynamic configuration elements to a Lambda@Edge function is to use
templatefile()
. Using environment variables would be much cleaner and more maintainable.While the
templatefile()
approach works, it becomes inconvenient when your function codebase is spread across multiple files and/or includesnode_modules
. This is because the entire codebase directory cannot be considered "static" and simply assigned to the function'ssource_dir
argument. Instead, the templating process must occur before the directory is considered ready for zipping.references