CloudFormation,与RDS和Lambda的联网问题

试图获得启用HTTP的Lambda连接到RDS数据库,获取结果并返回给调用者。 我得到各种超时,这让我疯狂。 我从来没有真正涉及到基础设施方面的事情,所以我所说的一些可能会失去标志。

当我尝试创build没有任何VPC的Lambda和Postgres数据库时,Lambda没有连接到Postgres – 超时。

当我尝试创build一个基本的VPC,并将其中的Lambda和数据库,Lambda连接并获得行,但然后Lambda本身无法退出VPC和超时。

我正在尝试通过CloudFormation来做到这一点,所以我不必担心回溯我的步骤。 到目前为止,我有这个。 它应该创造

  • 一个VPC
  • 我的地区有三个子网
  • 我的数据库的子网
  • 我的职能的安全组
  • 我的数据库的安全组

我认为我需要以某种方式将这些function组合在一起,但我不知道这是如何工作的。 任何人都可以把我放在正确的轨道上?

ServerlessVPC: Type: AWS::EC2::VPC Properties: CidrBlock: "10.0.0.0/16" ServerlessSubnetA: DependsOn: ServerlessVPC Type: AWS::EC2::Subnet Properties: VpcId: Ref: ServerlessVPC AvailabilityZone: ${self:provider.region}a CidrBlock: "10.0.0.0/24" ServerlessSubnetB: DependsOn: ServerlessVPC Type: AWS::EC2::Subnet Properties: VpcId: Ref: ServerlessVPC AvailabilityZone: ${self:provider.region}b CidrBlock: "10.0.1.0/24" ServerlessSubnetC: DependsOn: ServerlessVPC Type: AWS::EC2::Subnet Properties: VpcId: Ref: ServerlessVPC AvailabilityZone: ${self:provider.region}c CidrBlock: "10.0.2.0/24" ServerlessSecurityGroup: DependsOn: ServerlessVPC Type: AWS::EC2::SecurityGroup Properties: GroupDescription: SecurityGroup for Serverless Functions VpcId: Ref: ServerlessVPC ServerlessStorageSecurityGroup: DependsOn: ServerlessVPC Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Ingress for RDS Instance VpcId: Ref: ServerlessVPC SecurityGroupIngress: - IpProtocol: tcp FromPort: '5432' ToPort: '5432' SourceSecurityGroupId: Ref: ServerlessSecurityGroup - IpProtocol: tcp FromPort: '11211' ToPort: '11211' SourceSecurityGroupId: Ref: ServerlessSecurityGroup SecurityGroupEgress: ServerlessRDSSubnetGroup: Type: AWS::RDS::DBSubnetGroup Properties: DBSubnetGroupDescription: "RDS Subnet Group" SubnetIds: - Ref: ServerlessSubnetA - Ref: ServerlessSubnetB - Ref: ServerlessSubnetC ServerlessRDSCluster: DependsOn: ServerlessStorageSecurityGroup Type: "AWS::RDS::DBInstance" Properties: DBName: ${self:custom.database_name} AllocatedStorage: 10 DBInstanceClass: "db.t2.micro" Engine: "postgres" EngineVersion: "9.6.2" MasterUsername: ${self:custom.env.DATABASE_USER} MasterUserPassword: ${self:custom.env.DATABASE_PASSWORD} VPCSecurityGroups: - "Fn::GetAtt": ServerlessStorageSecurityGroup.GroupId DBSubnetGroupName: Ref: ServerlessRDSSubnetGroup DeletionPolicy: "Snapshot" 

为了让您的Lambdafunction(a)访问您的RDS实例,以及(b)访问外部世界,您需要将Lambdafunction放入您的VPC中,并添加一个NAT到您的VPC以便外部访问。

请执行下列操作:

  1. 将您的Lambda函数放入VPC中的私有子网中。
  2. 公有子网中添加NAT实例或网关。
  3. 确保您的私有子网的路由表允许访问RDS实例。
  4. 确保您的私有子网的路由表将直接出站stream量转发到NAT。
  5. 如果Lambda函数支持安全组,请确保您的RDS实例的安全组允许访问您的Lambda函数的安全组。 如果Lambda函数不支持安全组,请确保您的RDS实例的安全组允许从您的私有子网或VPC的CIDR块进行访问。

在您的云端模板中,我没有看到任何公共子网,也没有Internet或NAT网关。 我不使用CloudFormation或Lambda,所以可能会有一些不必要的魔法,但是对于一般的VPC,如果您想要私有子网中的某些内容能够与外部世界通信,则需要使用NAT网关(最好是每个AZ一个),NAT网关的公共子网,NAT网关通过的Internet网关,以及通过NAT网关在私有子网中的默认路由。

如果您查看帐户中的默认VPC,并追踪所有已连接的位,则会看到您需要设置的结构types。