In order to do version control in Lambda, we all knew that we can do it with versions and aliases. What if I want to integrate the versioning with my API gateway stages. That means, in different stages, it will point to different versions I made of my functions. This gives me the ability to have environments like staging and production, which is great, we don’t want to mess them up to break my production codes. So let’s do it!
Understanding the tools
Lambda Versions and Aliases
Create a new version is easy, just click on “Actions” > “Publish new version”. Version is named in increasing number. The first one is ‘1’, the second is ‘2’ and so on. Also, the code for any version is immutable, once you created a version, you can’t change the content. It’s like a snapshot of your function at that moment.
Then, it comes to aliases. An alias is a given name that points to one of your versions. You can change to a different version at any time you want. On top of that, there’s a feature that can split traffic to different versions. It is convenient when doing some testing.
API Gateway Stages
Stages are like separating APIs with different environments. With different stages, you will have different end-point of the API. When deploying APIs, you can easily choose between stages that you want them to be.
Implementation
Lambda
- Publish new version
Let’s say this is the first time we’re doing this, so we will get Version1
- Create aliases
Let’s create two aliases,stg
andprod
. And point them all to Version1
API Gateway
- Create stages
Create two stages calledstaging
andproduction
- Create stage variables
In each stage settings, click “Add Stage Variable” and give a name and its corresponding value.
Forstaging
stage, create with a name likelambdaAlias
. And the value is the actual alias name in your Lambda function that you want it to point to. In this case, the value will bestg
.
Forproduction
, it will beName: lambdaAlias, Value: prod
. - Set the Lambda function name
Go to your API and clickIntegration Request
. Then set the Lambda function likeMY_FUNCTION:${stageVariables.lambdaAlias}
.
Result
At this point, if you send a request to the staging API, the lambda function that’ll be triggered will be MY_FUNCTION:stg
.
Next time when you want to add new features to your function. You can do:
- Modify the code
- Publish a new version
- Make alias
stg
to have the new version of code - When it’s ready, you can switch alias
prod
to the new version of code