You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于对应.env文件创建4个AWS Lambda并配置环境变量

Got it, let's break down how to solve this. The goal is to modify your build.sh to deploy each of your 4 Lambda functions, pulling environment variables directly from their respective .env files. Here's a complete, robust solution:

Step-by-Step Solution

First, let's outline the core approach:

  • Loop through each Lambda folder
  • Load the .env file in the folder and convert its key-value pairs into the JSON format AWS Lambda expects
  • Package the Lambda code (including dependencies if needed)
  • Either create a new Lambda function or update an existing one, applying the environment variables

1. Final build.sh Implementation

Replace your existing build.sh with this script (adjust the common configuration values to match your AWS setup):

#!/bin/bash
set -euo pipefail

# --------------------------
# Common Configuration (Adjust these!)
# --------------------------
AWS_REGION="us-east-1"          # Your AWS region
RUNTIME="nodejs18.x"            # Match your Node.js version (e.g., nodejs20.x)
ROLE_ARN="arn:aws:iam::123456789012:role/your-lambda-execution-role"  # IAM role for Lambda
HANDLER="index.handler"         # Your Lambda handler (index.js exports.handler)

# List of your Lambda function folders
LAMBDA_FOLDERS=("folder1ForLambda1" "folder2ForLambda2" "folder3ForLambda3" "folder4ForLambda4")

# --------------------------
# Deployment Logic
# --------------------------
for FOLDER in "${LAMBDA_FOLDERS[@]}"; do
    echo "=== Processing Lambda in folder: $FOLDER ==="
    
    # Navigate to the Lambda folder (fail if missing)
    cd "$FOLDER" || { echo "Error: Could not enter folder $FOLDER"; exit 1; }
    
    # Generate environment variables JSON from .env
    if [ -f .env ]; then
        echo "Loading environment variables from .env..."
        # Parse .env into Lambda-compatible JSON (handles escaped quotes)
        ENV_VARS_JSON=$(awk -F '=' '
            BEGIN { print "{\"Variables\": {" }
            /^[A-Za-z_][A-Za-z0-9_]*=/ {
                gsub(/"/, "\\\"", $2);  # Escape double quotes in values
                printf "\"%s\": \"%s\",", $1, $2
            }
            END { print "}}" }
        ' .env | sed 's/,\s*}}$/}}/')  # Remove trailing comma to avoid JSON errors
    else
        echo "Warning: No .env file found in $FOLDER - using empty environment variables"
        ENV_VARS_JSON="{}"
    fi
    
    # Install production dependencies (uncomment if you have package.json dependencies)
    # echo "Installing production dependencies..."
    # npm install --production
    
    # Package Lambda code (include node_modules if present)
    echo "Packaging code..."
    zip -r function.zip index.js node_modules/ 2>/dev/null || zip function.zip index.js
    
    # Use folder name as Lambda function name (customize this if needed)
    FUNCTION_NAME="$FOLDER"
    
    # Check if Lambda already exists (update if yes, create if no)
    if aws lambda get-function --function-name "$FUNCTION_NAME" --region "$AWS_REGION" >/dev/null 2>&1; then
        echo "Updating existing Lambda: $FUNCTION_NAME"
        # Update code
        aws lambda update-function-code \
            --function-name "$FUNCTION_NAME" \
            --region "$AWS_REGION" \
            --zip-file fileb://function.zip
        # Update environment variables
        aws lambda update-function-configuration \
            --function-name "$FUNCTION_NAME" \
            --region "$AWS_REGION" \
            --environment "$ENV_VARS_JSON"
    else
        echo "Creating new Lambda: $FUNCTION_NAME"
        aws lambda create-function \
            --function-name "$FUNCTION_NAME" \
            --region "$AWS_REGION" \
            --runtime "$RUNTIME" \
            --role "$ROLE_ARN" \
            --handler "$HANDLER" \
            --zip-file fileb://function.zip \
            --environment "$ENV_VARS_JSON"
    fi
    
    # Clean up packaged zip
    rm function.zip
    
    # Navigate back to root folder
    cd ..
done

echo "=== All Lambda functions processed successfully! ==="

2. Key Notes & Adjustments

  • Permissions: Ensure your AWS CLI has these permissions:
    • lambda:CreateFunction
    • lambda:UpdateFunctionCode
    • lambda:UpdateFunctionConfiguration
    • iam:PassRole (to attach the execution role)
  • .env File Rules: Keep your .env files in KEY=value format (no spaces around =). The script handles escaped double quotes in values (e.g., API_KEY="abc123" becomes valid JSON).
  • Dependency Handling: If your Lambda uses npm packages, uncomment the npm install --production line to install production-only dependencies before packaging.
  • Function Naming: The script uses the folder name as the Lambda function name. If you want custom names, replace FUNCTION_NAME="$FOLDER" with a custom string (e.g., FUNCTION_NAME="my-custom-lambda-1").

内容的提问来源于stack exchange,提问作者hrushilok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:45:36