【问题标题】:Need to configure serverless resource output to get api gateway api id需要配置serverless资源输出获取api gateway api id
【发布时间】:2017-12-09 19:08:24
【问题描述】:

我有一个无服务器项目,它正在创建 API 网关 API 等等。项目中的其中一个函数需要为 API 端点生成 URL。

我的计划是使用 serverless.yml 中的资源输出获取 API ID,然后创建 URL 并将其作为 env 参数传递给 lambda 函数。

我的问题/疑问是如何在 serverless.yml 中获取 API ID 作为云形成输出?

我试过了:

resources:
  Outputs:
    RESTApiId:
      Description: The id of the API created in the API gateway
      Value:
        Ref: name-of-api

但这给出了错误:

The CloudFormation template is invalid: Unresolved resource dependencies [name-of-api] in the Outputs block of the template

【问题讨论】:

  • 如果在同一个项目中,不能直接将{Ref: myApiGateway}输出到函数的环境变量中吗?

标签: aws-api-gateway amazon-cloudformation serverless-framework


【解决方案1】:

你可以在serverless.yml文件中写这样的东西:

provider:
  region: ${opt:region, 'eu-west-1'}
  stage: ${opt:stage, 'dev'}
  environment:
    REST_API_URL:
      Fn::Join:
        - ""
        - - "https://"
          - Ref: "ApiGatewayRestApi"
          - ".execute-api."
          - ${self:provider.region}
          - Ref: "AWS::URLSuffix"
          - "/"
          - ${self:provider.stage}"

现在您可以使用可选的命令行选项 --stage 和/或 --region 调用 serverless 来覆盖上面定义的默认值,例如:

serverless deploy --stage production --region us-east-1

然后您可以在您的代码中使用环境变量REST_API_URL

node.js:

const restApiUrl = process.env.REST_API_URL;

蟒蛇:

import os
rest_api_url = os.environ['REST_API_URL']

Java:

String restApiUrl = System.getenv("REST_API_URL");

【讨论】:

  • 这不是这个问题的答案。输出可以在堆栈之间共享,但环境不能
【解决方案2】:

无服务器框架有一个关于它们如何为资源生成名称的文档页面。

看。 AWS CloudFormation Resource Reference

所以生成的RestAPI资源被称为ApiGatewayRestApi

【讨论】:

    【解决方案3】:

    不幸的是,文档没有提到它:

    resources:
      Outputs:
        apiGatewayHttpApiId:
          Value:
            Ref: HttpApi
          Export:
            Name: YourAppHttpApiId
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-11
      • 2017-04-23
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 2023-01-08
      相关资源
      最近更新 更多