# Cannot connect to a AWS RDS mysql database from lambda serverless in python

**URL:** <https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817>\
**Category:** Serverless Framework\
**Tags:** lambda\
**Created:** [February 20, 2018, 10:49pm UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817 "2018-02-20T22:49:24Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![michaelmei](https://avatars.discourse-cdn.com/v4/letter/m/d07c76/32.png) [@michaelmei](https://forum.serverless.com/u/michaelmei)\
**Post date:** [February 20, 2018, 10:49pm UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/1 "2018-02-20T22:49:24Z")

</div>

I have wrote an AWS lambda function in python to access my mysql instance in RDS. The mysql instance is in the same region as the AWS lambda function and was assigned a default VPC.

The following is the python handler code, with an error printing out: “ERROR: Unexpected error: Could not connect to MySql instance”. The handler is “mysql\_test”. I am new to [serverless.com](http://serverless.com). Would you guys please help me in this issue since it is very urgent and important for our business to migrate from the traditional architecture to serverless framework. Thanks!

**import sys**  
**import logging**  
**import pymysql**

**name = "xxxx"**  
**password = "xxxxxxxxxx"**  
**db\_name = "xxxxxxxxxx"**  
**rds\_host = "[xxxxxxxxxxxx.us-west-2.rds.amazonaws.com](http://xxxxxxxxxxxx.us-west-2.rds.amazonaws.com)"**  
**port = 3306**

**logger = logging.getLogger()**  
**logger.setLevel(logging.INFO)**

**try:**  
\*\* conn = pymysql.connect(rds\_host, user=name,\*\*  
\*\* passwd=password, db=db\_name, connect\_timeout=5)\*\*  
**except:**  
\*\* logger.error(“ERROR: Unexpected error: Could not connect to MySql instance.”)\*\*  
\*\* sys.exit()\*\*

**logger.info(“SUCCESS: Connection to RDS mysql instance succeeded”)**

**def mysql\_test(event, context):**  
\*\* “”"\*\*  
\*\* This function inserts content into mysql RDS instance\*\*  
\*\* “”"\*\*  
\*\* item\_count = 0\*\*

\*\* with conn.cursor() as cur:\*\*  
\*\* cur.execute(“create table Employee3 (EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))”)\*\*  
\*\* cur.execute(‘insert into Employee3 (EmpID, Name) values(1, “Joe”)’)\*\*  
\*\* cur.execute(‘insert into Employee3 (EmpID, Name) values(2, “Bob”)’)\*\*  
\*\* cur.execute(‘insert into Employee3 (EmpID, Name) values(3, “Mary”)’)\*\*  
\*\* conn.commit()\*\*

\*\* cur.execute(“select \* from Employee3”)\*\*  
\*\* for row in cur:\*\*  
\*\* item\_count += 1\*\*  
\*\* logger.info(row)\*\*

\*\* response = {\*\*  
\*\* “statusCode”: 200,\*\*  
\*\* “body”: “Added %d items to RDS MySQL table” %(item\_count)\*\*  
\*\* }\*\*

\*\* return response\*\*

Best,  
Michael

---

<div class="post-metadata">

**Author:** ![rupakg](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/rupakg/32/900_2.png) [@rupakg](https://forum.serverless.com/u/rupakg)\
**Post date:** [February 21, 2018, 12:12am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/2 "2018-02-21T00:12:05Z")

</div>

@michaelmei just browsing your code looks like you might have to pass in the `port` as well in your connection string.

---

<div class="post-metadata">

**Author:** ![michaelmei](https://avatars.discourse-cdn.com/v4/letter/m/d07c76/32.png) [@michaelmei](https://forum.serverless.com/u/michaelmei)\
**Post date:** [February 21, 2018, 12:44am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/3 "2018-02-21T00:44:30Z")

</div>

Hi @rupakg,

Thanks for pointing that out. I have changed the code to the following, but still got the same error message. Would it might be caused by the VPC network? Shall I configure the VPC network for the function even it is in the same aws region as the RDS mysql instance?

import sys  
import logging  
import pymysql

name = "xxxx"  
password = "xxxxxxxxxx"  
db\_name = "xxxxxxxxxx"  
rds\_host = "[xxxxxxxxxxxx.us-west-2.rds.amazonaws.com:3306](http://xxxxxxxxxxxx.us-west-2.rds.amazonaws.com:3306)"  
port = 3306

logger = logging.getLogger()  
logger.setLevel(logging.INFO)

try:  
\*\* conn = pymysql.connect(rds\_host, user=name,\*\*  
\*\* passwd=password, db=db\_name, connect\_timeout=5)\*\*  
except:  
\*\* logger.error(“ERROR: Unexpected error: Could not connect to MySql instance.”)\*\*  
\*\* sys.exit()\*\*

logger.info(“SUCCESS: Connection to RDS mysql instance succeeded”)

def mysql\_test(event, context):  
\*\* “”"\*\*  
\*\* This function inserts content into mysql RDS instance\*\*  
\*\* “”"\*\*  
\*\* item\_count = 0\*\*

\*\* with conn.cursor() as cur:\*\*  
\*\* cur.execute(“create table Employee3 (EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))”)\*\*  
\*\* cur.execute(‘insert into Employee3 (EmpID, Name) values(1, “Joe”)’)\*\*  
\*\* cur.execute(‘insert into Employee3 (EmpID, Name) values(2, “Bob”)’)\*\*  
\*\* cur.execute(‘insert into Employee3 (EmpID, Name) values(3, “Mary”)’)\*\*  
\*\* conn.commit()\*\*

\*\* cur.execute(“select \* from Employee3”)\*\*  
\*\* for row in cur:\*\*  
\*\* item\_count += 1\*\*  
\*\* logger.info(row)\*\*

\*\* response = {\*\*  
\*\* “statusCode”: 200,\*\*  
\*\* “body”: “Added %d items to RDS MySQL table” %(item\_count)\*\*  
\*\* }\*\*

\*\* return response\*\*

Best,  
Michael

---

<div class="post-metadata">

**Author:** ![rupakg](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/rupakg/32/900_2.png) [@rupakg](https://forum.serverless.com/u/rupakg)\
**Post date:** [February 21, 2018, 5:27am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/4 "2018-02-21T05:27:47Z")

</div>

@michaelmei Is the RDS configured within a VPC? If yes, then you have to configure you function to access the VPC network.

---

<div class="post-metadata">

**Author:** ![michaelmei](https://avatars.discourse-cdn.com/v4/letter/m/d07c76/32.png) [@michaelmei](https://forum.serverless.com/u/michaelmei)\
**Post date:** [February 21, 2018, 5:30am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/5 "2018-02-21T05:30:02Z")

</div>

Hi Rupak,

Yes. The RDS Mysql instance is in the default VPC. would you please give me an example of how to configure the function to be in the same VPC region in serverless yaml file?

Thanks!  
Michael.

---

<div class="post-metadata">

**Author:** ![rupakg](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/rupakg/32/900_2.png) [@rupakg](https://forum.serverless.com/u/rupakg)\
**Post date:** [February 21, 2018, 8:43am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/6 "2018-02-21T08:43:09Z")

</div>

@michaelmei you can put the following snippet under the `provider` section:

```auto
  vpc:
    securityGroupIds:
      - sg-xxxxxxx
    subnetIds:
      - subnet-xxxxxxx
  iamRoleStatements:
    - Effect: Allow
      Action:
        - "ec2:CreateNetworkInterface"
      Resource: "*"

```

Let me know if it works for you,

Thanks,  
Rupak Ganguly

---

<div class="post-metadata">

**Author:** ![michaelmei](https://avatars.discourse-cdn.com/v4/letter/m/d07c76/32.png) [@michaelmei](https://forum.serverless.com/u/michaelmei)\
**Post date:** [February 21, 2018, 11:55pm UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/7 "2018-02-21T23:55:18Z")

</div>

@rupakg Thanks for the reply. appreciated. Just changed the serverless.yaml as following. But I got the following error when trying to deploy. I have admin access to the user. Would you please provide any suggestion? Thank you heaps!

**(venv) MacBook-Pro:serverless-wechatapitest michaelmei$ serverless deploy**  
**Serverless: Installing required Python packages with python3.6…**  
**Serverless: Docker Image: lambci/lambda:build-python3.6**  
**Serverless: Linking required Python packages…**  
**Serverless: Packaging service…**  
**Serverless: Excluding development dependencies…**  
**Serverless: Unlinking required Python packages…**  
**Serverless: Uploading CloudFormation file to S3…**  
**Serverless: Uploading artifacts…**  
**Serverless: Uploading service .zip file to S3 (22.35 MB)…**  
**Serverless: Validating template…**  
**Serverless: Updating Stack…**  
**Serverless: Checking Stack update progress…**  
**Serverless: Operation failed!**  
\*\* Serverless Error ---------------------------------------\*\*  
\*\* An error occurred: IamRoleLambdaExecution - API: iam:AttachRolePolicy User: arn:aws:iam::xxxxxxxxxxxxx:user/xxxxxxxxx is not authorized to perform: iam:AttachRolePolicy on resource: role aws-python-wechatapi-dev-us-west-2-lambdaRole.\*\*  
\*\* Your Environment Information -----------------------------\*\*  
\*\* OS: darwin\*\*  
\*\* Node Version: 8.6.0\*\*  
\*\* Serverless Version: 1.25.0\*\*

# Below is my serverless yaml file

service: aws-python-wechatapi

frameworkVersion: “\>=1.2.0 \<2.0.0”

provider:  
name: aws  
stage: dev  
region: us-west-2  
runtime: python3.6  
vpc:  
securityGroupIds:  
- sg-xxxxxx  
subnetIds:  
- subnet-xxxxxxxxx  
- subnet-xxxxxxxxx  
- subnet-xxxxxxxxx  
iamRoleStatements:  
- Effect: Allow  
Action:  
- "ec2:CreateNetworkInterface"  
Resource: “\*”

functions:  
currentTime:  
handler: handler.mysql\_test  
events:  
- http:  
path: mysql  
method: get

resources:  
Resources:  
WriteDashPostLogGroup:  
Type: AWS::Logs::LogGroup  
Properties:  
RetentionInDays: "30"  
MyDB:  
Type: AWS::RDS::DBInstance  
Properties:  
DBName: 'xxxxxxxxxx’  
AllocatedStorage: '5’  
DBInstanceIdentifier: 'xxxxxxxxxx’  
DBInstanceClass: db.m1.small  
Engine: MySQL  
MasterUsername: xxxxxxxxxxxx  
MasterUserPassword: xxxxxxxxxxxx  
DeletionPolicy: Snapshot

plugins:

- serverless-python-requirements

custom:  
pythonRequirements:  
dockerizePip: non-linux

---

<div class="post-metadata">

**Author:** ![buggy](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/buggy/32/177_2.png) [@buggy](https://forum.serverless.com/u/buggy)\
**Post date:** [February 22, 2018, 5:44am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/8 "2018-02-22T05:44:05Z")

</div>

If you copied this directly from your serverless.config then it looks like you’ve indented the securityGroupIds and subnetIds too much. Instead of

```auto
  vpc:
      securityGroupIds:
        - sg-xxxxxx
      subnetIds:
        - subnet-xxxxxxxxx
        - subnet-xxxxxxxxx
        - subnet-xxxxxxxxx

```

use

```auto
  vpc:
    securityGroupIds:
      - sg-xxxxxx
    subnetIds:
      - subnet-xxxxxxxxx
      - subnet-xxxxxxxxx
      - subnet-xxxxxxxxx

```

---

<div class="post-metadata">

**Author:** ![michaelmei](https://avatars.discourse-cdn.com/v4/letter/m/d07c76/32.png) [@michaelmei](https://forum.serverless.com/u/michaelmei)\
**Post date:** [February 22, 2018, 6:21am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/9 "2018-02-22T06:21:39Z")

</div>

Hi @buggy, I have changed the indention and attached the screenshot of the configuration. Still got the error. Please indicate. Thanks!

 ![14%20pm](https://canada1.discourse-cdn.com/flex036/uploads/serverless/original/2X/8/82315b5f091fd82ec464eaba3ce22f6937d5a927.png)

---

<div class="post-metadata">

**Author:** ![alexdebrie1](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/alexdebrie1/32/899_2.png) [@alexdebrie1](https://forum.serverless.com/u/alexdebrie1)\
**Post date:** [February 22, 2018, 10:39am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/10 "2018-02-22T10:39:09Z")

</div>

@michaelmei Are you still getting the following error:

> [@michaelmei](#):
>
> An error occurred: IamRoleLambdaExecution - API: iam:AttachRolePolicy User: arn:aws:iam::xxxxxxxxxxxxx:user/xxxxxxxxx is not authorized to perform: iam:AttachRolePolicy on resource: role aws-python-wechatapi-dev-us-west-2-lambdaRole.

If so, it looks like a permissions error for your IAM user doing deploys. Are you still using the same credentials that were working previously?

---

<div class="post-metadata">

**Author:** ![michaelmei](https://avatars.discourse-cdn.com/v4/letter/m/d07c76/32.png) [@michaelmei](https://forum.serverless.com/u/michaelmei)\
**Post date:** [February 23, 2018, 3:29am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/11 "2018-02-23T03:29:55Z")

</div>

Hi @alexdebrie1,

Thanks for the reply. I have double checked with the iam user and it turned out it is the one that worked previously. Would you please refer to the following permission I gave to the user and provide some hints on it? Thanks!

 ![42%20pm](https://canada1.discourse-cdn.com/flex036/uploads/serverless/original/2X/0/0949835847a54d1179152149c61f31b2df5ca337.png)

---

<div class="post-metadata">

**Author:** ![kvarela](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/kvarela/32/2288_2.png) [@kvarela](https://forum.serverless.com/u/kvarela)\
**Post date:** [July 26, 2018, 12:14am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/12 "2018-07-26T00:14:25Z")

</div>

> [@rupakg](#):
>
> vpc: securityGroupIds: - sg-xxxxxxx subnetIds: - subnet-xxxxxxx iamRoleStatements: - Effect: Allow Action: - “ec2:CreateNetworkInterface” Resource: “\*”

Did you ever figure this out? I’m running into the same problem trying to connect to RDS Postgres within a VPC from my node lambda function. I’ve added the following to my serverless.yml, but it’s not helping:

```
provider:
  name: aws
  runtime: nodejs6.10
  vpc:
    securityGroupIds:
      - sg-011159da68f5dd3ae
    subnetIds:
      - subnet-36a85808
      - subnet-0465080b
      - subnet-c038488a
      - subnet-36a85808
      - subnet-85e14cd9
      - subnet-b1b311d6
      - subnet-fba20dd5
  iamRoleStatements:
    - Effect: Allow
      Action:
        - "ec2:CreateNetworkInterface"
      Resource: "*"

```

Any help much appreciated!

---

<div class="post-metadata">

**Author:** ![rupakg](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/rupakg/32/900_2.png) [@rupakg](https://forum.serverless.com/u/rupakg)\
**Post date:** [September 20, 2018, 3:24pm UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/13 "2018-09-20T15:24:05Z")

</div>

@kvarela What is not working? The above yaml looks good to me. Give me more details of what error you are seeing.

---

<div class="post-metadata">

**Author:** ![rudra1921](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/rudra1921/32/6294_2.png) [@rudra1921](https://forum.serverless.com/u/rudra1921)\
**Post date:** [October 22, 2021, 6:16pm UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/14 "2021-10-22T18:16:55Z")

</div>

Hello  
@michaelmei michaelmei  
@rupakg  
I am facing this same issue  
Cannot connect to a AWS RDS mysql database from lambda in python with same code … Kindly help me with this issue .

---

<div class="post-metadata">

**Author:** ![rudra1921](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/rudra1921/32/6294_2.png) [@rudra1921](https://forum.serverless.com/u/rudra1921)\
**Post date:** [October 25, 2021, 10:32am UTC](https://forum.serverless.com/t/cannot-connect-to-a-aws-rds-mysql-database-from-lambda-serverless-in-python/3817/15 "2021-10-25T10:32:27Z")

</div>

Can any one have solution for this issue
