Search code examples
serverlessaws-sam-cliaws-sam

How to get stack output from AWS SAM?


I would like to perform automatic integration tests on my serverless projects. To do that, I need to get the api endpoints somehow. There is already the plugin serverless-stack-output for Serverless framework that serves the purpose. But I'm wondering how can I achieve similar thing by AWS SAM after I deploy my application?

Meanwhile, If I can somehow get my api's base url as well as individual endpoints, then I'm able to connect them and and perform tests against them.


Solution

  • As AWS SAM builds upon AWS CloudFormation you can use CloudFormation's Outputs-feature.

    How to define such outputs is pretty straight forward. You can e.g. refer to the "hello world" template in the SAM-template-repository. The relevant section is the definition of the outputs:

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

    You then still need a way to get the outputs after you deployed the CloudFormation stack. For that you can e.g. use the AWS CLI:

    aws cloudformation describe-stacks --stack-name mystack \
        --query 'Stacks[0].Outputs[?OutputKey==`HelloWorldApi`].OutputValue' \
        --output text