首页 文章

获取对在CloudFormation中触发AWS :: Serverless :: Function的Api的引用

提问于
浏览
0

在CloudFormation模板中,我正在定义一个带有由API网关触发的lambda函数的无服务器应用程序,如下所示:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      # ...
      Events:
        GetStuff:
          Type: Api
          Properties:
            Path: /stuff
            Method: get

这将生成一个API网关资源,该资源设置为接收 GET 请求并转发到我的lambda,它可以正常工作 .

但是,我无法弄清楚如何在模板的 Output 部分中引用该API实例:

Output:
  MyGatewayId:
    Description: Id of the auto-generated API Gateway resource
    Value: # what do I put here?

我按照建议here尝试了 !GetAtt MyFunction.RootResourceId ,但是当我尝试部署堆栈时导致失败:

创建变更集失败:Waiter ChangeSetCreateComplete失败:服务员遇到终端故障状态:FAILED . 原因:模板资源属性“MyGatewayId”无效

2 回答

  • 2

    如果您真的希望能够输出关键是了解无服务器转换正在为您做什么,根据您的规范生成一系列资源 .

    您可以检查您的CloudFormations资源,但要根据您的规范确定

    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    
    Resources:
      MyFunction:
        Type: AWS::Serverless::Function
        Properties:
          # ...
          Events:
            GetStuff:
              Type: Api
              Properties:
                Path: /stuff
                Method: get
    

    它应该为您生成一些资源 . 根据您的 Events 属性以及未指定RestApiId的事实,它将为您生成默认的API Gateway Rest API,并为其提供 ServerlessRestApi 的逻辑ID . 所以回答你关于 Outputs 的原始问题

    Output:
      MyGatewayId:
        Description: Id of the auto-generated API Gateway resource
        Value: !Ref ServerlessRestApi
    
  • 1

    如果在模板中指定API网关,则可以将其作为输出 .

    Resources:
      MyAPI
        Type AWS::Serverless::Api
        Properties:
          DefinitionUri: s3://<bucket>/swagger.yaml
    

    使用此方法,您可以在输出中使用资源 . 但是,这也要求您使用swagger,因为 DefinitionUri 是必需属性 .

    您始终可以使用以下命令提取id:

    aws cloudformation describe-stack-resources --stack-name <your-stack> \
        --query "StackResources[?ResourceType == 'AWS::ApiGateway::RestApi'].PhysicalResourceId" \
        --output text
    

    这意味着您还可以通过以下方式轻松地将URL提取到API:

    aws cloudformation describe-stack-resources --stack-name <your-stack> \
        --query "StackResources[?ResourceType == 'AWS::ApiGateway::RestApi'].PhysicalResourceId" \
        --output text \
        | awk '{print "https://"$1".execute-api.eu-west-1.amazonaws.com/Prod"}'
    

相关问题