Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Cloudformation: How to fix "Api Event must reference an Api in the same template" error?

I am trying to split my stack into nested stack because i hit the AWS Max stack resource limit. I am building a REST API. I want to use a one API Gateway for all the stacks. Below is my code.

template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aws-restapi

  Sample SAM Template for aws-restapi
  
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 5
    VpcConfig:
        SecurityGroupIds:
          - sg-041f2xxxd921e8e
        SubnetIds:
          - subnet-03xxxb2d
          - subnet-c4dxxxcb

Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod

  GetAllAccountingTypesFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/accounting-types/accountingtypes-getall.getallaccountingtypes
      Runtime: nodejs14.x
      Events:
        GetAllAccountingTypesAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /accountingtypes/getall
            Method: get
            RestApiId:
              Ref: ApiGatewayApi
  GetAccountingTypeByIDFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/accounting-types/accountingtypes-byid.getbyid
      Runtime: nodejs14.x
      Events:
        GetAllAccountingTypesAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /accountingtypes/getbyid
            Method: get
            RestApiId:
              Ref: ApiGatewayApi
  
  NestedStackTwo:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: nestedstack.yaml

  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                  - ec2:DescribeInstances
                  - ec2:AttachNetworkInterface
                Resource: '*'

Outputs:
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for functions"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"

nestedstack.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aws-restapi

  Sample SAM Template for aws-restapi

Globals:
  Function:
    Timeout: 5
    VpcConfig:
        SecurityGroupIds:
          - sg-041f2459dcd921e8e
        SubnetIds:
          - subnet-03xxxx2d
          - subnet-c4dxxxxcb

Parameters:
   ApiId: ApiGatewayApi

Resources:
  GetAllPromotionsFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/promotions/promotions-getall.getAllPromotions
      Runtime: nodejs14.x
      Events:
        GetAllPromotionsAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /promotions/getall
            Method: get
            RestApiId:
              Ref: !Ref ApiId
  SavePromotionsFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/promotions/promotions-save.savePromotions
      Runtime: nodejs14.x
      Events:
        SavePromotionsAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /promotions/save
            Method: post
            RestApiId:
              Ref: !Ref ApiId
  UpdatePromotionsFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/promotions/promotions-update.updatePromotions
      Runtime: nodejs14.x
      Events:
        UpdatePromotionsAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /promotions/update
            Method: post
            RestApiId:
              Ref: !Ref ApiId


  GetAllStaticInfoFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/static-info/staticinfo-getall.getAllStaticInfo
      Runtime: nodejs14.x
      Events:
        GetAllStaticInfoAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /staticinfo/getall
            Method: get
            RestApiId:
              Ref: !Ref ApiId
  SaveStaticInfoFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/static-info/staticinfo-save.saveStaticInfo
      Runtime: nodejs14.x
      Events:
        SaveStaticInfoAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /staticinfo/save
            Method: post
            RestApiId:
              Ref: !Ref ApiId
  UpdateStaticInfoFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aws-restapi/
      Handler: source/static-info/staticinfo-update.updateStaticInfo
      Runtime: nodejs14.x
      Events:
        UpdateStaticInfoAPIEvent:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /staticinfo/update
            Method: post
            RestApiId:
              Ref: !Ref ApiId
  
  

However, I can't build this project with sam build. I get the following error.

InvalidSamDocumentException(
samcli.commands.validate.lib.exceptions.InvalidSamDocumentException: [InvalidResourceException('GetAllPromotionsFunction', 'Event with id [GetAllPromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.')

Above error is generated for all the functions in the nested stack. If you need the full stacktrace, it is below.

Traceback (most recent call last):
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/samlib/wrapper.py", line 68, in run_plugins
    parser.parse(template_copy, all_plugins)  # parse() will run all configured plugins
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/samlib/wrapper.py", line 88, in parse
    sam_plugins.act(LifeCycleEvents.before_transform_template, sam_template)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samtranslator/plugins/__init__.py", line 136, in act
    raise ex
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samtranslator/plugins/__init__.py", line 133, in act
    getattr(plugin, method_name)(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samtranslator/plugins/api/implicit_api_plugin.py", line 100, in on_before_transform_template
    raise InvalidDocumentException(errors)
samtranslator.model.exceptions.InvalidDocumentException: [InvalidResourceException('GetAllPromotionsFunction', 'Event with id [GetAllPromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('SavePromotionsFunction', 'Event with id [SavePromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('UpdatePromotionsFunction', 'Event with id [UpdatePromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('GetAllStaticInfoFunction', 'Event with id [GetAllStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('SaveStaticInfoFunction', 'Event with id [SaveStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('UpdateStaticInfoFunction', 'Event with id [UpdateStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.')]

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/homebrew/bin/sam", line 8, in <module>
    sys.exit(cli())
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/decorators.py", line 73, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/telemetry/metric.py", line 153, in wrapped
    raise exception  # pylint: disable=raising-bad-type
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/telemetry/metric.py", line 122, in wrapped
    return_value = func(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/utils/version_checker.py", line 42, in wrapped
    actual_result = func(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/cli/main.py", line 90, in wrapper
    return func(*args, **kwargs)
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/commands/build/command.py", line 210, in cli
    do_cli(
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/commands/build/command.py", line 279, in do_cli
    with BuildContext(
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/commands/build/build_context.py", line 84, in __enter__
    self._stacks, remote_stack_full_paths = SamLocalStackProvider.get_stacks(
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/providers/sam_stack_provider.py", line 242, in get_stacks
    stacks_in_child, remote_stack_full_paths_in_child = SamLocalStackProvider.get_stacks(
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/providers/sam_stack_provider.py", line 236, in get_stacks
    current = SamLocalStackProvider(
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/providers/sam_stack_provider.py", line 51, in __init__
    self._template_dict = self.get_template(
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/providers/sam_base_provider.py", line 189, in get_template
    template_dict = SamTranslatorWrapper(template_dict, parameter_values=parameters_values).run_plugins()
  File "/opt/homebrew/Cellar/aws-sam-cli/1.29.0/libexec/lib/python3.8/site-packages/samcli/lib/samlib/wrapper.py", line 70, in run_plugins
    raise InvalidSamDocumentException(
samcli.commands.validate.lib.exceptions.InvalidSamDocumentException: [InvalidResourceException('GetAllPromotionsFunction', 'Event with id [GetAllPromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('SavePromotionsFunction', 'Event with id [SavePromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('UpdatePromotionsFunction', 'Event with id [UpdatePromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('GetAllStaticInfoFunction', 'Event with id [GetAllStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('SaveStaticInfoFunction', 'Event with id [SaveStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.'), InvalidResourceException('UpdateStaticInfoFunction', 'Event with id [UpdateStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.')] ('GetAllPromotionsFunction', 'Event with id [GetAllPromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.') ('GetAllStaticInfoFunction', 'Event with id [GetAllStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.') ('SavePromotionsFunction', 'Event with id [SavePromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.') ('SaveStaticInfoFunction', 'Event with id [SaveStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.') ('UpdatePromotionsFunction', 'Event with id [UpdatePromotionsAPIEvent] is invalid. Api Event must reference an Api in the same template.') ('UpdateStaticInfoFunction', 'Event with id [UpdateStaticInfoAPIEvent] is invalid. Api Event must reference an Api in the same template.')

How can I fix this?

like image 731
PeakGen Avatar asked Oct 27 '25 14:10

PeakGen


1 Answers

If you look into the documentation for the API Event for the serverless function, they write:

RestApiId Identifier of a RestApi resource, which must contain an operation with the given path and method. Typically, this is set to reference an AWS::Serverless::Api resource defined in this template.

If you don't define this property, AWS SAM creates a default AWS::Serverless::Api resource using a generated OpenApi document. That resource contains a union of all paths and methods defined by Api events in the same template that do not specify a RestApiId.

This cannot reference an AWS::Serverless::Api resource defined in another template.

template.yaml:

NestedStackTwo:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: nestedstack.yaml
      Parameters:
        ApiId: !Ref ApiGatewayApi

nestedstack.yaml:

Parameters:
   ApiId:
     Type: string
like image 61
Robert Kossendey Avatar answered Oct 30 '25 07:10

Robert Kossendey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!