[AWS] how to create a dynamic apigateway stage and lambda alias

Hey so basically what I’m trying to achieve is something like Vercels preview environments but with lambda.

On every pull request I want to update my lambda functions code, alias and gateway stage per pull request dynamically. For the sake of simplicity lets say I open a pull request on my repo called “mybranch”. I want the lambda functions code to be updated, tagged with an alias of “mybrach” and deployed to the api gateway stage called “mybranch” with the appropriate function alias.

All cdk solutions I’ve looked at seem geared towards, static stages un-variabled function aliases and a full deployment per pull request. Is there any way to achieve this or any documentation about how to go about doing this?

I tried messing around with the lifecycle policies on resources but doesn’t really seem to work.

1 Like

Hi @thekollective :wave:

I’m afraid that you’d need to connect most of the dots yourself and build this workflow in some kind of CI (e.g. Github Actions) as we currently don’t have built-in support for this kind of customized workflow.
Regarding your question about API Gateway stages: I’d probably try to split my application into multiple stacks and have one stack that only deploys the API Gateway stage (possibly taking a branch name as an argument). I’d then adjust my CI in a way that only that stack will be deployed.
You’d also need a bit of tooling to create a place to store your Terraform state (e.g. a Terraform Cloud Workspace) and to clean up everything after the branch has been deleted / the PR has been merged / after some timeout.

Yea that makes sense, I guess the better question I should’ve asked was more like “how do I ‘upsert’ a dynamic resource while keeping the previous resource”. For example if I provide a stage name to the gateway stage “one”, deploy, then change the stage name to “two”. stage “one” no longer will exist. I’m new to infrastructure management and haven’t found anything in the docs for something like this yet.

CDKTF (and other many other IaC options) are declarative in nature. This means you are specifying what you want your infrastructure to be. As such, you’ll need to define both stages if you want the previous one to continue to exist.
There are methods for ignoring certain changes or moving resources out of the control of code, but I wouldn’t recommend them at this stage.