Shiyas
Shiyas

Reputation: 710

Automating API Gateway Stage Deployment

Im creating API gateway stage using cloudformation.

  ApiDeployment:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: !Ref ExampleRestApi
      StageName: dev 

Here is the problem, Whenever I create a new API, I just need to deploy the stage using AWS console. is there any way that I can automate the deploy process so that no further console action is required.

Upvotes: 2

Views: 2411

Answers (2)

Federico
Federico

Reputation: 1731

I've found berenbums response to be mostly correct, but there are a few things I don't like. The proposed method of creating a resource like ApiDeployment#TIMESTAMP# doesn't keep the deployment history. This makes sense, since the old ApiDeployment#TIMESTAMP# element is being deleted and a new one is being created every time.

Using ApiDeployment#TIMESTAMP# creates a new deployment every time the template is deployed, which might be undesirable if the template is being deployed to create/update other resources.

Also, using ApiDeployment#TIMESTAMP# didn't work well when adding the StageDescription property. A potential solution is to add a static APIGwDeployment resource for the initial deployment (with StageDescription) and ApiDeployment#TIMESTAMP# for the updates.

The fundamental issue though, is that creating a new api gw deployment is not well suited for cloudformation (beyond the initial deployment). I think after the initial deployment, it's better to do an AWS API invocation to update the deployment (see https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-deployments.html).

In my particular case I created a small Ansible module to invoke aws apigateway create-deployment which updates an existing stage in one operation.

Upvotes: 2

berenbums
berenbums

Reputation: 1354

When you define a Deployment resource like this, CloudFormation will create the deployment only on the first run. On the second run it will observe that the resource already exists and the CloudFormation definition did not change, so it won't create another deployment. To work around that, you can add something like a UUID/timestamp placeholder to the resource ID and replace it everytime before doing the CloudFormation update:

ApiDeployment#TIMESTAMP#:
  Type: AWS::ApiGateway::Deployment
  Properties:
    RestApiId: !Ref ExampleRestApi
    StageName: dev

This way you are still able to see your deployment history in the API Gateway console.

If you don't want to manipulate your template like this, you can also add a Lambda-backed Custom Resource to your CloudFormation stack. Using an AWS SDK, you can have the Lambda function automatically creating new deployments for you when the API was updated.

Upvotes: 4

Related Questions