API Gateway Force Redeployment CloudFormation

This is something that if you’ve not noticed yet, you will at some point and it’ll catch you out.

If you have an API Gateway configured in CloudFormation that is already deployed and you make changes to the structure of the API (maybe adding a new endpoint) when you deploy your CloudFormation stack you may expect your new changes to be deployed to the API Gateway Stage however this won’t always happen.

In order to deploy your changes to the stage in API gateway you’d have to select the Deploy API option within the Actions drop down in the API Gateway AWS Console.

We can get around this by ensuring the API Gateway Stage is redeployed on each CloudFormation stack update.

Our approach to solving this issue may be considered a bit of ‘hack’ however it works flawlessly!

Within our CloudFormation template we name the AWS::ApiGateway::Deployment with a placeholder suffix. __TIMESTAMP and then within our CI/CD pipeline we use shell commands to replace the placeholder with the current unix timestamp ensuring that the deployment is always redeployed.

See the resource name for the deployment on line 14 below:

APIGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      StageName: !Sub ${EnvironmentTagName}
      RestApiId: !Ref APIGateway
      DeploymentId: !Ref APIGatewayDeployment__TIMESTAMP__
      TracingEnabled: true
      MethodSettings:
          - DataTraceEnabled: true
            HttpMethod: "*"
            LoggingLevel: INFO
            ResourcePath: "/*"
            MetricsEnabled: true

  APIGatewayDeployment__TIMESTAMP__:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: !Ref APIGateway
      Description: !Sub ${EnvironmentTagName} Deployment __TIMESTAMP__

  APIGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: !Ref "AWS::StackName"
      ...

Then within our CI/CD pipeline we execute the following:

  TIMESTAMP="$(date +%s)"
  sed -i "s/__TIMESTAMP__/${TIMESTAMP}/g" template.yaml

It’s worth noting that using this approach may not be most appropriate for your own use cases as it does limit some of the functionality you can use within API Gateway. We have an API Gateway resource in each stack we deploy, so each of our Production, Testing, Staging environments have entirely separate API Gateways. This is obviously different to having a single API Gateway and multiple stages. We also can’t roll back deployments on a stage without redeploying our stack to roll back changes.

Comments

comments powered by Disqus