从 VPC 内访问 VPC 外的 AWS 资源 - Serverless Framework

Access AWS Resource Outside of VPC from Within VPC - Serverless Framework

我正在尝试从 VPC 内的 lambda 函数访问 VPC 外的运动流。当前,当执行写入运动流的代码时,它将挂起然后超时。当我从 VPC 中取出 lambda 时,写入流的代码工作正常。但我需要访问 VPC 中的资源,然后写入流。有人知道怎么修这个东西吗?

这是我在 VPC 中的函数

functions:
  handleChanges:
    handler: functions/handlers.handleChanges
    timeout: 10
    package:
      include:
        - functions/utils/**
    events:
      - http:
          method: POST
          path: "/"
          integration: lambda
    vpc:
      securityGroupIds:
        - ${file(./private.yml):variables.securityGroup}
      subnetIds:
        - ${file(./private.yml):variables.subnetID}

这是我的政策

iamRoleStatements:
  - Effect: "Allow"
    Action:
      - "kinesis:PutRecord"
      - "kinesis:GetRecords"
      - "kinesis:GetShardIterator"
      - "kinesis:DescribeStream"
      - "kinesis:ListStreams"
    Resource:
      Fn::GetAtt:
        - KinesisStream
        - Arn
  - Effect: "Allow"
    Action:
      - "cognito-idp:AdminGetUser"
    Resource: "*"
  - Effect: "Allow"
    Action:
      - "logs:CreateLogGroup"
      - "logs:CreateLogStream"
      - "logs:PutLogEvents"
      - "ec2:CreateNetworkInterface"
      - "ec2:DescribeNetworkInterfaces"
      - "ec2:DeleteNetworkInterface"
    Resource: "*"

最后这是我的运动流资源

KinesisStream:
  Type: AWS::Kinesis::Stream
  Properties:
    Name: ${self:provider.environment.STREAM_NAME}
    ShardCount: 1

唯一的解决方案是向您的 VPC 添加一个 NAT Gateway (or NAT instance),这样位于私有子网中的资源(例如您的 Lambda 函数)将可以访问 VPC 外部的资源。

无需 NAT,您也可以使用 VPC 端点: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html 这就是对 Kinesis 的处理方法: https://docs.aws.amazon.com/streams/latest/dev/vpc.html

适合我 :) 并且匹配更便宜。 确保设置正确的安全组(私有 VPC 的 sg 而不是默认 VPC)

如果您要阅读 NAT 定价文档,他们也会推荐这个: https://aws.amazon.com/vpc/pricing/ 阅读最后的注释:

Note: To avoid the NAT Gateway Data Processing charge in this example, you could setup a Gateway Type VPC endpoint and route the traffic to/from S3 through the VPC endpoint instead of going through the NAT Gateway. There is no data processing or hourly charges for using Gateway Type VPC endpoints. For details on how to use VPC endpoints, please visit VPC Endpoints Documentation.