Home > Blockchain >  How do I inject environment variables to Lambda running under sam local?
How do I inject environment variables to Lambda running under sam local?

Time:09-23

I am developing an aws lambda locally using AWS SAM.
I am trying to inject environment variables, with no success.
The Lambda code is:

exports.lambdaHandler = async (event, context) => {
    console.log('INJECTED ENVIRONMENT:',JSON.stringify(process.env));
    response = {
        'statusCode': 200,
        'body': "booo"
    }
    return response;
};

The environment file test.json is:

{
  "parameters": {
    "PPPPPPPPPPPPPPPPPPPPP1": "PPPPPPPPPPPPPPPPPPPPP1",
    "PPPPPPPPPPPPPPPPPPPPP2": "PPPPPPPPPPPPPPPPPPPPP2",
    "PPPPPPPPPPPPPPPPPPPPP3": "PPPPPPPPPPPPPPPPPPPPP3"
  }
}

I am running the lambda. It runs ok, shows me the expected output, Except the env variables I tried defining.
sam local invoke -e events/event.json -n test.json

What am I missing?

CodePudding user response:

The environment variables file has a specific format it needs to adhere to that depends on the logical id of the lambda function you want to test:

Test.json:

{
  "LogicalIdOfLambdaHere":{
    "ENV_VAR_KEY": "value"
  }
}

Make sure the logical id matches the one defined in your sam template. Alternatively you can use Parameters instead of parameters.

Note you also need to define the same variables in the actual SAM template. This method is for overriding the values specified in the template and not for adding new ones not defined in the template. Variables are also case sensitive:)

  • Related