Search code examples
amazon-web-servicesaws-cloudformationaws-cloudformation-custom-resourcenested-stack

Use Nested Stack to separate API gateway error with ouse on other stacks


I have a error when try to deploy a nested stacks does one have APIGateway setups, and others has lambdas services

MainTemplate

Resources:
  SubStackAPIDev:
    Type: 'AWS::CloudFormation::Stack'
    Properties:
      TemplateURL: https://c....
      TimeoutInMinutes: 5
      
  SubStacklambdaA:
    Type: 'AWS::CloudFormation::Stack'
    Properties:
      TemplateURL: https://c....
      TimeoutInMinutes: 5
      Parameters:
        APIDev: !Ref APIGateway
.....

SubStackAPIDev

AWSTemplateFormatVersion: "2010-09-09"

Transform: AWS::Serverless-2016-10-31

....

Outputs:

  APIGateway:
    Description: "API Gateway Reference"
    Value: !Ref APIDev
    Export:
      Name: !Join [":", [!Ref "AWS::StackName", "APIDev"]]

SubStacklambdaA


AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Parameters:
   SecretsManagerName:
     ....
   APIDev:
     Type: string

Resources:
  LambdaFunctionDev:
    Type: AWS::Serverless::Function
    Properties:
      ...
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: ....
            Method: POST
            RestApiId: !Ref APIDev

When I execute sam package command, console return next error:

sam deploy --force-upload --template-file maintemplate-packaged.yaml --stack-name $STACK_NAME_DEV --region $AWS_REGION --capabilities CAPABILITY_AUTO_EXPAND CAPABILITY_IAM

Initiating deployment
=====================
Error: Failed to create changeset for the stack: B2bChannels-dev, An error occurred (ValidationError) when calling the CreateChangeSet operation: Template format error: Unresolved resource dependencies [APIGateway] in the Resources block of the template

How can I export ApGateWay resource to main template, to send another stack?


Solution

  • To refer to the output from a nested stack, you should use GetAtt:

      SubStacklambdaA:
        Type: 'AWS::CloudFormation::Stack'
        Properties:
          TemplateURL: https://c....
          TimeoutInMinutes: 5
          Parameters:
            APIDev: !GetAtt SubStackAPIDev.Outputs.APIGateway