Skip to content

Commit 7264566

Browse files
authored
Fix env vars override bug. (#531)
Currently, the script overrides existing env vars. This is dangerous, especially if someone used it by mistake for production lambda.
1 parent e1f5873 commit 7264566

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

experimental/aws-lambda-java-profiler/update-function.sh

+21-4
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,27 @@ aws lambda update-function-configuration \
3535
aws lambda wait function-updated \
3636
--function-name "$FUNCTION_NAME"
3737

38-
# Add environment variables
38+
# Get existing environment variables (handle null case)
39+
EXISTING_VARS=$(aws lambda get-function-configuration --function-name "$FUNCTION_NAME" --query "Environment.Variables" --output json 2>/dev/null)
40+
if [[ -z "$EXISTING_VARS" || "$EXISTING_VARS" == "null" ]]; then
41+
EXISTING_VARS="{}"
42+
fi
43+
44+
# Define new environment variables in JSON format
45+
NEW_VARS=$(jq -n --arg bucket "$BUCKET_NAME" \
46+
--arg java_opts "-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -javaagent:/opt/profiler-extension.jar" \
47+
'{AWS_LAMBDA_PROFILER_RESULTS_BUCKET_NAME: $bucket, JAVA_TOOL_OPTIONS: $java_opts}')
48+
49+
# Merge existing and new variables (compact JSON output)
50+
UPDATED_VARS=$(echo "$EXISTING_VARS" | jq -c --argjson new_vars "$NEW_VARS" '. + $new_vars')
51+
52+
# Convert JSON to "Key=Value" format for AWS CLI
53+
ENV_VARS_FORMATTED=$(echo "$UPDATED_VARS" | jq -r 'to_entries | map("\(.key)=\(.value)") | join(",")')
54+
55+
# Update Lambda function with correct format
3956
aws lambda update-function-configuration \
40-
--function-name "$FUNCTION_NAME" \
41-
--environment "Variables={AWS_LAMBDA_PROFILER_RESULTS_BUCKET_NAME=$BUCKET_NAME, JAVA_TOOL_OPTIONS=-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -javaagent:/opt/profiler-extension.jar}"
57+
--function-name "$FUNCTION_NAME" \
58+
--environment "Variables={$ENV_VARS_FORMATTED}"
4259

4360
# Update the function's permissions to write to the S3 bucket
4461
# Get the function's execution role
@@ -73,4 +90,4 @@ echo "Setup completed for function $FUNCTION_NAME with S3 bucket $BUCKET_NAME"
7390
echo "S3 write permissions added to the function's execution role"
7491

7592
# Clean up temporary files
76-
rm s3-write-policy.json
93+
rm s3-write-policy.json

0 commit comments

Comments
 (0)