diff --git a/packages/@aws-cdk/aws-lambda/lib/function.ts b/packages/@aws-cdk/aws-lambda/lib/function.ts index 7643e1db0f9f8..3f5d0514d652b 100644 --- a/packages/@aws-cdk/aws-lambda/lib/function.ts +++ b/packages/@aws-cdk/aws-lambda/lib/function.ts @@ -898,6 +898,30 @@ export class Function extends FunctionBase { * @param options Environment variable options. */ public addEnvironment(key: string, value: string, options?: EnvironmentOptions): this { + // Reserved environment variables will fail during cloudformation deploy if they're set. + // This check is just to allow CDK to fail faster when these are specified. + const reservedEnvironmentVariables = [ + '_HANDLER', + '_X_AMZN_TRACE_ID', + 'AWS_REGION', + 'AWS_EXECUTION_ENV', + 'AWS_LAMBDA_FUNCTION_NAME', + 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', + 'AWS_LAMBDA_FUNCTION_VERSION', + 'AWS_LAMBDA_INITIALIZATION_TYPE', + 'AWS_LAMBDA_LOG_GROUP_NAME', + 'AWS_LAMBDA_LOG_STREAM_NAME', + 'AWS_ACCESS_KEY', + 'AWS_ACCESS_KEY_ID', + 'AWS_SECRET_ACCESS_KEY', + 'AWS_SESSION_TOKEN', + 'AWS_LAMBDA_RUNTIME_API', + 'LAMBDA_TASK_ROOT', + 'LAMBDA_RUNTIME_DIR', + ]; + if (reservedEnvironmentVariables.includes(key)) { + throw new Error(`${key} environment variable is reserved by the lambda runtime and can not be set manually. See https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html`); + } this.environment[key] = { value, ...options }; return this; } diff --git a/packages/@aws-cdk/aws-lambda/test/function.test.ts b/packages/@aws-cdk/aws-lambda/test/function.test.ts index 72316fa1e6b21..ec2b238ca0035 100644 --- a/packages/@aws-cdk/aws-lambda/test/function.test.ts +++ b/packages/@aws-cdk/aws-lambda/test/function.test.ts @@ -3114,6 +3114,18 @@ test('FunctionVersionUpgrade adds new description to function', () => { }); }); +test('function using a reserved environment variable', () => { + const stack = new cdk.Stack(); + expect(() => new lambda.Function(stack, 'MyLambda', { + code: new lambda.InlineCode('foo'), + handler: 'index.handler', + runtime: lambda.Runtime.PYTHON_3_9, + environment: { + AWS_REGION: 'ap-southeast-2', + }, + })).toThrow(/AWS_REGION environment variable is reserved/); +}); + function newTestLambda(scope: constructs.Construct) { return new lambda.Function(scope, 'MyLambda', { code: new lambda.InlineCode('foo'),