Home > Mobile >  Change value of environment variable while invoking Lambda function
Change value of environment variable while invoking Lambda function

Time:01-03

I am learning lambda and currently trying to understand the environment variables. Below is a very simple code to show my question. (A nodejs function that will simply print the value of name constant).

exports.handler =  async function(event, context) {
   
   const name = process.env.NAME;
    return name;
  
};

I have already defined a environment variable on lambda as following

enter image description here

Now this lambda will surely print "xyz" after completion. But how we can overwrite/change the value of the "Name" variable while running the Lambda. so while invoking it will show the new value? For example something like --NAME = "abc" or --NAME abc

CodePudding user response:

From Invoke Lambda in AWS Console

Option 2: AWS CLI v2

From the command line you could invoke that Lambda using the AWS CLI.

aws \
    lambda \
    invoke \
    --cli-binary-format raw-in-base64-out \
    --function-name <function-name> \
    --payload '{"domain":"www.google.com"}' \
    outfile.txt

Option 3: AWS SDK

You can also write some code in a other Lambda, in a script on your local machine or any other way that can use the AWS Lambda and invoke the Lambda like this.

The following is an example of simple NodeJS CLI "code" using the v3 of the AWS SDK.

import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";

async function main() {
    const client = new LambdaClient({ region: "<your-region>" });

    const payload = JSON.stringify({
        "domain": "www.google.com"
    });

    const input = {
        "FunctionName": "<function-name>",
        "Payload": payload
    };
    
    const command = new InvokeCommand(input);
    const response = await client.send(command);
    
    console.log(response);
}

main()

If you run node index.js you will invoke the Lambda with the given payload.

To setup node:

npm init
npm install @aws-sdk/client-lambda

Remember to set type to module in the package.json.

  • Related