aws cannot connect to rds from lambda function

Asked 1 years ago, Updated 1 years ago, 423 views

I would like to create a linebot with aws-lambda.
When I wrote this code to connect to the database created by aws-rds via PyMySQL, I got an error.

def pickupDatabase():
    rds_host="rds endpoints"
    name = rds_config.db_username
    password = rds_config.db_password
    db_name = rds_config.db_name
    
    conn=pymysql.connect(host=rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
    msg=""
    item_count = 0
    
    with conn.cursor() as cur:
        cur.execute("select*from content")
        For row in cur:
            item_count+=1
            # logger.info(row)
    conn.close()
    
    return "Added% items from RDS MySQL table"%(item_count)
    
    

Tried
1. Verify Role
(Reference site: https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/services-rds-tutorial.html)
) →I made it based on the fact that I was going to create the execution role of the reference site, but it didn't change.

2. Verify that the contents of rds_config have been removed
→ I was able to take it out.I have also confirmed that there is no mistake.

Error Message Received

[ERROR] OperationalError: (2003, "Can't connect to MySQL server on 'test-database.cpstxnucpjex.ap-northeast-1.rds.amazonaws.com' (timed out)")

I think the reason for the error was that I couldn't connect to the database, but I checked and set up VPN settings, but it didn't work.
I'm sorry to ask you a beginner's question, but I'd like you to tell me what to check in this case and how to fix it frequently.
Thank you for your cooperation.

aws aws-lambda amazon-rds

2023-01-05 21:29

1 Answers

Based on the error message, you may not have been able to connect at the network level prior to authentication.

RDS is a service that is deployed within a VPC and Lambda is by default a service that is deployed outside the VPC, so there are two ways for a network to connect.

  • Assign VPCs to Lambda
  • Enable RDS public access

The latter is not generally recommended, so the former is recommended.Here's how to assign a VPC to Lambda:

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/configuration-vpc.html

One caveat is that Lambda must have access to the Internet access.Once you assign a VPC, Lambda will also access the Internet via the VPC, requiring NAT Gateway.


2023-01-05 23:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.