AWS:我可以在 VPC 内为 Lambda 函数提供对 public Websockets API 网关的访问权限吗?

AWS: Can I give a Lambda function inside a VPC access to a public Websockets API Gateway?

我在 API 网关中有一个 public API 使用 Websockets 协议。我将其连接 ID 存储在我的 VPC 内的数据存储中,并尝试编写一个 Lambda 来读取这些连接 ID,然后将数据发送给它们中的每一个 - 使用 await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: postData }).promise();。超时 - Lambda 无法将消息发送到 API 网关。所以我尝试将网关添加到 execute-apiaws ec2 create-vpc-endpoint --vpc-id vpc-xyz --vpc-endpoint-type Interface --service-name com.amazonaws.eu-west-1.execute-api --subnet-ids subnet-xyz --security-group-id sg-xyz。现在我通过调用 apigwManagementApi.

抛出了 ForbiddenException: Forbidden

我试过查看 execute-api 网关的文档,但是接口 https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html points to https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html 的文档会导致创建私有 APIs - 我不会想要这个,我需要我的 API 是 public。

我想我通常可以使用资源策略 https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies-examples.html 但这是一个 websocket API 所以这些说明不起作用,因为它们没有资源策略选项。

我在 AWS Slack 上询问过这个问题,无法使用资源策略并且会增加很多网络复杂性:https://awsdevelopers.slack.com/archives/C6LDW0BC3/p1570618074008500

来自该线程中的 AWS 开发人员:

hey there - when Lambda is VPC enabled, its subject to all routing rules of your VPC and Subnet.

To hit any public resource, you will need a NAT GW, routing rules, and SG setting to allow communication.

Resource polices will not work.

我遇到了同样的问题 - 此文档解释了问题的原因 (https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-vpc-connections/)。

要修复它,您需要添加边缘优化的自定义域名,这需要以下内容:

  • 将证书添加到 AWS ACM(您需要证书、私钥 和提供商根证书)到 us-east-1 ACM 管理器(你必须 将其添加到 us-east-1 以在边缘优化的证书列表中查看它。

  • 在 API 网关控制台中转到自定义域名并创建一个新域名。

  • 设置您的域名,将类型保留为边缘优化并应用您刚刚创建的证书

  • 域设置完成后(大约需要 40 分钟),您可以添加基本路径映射以将流量发送到您的 API/阶段。