How to get the name of the stage in an AWS Lambda function linked to API Gateway

Viewed 11086

I have the following Lambda function configured in AWS Lambda :

var AWS = require('aws-sdk');
var DOC = require('dynamodb-doc');
var dynamo = new DOC.DynamoDB();
exports.handler = function(event, context) {

    var item = { id: 123,
                 foo: "bar"};

    var cb = function(err, data) {
        if(err) {
            console.log(err);
            context.fail('unable to update hit at this time' + err);
        } else {
            console.log(data);
                context.done(null, data);
        }
    };

    // This doesn't work. How do I get current stage ?
    tableName = 'my_dynamo_table_' + stage;

    dynamo.putItem({TableName:tableName, Item:item}, cb);
};

Everything works as expected (I insert an item in DynamoDB every time I call it).

I would like the dynamo table name to depend on the stage in which the lambda is deployed.

My table would be:

  • my_dynamo_table_staging for stage staging
  • my_dynamo_table_prod for stage prod

However, how do I get the name of the current stage inside the lambda ?

Edit: My Lambda is invoked by HTTP via an endpoint defined with API Gateway

4 Answers

For those who use the serverless framework it's already implemented and they can access to event.stage without any additional configurations.

See this issue for more information.

You can get it from event variable. I logged my event object and got this.

{  ...
    "resource": "/test"
    "stageVariables": {
        "Alias": "beta"
    }
}
Related