serverless-application-model icon indicating copy to clipboard operation
serverless-application-model copied to clipboard

"API Stage not found" in AWS::ApiGateway::UsagePlan resource when changing API Stage name

Open piersf opened this issue 6 years ago • 13 comments

Description: I have the below API and Usage Plan resources created in my SAM template:

Parameters:
  ApiStageName:
    Type: String

ManagementApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: "my-api"
      StageName: !Ref ApiStageName

UsagePlanForManagementApi:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn: [ "ManagementApi" ]
    Properties:
        ApiStages:
            - ApiId: !Ref ManagementApi
              Stage: !Ref ApiStageName
        Description: "Management API Usage Plan"
        Quota:
            Limit: 100
            Period: DAY
        Throttle:
            BurstLimit: 50
            RateLimit: 100
        UsagePlanName: "my-api-usage-plan"

The above resource get deployed just fine and without any issues.

However, when I change the value of the ApiStageName parameter from v1 to v2, and try to run a sam deploy, the update with fail with the below error:

UPDATE_IN_PROGRESS                        AWS::ApiGateway::RestApi        ManagementApi        -
UPDATE_ROLLBACK_IN_PROGRESS               AWS::CloudFormation::Stack      dev-management-api-sam          The following resource(s) failed to update: [UsagePlanForManagementApi].
UPDATE_FAILED                             AWS::ApiGateway::UsagePlan      UsagePlanForManagementApi 
                                                                                                           API Stage not found: API_ID:v2 
                                                                                                           (Service: AmazonApiGateway; Status Code: 404; 
                                                                                                           Error Code: NotFoundException; Request ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxx)

It looks like there's some race condition going on here. I have used DependsOn on the Usage Plan resource to depend on the API resource but it does not seem make any difference.

Any idea how this can be fixed? Is this a bug in SAM?

Steps to reproduce the issue:

  1. Create the above resources and initially set the value of the ApiStageName parameter to v1
  2. Deploy
  3. Update the value of the ApiStageName parameter from v1 to v2
  4. Deploy

Observed result: The deployment fails with the above error when updating the value of the ApiStageName parameter to v2

Expected result: The deployment should not fail with the above error

I came across issue #32 which has been closed but I didn't see a solution. Also, that issue is from 2 years ago so I'm hoping a fix has been released since then.

Thank you

piersf avatar Apr 14 '20 18:04 piersf

For your current setup, it looks like you need to depend on the Stage resource that SAM generates rather than the API.

  UsagePlanForManagementApi:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn:
      - ManagementApi.Stage

On a side note, have you considered using the UsagePlan feature in SAM? The syntax for this same example you posted would be the following:

Parameters:
  ApiStageName:
    Type: String

Resources:
  ManagementApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: "my-api"
      StageName: !Ref ApiStageName
      Auth:
        UsagePlan:
          CreateUsagePlan: PER_API
          UsagePlanName: "my-api-usage-plan"
          Quota:
            Limit: 100
            Period: DAY
          Throttle:
            BurstLimit: 50
            RateLimit: 100
          Description: "Management API Usage Plan"

SAM handles the depends on and other resource dependencies for you in this case.

keetonian avatar Apr 17 '20 22:04 keetonian

@keetonian for some reason, the DependsOn solution didn't work for me: I had to remove the dot in the resource name.

  UsagePlanForManagementApi:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn:
-      - ManagementApi.Stage
+      - ManagementApiStage

spalladino avatar Jun 04 '20 15:06 spalladino

I had same issue and this works for me.

DependsOn: 'ApiGatewayDeployment${sls:instanceId}'

duc2019 avatar Oct 01 '20 01:10 duc2019

I had same issue and this works for me.

DependsOn: 'ApiGatewayDeployment${sls:instanceId}'

@duc2019 isn't that from the serverless framework? This is AWS SAM we're talking about.

piersf avatar Oct 01 '20 16:10 piersf

Looks like since writing this the naming convention for the logical name of the stage has changed to include the stage name.

e.g. if the provided stage name above was Prod then the depends on would need to be: DependsOn: ManagementApiProdStage

mkrauklis avatar May 25 '21 14:05 mkrauklis

@mkrauklis weird, I don't get the stage name included in the LogicalResourceId

+ Add                                   RestApiPublicApiAuthorizerAuthorizerP   AWS::Lambda::Permission                 N/A                                   
                                        ermission                                                                                                             
+ Add                                   RestApiStage                            AWS::ApiGateway::Stage                  N/A                                   
+ Add                                   RestApi                                 AWS::ApiGateway::RestApi                N/A                                   

for anyone looking at this, reviewing the changeset will help identify the miscreant you are after :)

sawilde avatar Mar 15 '22 09:03 sawilde

I had same issue and this works for me.

DependsOn: 'ApiGatewayDeployment${sls:instanceId}'

@duc2019 isn't that from the serverless framework? This is AWS SAM we're talking about.

this worked for me. It allows the serverless framework to finish off everything it needs, before firing off the usageplan amendments. thanks

PhilA1 avatar Oct 05 '22 12:10 PhilA1

Why has this issue been closed? I'm still experiencing the same issue as the author of this issue. This is the only approach that worked for me: https://github.com/aws/serverless-application-model/issues/1560#issuecomment-638944938

https://github.com/aws/serverless-application-model/issues/1560#issuecomment-615486160 is not an option for me because I want to create a usage plan, and an API key and then connect them using "AWS::ApiGateway::UsagePlanKey". If a usage plan is added inside the "AWS::Serverless::Api" resource then it cannot be referenced in the "AWS::ApiGateway::UsagePlanKey". At least I didn't find any documentation or working examples on that.

This works

  ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref StageName

  TestApiKey:
    Type: AWS::ApiGateway::ApiKey
    Properties:
      Name: !Sub test-api-key-${AWS::StackName}
      Description: Test API Key
      Enabled: true

  TestUsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn: 
      - ApiGatewayStage
    Properties:
      ApiStages:
        - ApiId: !Ref ApiGateway
          Stage: !Ref StageName
      Description: Test Usage Plan

  TestUsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    DependsOn: TestUsagePlan
    Properties:
      KeyId: !Ref TestApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref TestUsagePlan

This doesn't work:

ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref StageName

  TestApiKey:
    Type: AWS::ApiGateway::ApiKey
    Properties:
      Name: !Sub test-api-key-${AWS::StackName}
      Description: Test API Key
      Enabled: true

  TestUsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn: 
      - ApiGateway
    Properties:
      ApiStages:
        - ApiId: !Ref ApiGateway
          Stage: !Ref StageName
      Description: Test Usage Plan

  TestUsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    DependsOn: TestUsagePlan
    Properties:
      KeyId: !Ref TestApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref TestUsagePlan

domengabrovsek avatar Aug 20 '23 14:08 domengabrovsek

Thank you @domengabrovsek. Your solution also worked for me.

andersenthomas98 avatar Aug 22 '23 15:08 andersenthomas98

Similar to the above solutions I found the below worked for me. (I'm using serverless)

WebSocketUsagePlan:
  Type: AWS::ApiGateway::UsagePlan
  DependsOn: 
    - WebsocketsDeploymentStage

henryfJones avatar Sep 15 '23 11:09 henryfJones

TestUsagePlan: Type: AWS::ApiGateway::UsagePlan DependsOn: - ApiGatewayStage Properties: ApiStages: - ApiId: !Ref ApiGateway Stage: !Ref StageName Description: Test Usage Plan

I wonder in

TestUsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn: 
      - ApiGatewayStage
    Properties:
      ApiStages:
        - ApiId: !Ref ApiGateway
          Stage: !Ref StageName
      Description: Test Usage Plan

Why - ApiGatewayStage and not - ApiGateway ??

I used ApiGatewayStage and it gets deployed but when I do a request to the endpoint providing x-api-ley I get bad gateaway 502.

jorgesisco avatar Nov 20 '23 15:11 jorgesisco

Here is my API definition -

# API Gateway REST API
  HelloWorldApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true
      DefinitionBody:
        swagger: '2.0'
        info:
          title: Hello World API
        paths:
          /hello:
            post:
              security:
                - api_key: []
              x-amazon-apigateway-integration:
                type: aws_proxy
                httpMethod: POST
                uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloWorldFunction.Arn}/invocations
              responses:
                '200':
                  description: Success
        securityDefinitions:
          api_key:
            type: apiKey
            name: x-api-key
            in: header

and my usage plan -

StandardUsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn: HelloWorldApiStage
    Properties:
      UsagePlanName: !Sub ${AWS::StackName}-UsagePlan1
      Description: First usage plan
      ApiStages:
        - ApiId: !Ref HelloWorldApi
          Stage: Prod
      Throttle:
        RateLimit: 100
        BurstLimit: 200
      Quota:
        Limit: 1000
        Period: DAY

It keeps on throwing this

Error: Failed to create changeset for the stack: waf-apigw-sam, ex: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state: For expression "Status" we matched expected path: "FAILED" Status: FAILED. Reason: Template format error: Unresolved resource dependencies [HelloWorldApiStage] in the Resources block of the template
Deployment complete!

Saborni avatar Jul 08 '25 11:07 Saborni

This now makes sense - https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-generated-resources-api.html

When an AWS::Serverless::Api is specified, AWS Serverless Application Model (AWS SAM) always generates an AWS::ApiGateway::RestApi base AWS CloudFormation resource. In addition, it also always generates an AWS::ApiGateway::Stage and an AWS::ApiGateway::Deployment resource.

AWS::ApiGateway::RestApi

LogicalId: <api‑LogicalId>

Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation resource)

AWS::ApiGateway::Stage

LogicalId: <api‑LogicalId><stage‑name>Stage

<stage‑name> is the string that the StageName property is set to. 

For example, if you set StageName to Gamma, the LogicalId is MyRestApiGammaStage.

Referenceable property: <api‑LogicalId>.Stage

Saborni avatar Jul 08 '25 11:07 Saborni