Serverless Shared API Gateway Error when deploying to different stages

Question:

I’m using serverless version 1.29.2

I have a created an initial cloudformation script that creates an API GateWay REST API that will be used by other services. So Here is the cloudformation script responsible for it.

Here is serverless.yml for the application I was trying to deploy.

When I perform an sls deploy --stage dev everything works fine, However when I perform another deploy to sls deploy --stage prod

This error shows up.

Answer:

I’ve struggled with this one for a week now and the issue is to do with the way API Gateway is constructred out of resources and methods. From the documentation

In Amazon API Gateway, you build a REST API as a collection of programmable entities known as API Gateway resources. For example, you use a RestApi resource to represent an API that can contain a collection of Resource entities. Each Resource entity can in turn have one or more Method resources. Expressed in the request parameters and body, a Method defines the application programming interface for the client to access the exposed Resource and represents an incoming request submitted by the client.

Serverless CLI creates all the resource/methods for you when you have a function trigged by an http event.

From the example above this creates five resources ( api, v1, game, gameIdParam, scene) and finally adds a GET method on the the final resource.

Unfortunately when you have two seperate stacks (as you might in a microservice setup) if they are any part of the above methods then it errors with Another resource with the same parent already has this name

The solution is highlighted in this article from serverless deploy serverless microservice on aws although its not very explict and easily missed.

Firstly there is a top level cloudformation template which configures the required resources.

For the resource you want to add a serverless microservice to you export the id of the resource as an output variable in your stack.

Then in the serverless.yml file you import the api gateway reference and apigateway resource id.

You can then deploy each service without getting a clash of resource names in the api structure.

The templates below show having a top level set of resources.

api/v1/game/{gameId}/page

api/v1/game/{gameId}/scene

And then attaching PageService to the page resource and SceneService to the scene resource.

api-gateway.yml

serverless.yml ( Serverless Cli file for Page Service)

serverless.yml ( Serverless Cli file for Scene Service)

Hopefully this helps others getting this issue and if somebody has a better way of doing it I’d be keen to know 🙂

Leave a Reply