Creating Stages in API Gateway& Adding Alias in Lambda.
Today I was stuck finding a solution on a very specific problem: To find a way that to creating lambda alias and API gateway stages for multiple environments like dev, qa and production.
Introduction
Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale, It is like an executable of an API represented by a RestApi resource.
By using lambda versioning, you can manage your in-production function code in AWS Lambda better. When you use versioning in AWS Lambda, you can publish one or more versions of your Lambda function.
AWS Lambda also supports creating aliases for each of your Lambda function versions.
Using these AWS services Let’s find a solution…!!!
Step1: Login to your aws management console.
Step2: Create API gateway.
Step3: Now create a resource in API gateway.
- While creating the resource we need to enable the CORS to perform the aliases.
Step4: Create the METHOD for resource.
Step5: Here I have added the POST METHOD.
Step6: Create one lambda function as “test_lambda”.
Step7: Add the lambda function name as (test_lambda:${stageVariables.lambdaAlias}) and save.
Aws Lambda add-permission:
Grants an AWS service or another account permission to use a function. You can apply the policy at the function level, or specify a qualifier to restrict access to a single version or alias. If you use a qualifier, the invoker must use the full Amazon Resource Name (ARN) of that version or alias to invoke the function.
Name formats
- Function name — my-function (name-only), my-function:v1 (with alias).
- Function ARN — arn:aws:lambda:us-west-2:123456789012:function:my-function .
- Partial ARN — 123456789012:function:my-function .
You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
Step8: After click on save we will get aws lambda add-permisson pop up we have to copy that into notepad and click OK.
Step9: Now select Actions and click on Deploy-API.
Step10: When we click on Deploy-API we will get the Deployment stage there we have to create new Stage and add name, description then click on Deploy.
Stage variables:
Stage variables are name-value pairs that you can define as configuration attributes associated with a deployment stage of a REST API. They act like environment variables and can be used in your API setup and mapping templates.
You can use the same API setup with a different endpoint at each stage by resetting the stage variable value to the corresponding URLs. You can also access stage variables in the mapping templates, or pass configuration parameters to your AWS Lambda or HTTP backend.
Step11: After click on Deploy we will get the dev Stage, click on dev then we can see the Stage Variables.
Step12: Click on “Add stage variable” add (Name [lambdaAlias], Value [dev] ).
Step13: Now We are Deploying the QA too.
- Click on “Add stage variable” add (Name [lambdaAlias], Value [qa] ).
- CREATING ALIAS AND VERSIONING USING LAMBDA IN AWS
Step14: Add the below shown code in lambda and i am adding the target environment alias in Environment Variables.
import json
import osdef lambda_handler(event, context):
global processing_environment
function_name = context.function_name
function_arn = context.invoked_function_arn
alias = function_arn.split(":").pop()if alias != "qa" and alias != "prod":
alias = "dev"
# END - Following code is ued for calling appropriate environment variables #
environment = os.environ[alias + '_targetEnvironment']
processing_environment = aliasreturn {
'statusCode': 200,
'body': json.dumps('Hello from QA Lambda!')
}
Environment variables:
Environment variables for Lambda functions enable you to dynamically pass settings to your function code and libraries, without making changes to your code. Environment variables are key-value pairs that you create and modify as part of your function configuration.
You can use environment variables to store outputs, store connection and logging settings, By separating these settings from the application logic, you don’t need to update your function code when you need to change the function behavior based on different settings.
Step15: I have added the alias name and target function in Environment Variables.
Alias:
AWS Lambda also supports creating aliases for each of your Lambda function versions. Conceptually, an AWS Lambda alias is a pointer to a specific Lambda function version. It’s also a resource similar to a Lambda function, and each alias has a unique ARN. Each alias maintains an ARN for the function version to which it points.
Step16: In actions click on create the alias.
Step17: Add the alias name and description.
The function you create is the $LATEST version. You also create an alias (DEV, for development) that points to the newly created function. Developers can use this alias to test the function with the event sources in a development environment.
Note: For dev I am adding version is default version as $LATEST.
Step18: Now I am publishing the new version for QA.
Step19: Here i am creating the new version as 2.
Step20: Now i am creating the Alias for QA and adding the Version to QA.
This is how alias and versions will works.
Step21: Now open the notepad for aws lambda permission function which we have copied while integrating the lambda function in API Gateway.
aws lambda add-permission
--function-name "arn:aws:lambda:us-west-2:************:function:test_lambda:${stageVariables.lambdaAlias}" --source-arn "arn:aws:execute-api:us-west-2:************/*/POST/test"
--principal apigateway.amazonaws.com
--statement-id e********-***e-*ffa-*d6c-**********
--action lambda:InvokeFunction
Step22: Then remove the ${stageVariables.lambdaAlias} and add the “dev” or “qa”, remove the “Post” and add the “*”.
aws lambda add-permission
--function-name "arn:aws:lambda:us-west-2:***********:function:test_lambda:dev"
--source-arn "arn:aws:execute-api:us-west-2:***************/*/*/test"
--principal apigateway.amazonaws.com
--statement-id e*******-***e-*ffa-****-************
--action lambda:InvokeFunction
Step23: Now open the AWS CLI in browser and download, run the CLI.
Step24: Now open the command prompt and run the following commands.
aws — version.aws configureAWS Access Key ID [****************4BNQ]: Here you have to add Access keyAWS Secret Access Key [****************XuyH]: Here you have to add Secret Access KeyDefault region name [us-west-2]: Here you have to add regionDefault output format [JSON]: Here you have to add formatAdd the copied Aws permission function in the command prompt.
Step25: Open the API Gateway and copy the end point url of the DEV.
Step26: Then select end point url method from the Postman.
Step27: Copy the Endpoint Url for QA.
Step28: POST it from postman.
Step29: These are the current versions for dev and qa.
Step30: If you made any changes in code then make a new version.
Step31: Click actions and select publish new version.
Step32: Here add your new version name and click on publish.
Step33: Now the version is successfully created.
Step34: Click on qualifiers and click on alias.
Step35: In the bottom of the lambda function of alias you can find the version which is previous one.
Step36: Now change the version from 2 to 3 and click on save.
Step37: Now you can find alias has been changed from version 2 to version 3.
Ok, that’s it. I hope you found this case useful! See you next