简体   繁体   English

通过lambda使用psycopg2连接到亚马逊RDS

[英]connecting to amazon rds with psycopg2 via lambda

my code on aws lambda: 我在AWS Lambda上的代码:

import sys, boto3, logging, rds_config, psycopg2

rds_host = "hostname"
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name

s3 = boto3.resource('s3')
rds_client = boto3.client('rds',aws_access_key_id=Access_Key,aws_secret_access_key=Secret_Access_Key)
instances = rds_client.describe_db_instances()
print (instances)

try:
    conn = psycopg2.connect(host=rds_host,
                        database=db_name,
                        user=name,
                        password=password)
    cur = conn.cursor()

except:
    logger.error("ERROR: Unexpected error: Could not connect to Postgresql instance.")
    sys.exit()

I believe I have with boto3.client connected to RDS Instance because the info of instance is outputed to screen. 我相信我的boto3.client已连接到RDS实例,因为实例的信息已输出到屏幕。

But with psycopg2 that will not do. 但是使用psycopg2则不会。
And instead of logger.error I got the time out error message: 而不是logger.error我得到了超时错误消息:

Task timed out after 60.06 seconds

in addition: I can connect to RDS either with my local psql console or with python script from my local server. 另外:我可以使用本地psql控制台或本地服务器中的python脚本连接到RDS。 Only if I test the script with aws-lambda online, it doesn´t work 仅当我在线使用aws-lambda测试脚本时,它才起作用

Any help Regarding this? 有什么帮助吗? Thank you! 谢谢!

The RDS documentation suggest that if you are getting timeout errors and the host and port are correct then you should check the security group that the DB is in allows network access. RDS文档建议,如果遇到超时错误并且主机和端口正确,则应检查数据库所在的安全组是否允许网络访问。 By default DB instances are not given network access. 默认情况下,不授予数据库实例网络访问权限。

See Getting Started and Controlling Access with Amazon RDS Security Groups 请参阅入门使用Amazon RDS安全组控制访问

Hab the same issue recently. 最近遇到同样的问题。 The 60 seconds are typical for a timeout connecting to the RDB instance. 60秒通常是连接到RDB实例的超时时间。

Double check your security groups and vpc settings, by default access is denied and you need to enable it explicitly. 仔细检查您的安全组和vpc设置,默认情况下拒绝访问,您需要显式启用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM