如何从Lambda函数连接到serverless.yml中“资源”下定义的RDS?

时间:2019-05-23 21:54:22

标签: amazon-cloudformation serverless-framework

说我在serverless.yml中有这样一个部分:

resources: 
  Resources:
    RDSCluster:
      Type: AWS::RDS::DBCluster
      Properties:
        MasterUsername: SomeUserName
        MasterUserPassword: SomePassword
        DatabaseName: SomeDatabaseName
        Engine: aurora
        EngineMode: serverless
        ScalingConfiguration:
          AutoPause: true
          MaxCapacity: 16
          MinCapacity: 2
          SecondsUntilAutoPause: 300

我用node.js编写的Lambda函数如何连接到该数据库,即什么是主机名/ ip,以及在哪里/如何捕获它?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用cloudformation的GetAtt函数访问DBCluster创建中的返回值:

provider:
  environment:
    RDS:
      Fn::GetAtt: [ RDSCluster, Endpoint.Address ]

现在您可以像下面这样在node.js代码中访问RDS FQDN(主机名+域名):

console.log(process.env.RDS);
// mystack-mydb-1apw1j4phylrk.cg034hpkmmjt.us-east-2.rds.amazonaws.com

您可以在此处查看有关DBCluster资源的Cloudformation返回值的更多信息:https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#aws-properties-rds-database-instance-return-values