AWS Lambda - Unable to connect to SQL Server RDS

前提是你 提交于 2019-12-06 12:29:39

问题


Hi I was having the same problem as this post but the posted answer (no sample code) wasn't provided so I will start a new thread and ask you guys.

I have created a AWS Serverless Application (.Net Core) project for our lambda function and below code is what I used to connect in AWS RDS.


string ConnectionString = "Data Source=rds4abc1190.asdfqwerqb9l.us-east-1.rds.amazonaws.com,2855;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=myID;Password=mypassword;Encrypt=False";

using (var Conn = new SqlConnection(ConnectionString))
{
     using (var Cmd = new SqlCommand("SELECT * from Customer", Conn))
     {
          Conn.Open(); //<-- this is where the error fires.

          SqlDataReader rdr = Cmd.ExecuteReader();
          while (rdr.Read())
          {
                myDbItems.Add(rdr[1].ToString());
          }

          Conn.Close();
      }
 }

Using the above code works fine when running on local machine but if deployed in AWS Api Gateway, that code would error.

"errorType": "SqlException", "errorMessage": "Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=781; handshake=1957; [Login] initialization=40; authentication=122; [Post-Login] complete=12219;",


回答1:


Added the following in each function in the serverless.template.

"Role": "arn:aws:iam::053984854873:role/1234-Dev",              
    "Policies": [ "AWSLambdaBasicExecutionRole", "AWSLambdaBasicExecutionRole-ABC1234","LambdaAccess-1234" ], 
    "VpcConfig" : {
        "SecurityGroupIds" : ["sg-4f2cbff1","sg-3584a444"],
        "SubnetIds" : ["subnet-f2520727","subnet-388b4ab2"]
    }



回答2:


If the answer is the same as the referenced post, then there wasn't any sample code because it isn't a code issue. He upgraded the database engine version in RDS because the drivers that AWS Lambda uses wouldn't support connections to MSSQL 2008 R2, while his local machine had the necessary drivers.

Here is the AWS doc on upgrading RDS SQL Server Engine versions:

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.SQLServer.html



来源:https://stackoverflow.com/questions/45003449/aws-lambda-unable-to-connect-to-sql-server-rds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!