Concept for how to use ApiGateway StageVariables, Lambda Version, Alias, Environment variable, all together
Tags: aws, cdk, serverless, python
Published: 2021-05-02 09:56:28

In [previous part](https://dev.to/upupkenchoong/how-to-set-environment-variable-for-lambda-using-cdk-4m36)of this series, we know how to set `environment variables` inside our Lambda. 

In this part, I will talk about how we can use Apigateway StageVariables, Lambda Version, Alias, Environment variable all together. 

We have to understand how the whole process work first, then only we can create this easily using CDK code. 

**Let's imagine this scenario**
- You have an API that will use Lambda function
- You make a Lambda function
- This function will in production which used by real world user 
- But you also want to edit this Lambda or continuously develop new stuff for this Lambda 
- Now what if you have some error when editing the Lambda code? 

Then this will effect you Real world user right? The app will crash, then user leave, give you some nasty feedback. 
NO GOOD! 
Can you imagine how painful and stressful when developing stuff like this? 

Then this is why Lambda Version and Alias come in handy. 

**How `Lambda version` work?**
Imagine this:
- You make a Lambda function
- By default, every Lambda function have a `$Latest` version, this is where you keep editing/developing your code, this only use by you. 
- When everything ok, you publish a new `Version` for the function, let say `version:1`. The real world user will access to this `version:1`.
- We will keep repeating the process which is edit code in `$Latest`, publish a new `version` every time when everything ok for production. 

By doing this, you keep editing code in `$Latest`, any changes in `$Latest` will not affect to `version:1`, so any error will not annoy your real world user. 

Now you have 2 `version` for your Lambda, `$Latest` and `version:1`, then how we can set the production user will access `version:1` and developer(us) will access `$Latest`? 

This is why `Lambda Alias` come in handy. 

**The process of `alias` and `version` look like this:**
- Now we need to create 2 `alias` for our Lambda named `dev` and `prod`
- `dev` alias -> point to -> `$Latest` version 
- `prod` alias -> point to -> `version:1`(or 2,3,4,5, depends)

Alias is done, but now your frontend application still don't know which Lambda `version` to access. 

This is why APIGateway `StageVariables` come in play. 

Now we can create 2 `Stage` for your API named `dev` and `prod`
 
This will give us 2 URL which look like this: 
-  https://{APP-ID}.execute-api.{aws-region}.amazonaws.com/dev
-  https://{APP-ID}.execute-api.{aws-region}.amazonaws.com/prod

Now set a `Stage Variables` for each API stage like:
- `dev` stage: `lambdaAlias:dev`
- `prod` stage: `lambdaAlias:prod`

Then the whole process will look like this: 

```
API dev stage -> Lambda dev alias -> Lambda `$Latest` version
 
API prod stage -> Lambda prod alias -> Lambda `version:1`
```

Then inside the Lambda function we get back the `StageVariables` and use it with the `environment variables` that we set in [previous part](https://dev.to/upupkenchoong/how-to-set-environment-variable-for-lambda-using-cdk-4m36): 

```python
import boto3
import os

def MyFirstLambdaHandler(event, context):
    client = boto3.client('dynamodb')

    # Get the stageVariable lambdaAlias
    stage = event['stageVariables']['lambdaAlias']
    
    # Get the environment variable depends on stage variable
    if stage == 'prod':
        tableName = os.environ['production_db_url']

    if stage == 'dev':
        tableName = os.environ['development_db_url']

    # Then here you can access different table depends on environment

```

Now we connecting the dots:
```
API dev -> Lambda dev alias -> Lambda version:$Latest -> environment variables 

API prod -> Lambda prod alias -> Lambda version:1 -> environment variables
```

**For summary:**
TLDR, everything in development stay in development, which wont affect anything in production. 

Now you have some basic concept for Lambda `Version`, `Alias`, APIGateway `stage variables` and environment variables. 

You now know how to continuously develop your Lambda, but at the same time wont fu**ked up your whole production app when some error happened when developing. 


**In next part of the series, I will talk about:**
- How to create Lambda Version using CDK
- How to create Lambda Alias and hit different Lambda Version using CDK 
- How to create different Deployment stage of API gateway and set stage variables using CDK

In case you cant wait that long, here is my previous work on this topic: 
- [A dev.to comment](https://dev.to/upupkenchoong/comment/1b7f0)
- [SO question I answer](https://stackoverflow.com/a/66844497/4332049)

**Before you go,** if you like this series or find this useful consider to buy me a coffee 😊🤞 for 5 USD or more. 
I will prepare a GitHub repo for this whole tutorial series and arrange into separate commit for each part. 
This will only available for my supporter cause I spent a lot of time to prepare this. Anyway, I appreciate you here. Have a good day.

<a href="https://www.buymeacoffee.com/kenchoong" target="_blank">
![bmaco](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ap0mog1ue623vr1zbo36.jpg)
</a>

Shout out to me on Twitter: [@upupkenchoong](https://twitter.com/upupkenchoong)