3

I have a lambda function(without APIGateWay. I want same lambda function in both test and prod stage and for that I want to get the stage name during runtime. My code is written in java and I know that we can find out the default AWS region using following:

Regions regions = Regions.fromName(System.getenv("AWS_DEFAULT_REGION"));

So here are my questions:

1- How to get the name of the stage in which my lambda function is running?

2- What does this default region means? will it be always same as the region in which my lambda function is running?

Any lead is highly appreciated.

  • Are you using this with ApiGateway – ProgrammingLlama Mar 26 '18 at 16:54
  • Are you looking for something like this? https://aws.amazon.com/blogs/compute/using-api-gateway-stage-variables-to-manage-lambda-functions/ – Woodrow Mar 26 '18 at 19:48
  • I got a solution using environment variables. we can set environment variables using AWS console and can use them in our lambda function. –  Mar 27 '18 at 09:01

1 Answers1

1

How to get the name of the stage in which my lambda function is running?

For Lambda Proxy integration, you can get the stage name from the requestContext in the input stream, which contains the API request serialized as a JSON string by API Gateway. The input data can also include the request's stage variables stageVariables (if you use/need any). For example:

JSONParser parser = new JSONParser();

public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
  ...
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  String stage = null;

  JSONObject event = (JSONObject)parser.parse(reader);
  if (event.get("requestContext") != null) {
    JSONObject requestContext = (JSONObject)parser.parse((String)event.get("requestContext"));
    if (requestContext.get("stage") != null) {
      stage = (String)requestContext.get("stage");
    }
  }
  ...
}

See full example.

What does this default region means? will it be always same as the region in which my lambda function is running?

YES according to docs and NO according to the SDK.

The SDK does not reference it. It uses AWS_REGION only. See SDKGlobalConfiguration.java.

Khalid T.
  • 10,039
  • 5
  • 45
  • 53