Skip to content
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

Closed

Conversation

jwadolowski
Copy link
Contributor

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 includes node_modules. This is because the entire codebase directory cannot be considered "static" and simply assigned to the function's source_dir argument. Instead, the templating process must occur before the directory is considered ready for zipping.

references

Copy link

coderabbitai bot commented Mar 3, 2025

📝 Walkthrough

Walkthrough

The pull request introduces environment variable support to Lambda@Edge functions. In the Terraform example, an environment block is added to the viewer_response function configuration with a variable MY_RESPONSE_HEADER set to "test". The corresponding JavaScript handler now includes a new header x-my-response-header derived from that environment variable. In addition, module documentation and configuration files have been updated to include alternative source options and an optional environment attribute, ensuring consistent support for dynamic environment configurations across the module.

Changes

Files Change Summary
examples/complete/{lambda-at-edge.tf, lib/index.js} Added environment variable support in examples: Introduced an environment block with MY_RESPONSE_HEADER in the Terraform file and updated the JS handler to add a new header x-my-response-header from the environment variable.
modules/lambda@edge/{README.md, main.tf, variables.tf} Updated module configurations: Revised documentation to include alternative source options (source_dir, source_zip), added a dynamic block in main.tf to conditionally configure environment variables, and modified variable definitions to include an optional environment attribute with a variables map.

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mergify mergify bot added the triage Needs triage label Mar 3, 2025
@jwadolowski jwadolowski marked this pull request as ready for review March 3, 2025 12:28
@jwadolowski jwadolowski requested review from a team as code owners March 3, 2025 12:28
@jwadolowski jwadolowski requested review from Gowiem and jamengual March 3, 2025 12:28
Copy link

@coderabbitai coderabbitai bot left a 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 Description

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8853705 and b0ed4a6.

📒 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 Support

The updated functions input now includes the new environment attribute set as an optional object with a variables map. This clearly enables the configuration of environment variables for individual Lambda@Edge functions. Please ensure that the examples (e.g., in examples/complete/lambda-at-edge.tf and examples/complete/lib/index.js) are updated to demonstrate how to use this new capability.

Comment on lines +89 to +94
dynamic "environment" {
for_each = each.value.environment != null ? [each.value.environment] : []
content {
variables = environment.value.variables
}
}
Copy link

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:


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.

Suggested change
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.

@jwadolowski
Copy link
Contributor Author

It turned out that Lambda@Edge does not support env variables (docs), which makes this PR pointless.

@jwadolowski jwadolowski closed this Mar 3, 2025
@mergify mergify bot removed the triage Needs triage label Mar 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant