AWS Lambda函数连接到RDS错误

时间:2017-08-05 09:49:32

标签: python amazon-web-services aws-lambda

我无法通过他们提供的测试示例使用Lambda函数连接到RDS

这是代码:

import sys
import logging
import rds_config
import pymysql
#rds settings
rds_host  = "connection_link"
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name


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 handler(event, context):
    """
    This function fetches content from 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)
            #print(row)

    return "Added %d items from RDS MySQL table" %(item_count)

这是我的部署包的结构

app/pymysql/...
app/app.py
app/rds_config.py
app/PyMySQL-0.7.11.dist-info/...

我已将app文件夹中的所有文件打包成zip文件。

这是错误是获取

  

" errorMessage":" RequestId:96fb4cd2-79c1-11e7-a2dc-f97407196dbb在完成请求之前退出流程"

我已经在MYSQL Workbench上检查了我的RDS连接工作正常

4 个答案:

答案 0 :(得分:0)

<强>更新

假设您的实际Python代码实际缩进正确,与您上面发布的代码不同。

由于某种原因,您的功能无法连接到您的数据库。而不是向用户返回错误,您基本上将其告诉sys.exit(1),这就是Lambda在完成请求之前说出&#34;流程退出的原因&#34;。

- 原始答案 -

这看起来不像AWS lambda处理程序。

你应该编写一个函数处理程序,接受lambda事件和context作为参数。

请从AWS Lambda documentation了解更多相关信息。

答案 1 :(得分:0)

您的zip文件存在问题。

我也使用相同的lambda函数。

请按照以下步骤操作。

1. your app.py and rds_config.py files are good.

2. Then download the pymysql https://pypi.python.org/pypi/PyMySQL

3. Extract it.

4. Copy the pymysql to somewhere. (Note: Dont add all contents inside the PyMySQL-0.7.11 folder, we just need pymysql only.)

5. Then create a zip file with app.py, rds_config.py and pymysql folder.

enter image description here

答案 2 :(得分:0)

正如@MarkB在评论中提到的,要进行连接,您需要在Lambda函数中将VPCSubnetsSecurity Group设置为与RDS实例相同: VPC, Subnets and Security group in Lambda function

,此外,您还需要检查ProtocolPortSource的安全组中的“入站和出站”,以确保它对您的IP和端口范围是开放的。 Open Port and IP range for your Security group

答案 3 :(得分:0)

我只是遇到了同样的问题,事实证明这是因为我在创建时没有为数据库指定名称。 轻松创建没有提供此选项,因此您必须使用 Standard Create ,其中可以在其他配置下指定名称。此名称是您应在 * This is a class that tests the Deck class using assert statements. */ public class DeckTester { /** * The main method in this class checks the Deck operations for consistency * using assert statements. * @param args is not used. */ public static void main(String[] args) { test2CardDeck(); test1CardDeck(); testShuffle(); //Line 15 System.out.println("All tests passed!"); } /** * Create a 1-card Deck and test the Deck methods with it. */ private static void test1CardDeck() { String[] r1 = {"ace"}; String[] s1 = {"spades"}; int[] v1 = {1}; Deck d = new Deck(r1, s1, v1); testOneCard(d, new Card("ace", "spades", 1)); testEmpty(d); d.shuffle(); testOneCard(d, new Card("ace", "spades", 1)); testEmpty(d); } /** * Create a 2-card Deck and test the Deck methods with it. */ private static void test2CardDeck() { String[] r2 = {"ace", "2"}; String[] s2 = {"hearts"}; int[] v2 = {1, 2}; Deck d = new Deck(r2, s2, v2); assert d.size() == 2 : "Initial size is " + d.size() + ". It should be 2."; assert !d.isEmpty() : "Initial deck is empty."; boolean aceIsFirst, twoIsFirst; Card c = d.deal(); assert c != null : "1st card dealt is null."; aceIsFirst = c.matches(new Card("ace", "hearts", 1)); twoIsFirst = c.matches(new Card("2", "hearts", 2)); assert (aceIsFirst || twoIsFirst) : "1st card dealt is " + c + ". It is not the one of the two correct cards."; assert d.size() == 1 : "Size after one deal is " + d.size() + ". It should be 1."; assert !d.isEmpty() : "Deck is empty after one deal."; c = d.deal(); assert c != null : "2nd card dealt is null."; if (aceIsFirst) { assert c.matches(new Card("2", "hearts", 2)) : "2nd card dealt is " + c + ". It is not one of the two correct cards."; } else { assert c.matches(new Card("ace", "hearts", 1)) : "2nd card dealt is " + c + ". It is not one of the two correct cards."; } testEmpty(d); d.shuffle(); c = d.deal(); assert c != null : "1st card dealt after shuffle is null."; aceIsFirst = c.matches(new Card("ace", "hearts", 1)); twoIsFirst = c.matches(new Card("2", "hearts", 2)); assert (aceIsFirst || twoIsFirst) : "1st card dealt after shuffle is " + c + ". It is not the one of the two correct cards."; assert d.size() == 1 : "Size is " + d.size() + "after shuffle and one deal. It should be 1."; assert !d.isEmpty() : "Deck is empty after shuffle and one deal."; c = d.deal(); assert c != null : "2nd card dealt after shuffle is null."; if (aceIsFirst) { assert c.matches(new Card("2", "hearts", 2)) : "2nd card dealt after shuffle is " + c + ". It is not the one of the two correct cards."; } else { assert c.matches(new Card("ace", "hearts", 1)) : "2nd card dealt after shuffle is " + c + ". It is not the one of the two correct cards."; } testEmpty(d); } /** * Check that the given deck is empty. * @param d is a deck that should be empty. */ private static void testEmpty(Deck d) { assert d.size() == 0 : "Size for an empty deck is " + d.size() + ". It should be 0."; assert d.isEmpty() : "isEmpty is false for an empty deck."; Card c = d.deal(); assert c == null : "Dealt card is " + c + ". It should be null for an empty deck."; } /** * Check that the given deck contains the given card and nothing else. * @param d is a deck that should contain a single card. * @param intended is the card that the one-card deck should contain. */ private static void testOneCard(Deck d, Card intended) { assert d.size() == 1 : "Size is " + d.size() + ". It should be 1 for a 1-card deck."; assert !d.isEmpty() : "isEmpty true for a 1-card deck."; Card c = d.deal(); assert c != null : "1st dealt card is null for a 1-card deck."; assert c.matches(intended) : "1st card dealt for a 1-card deck is " + c + ". It should be " + intended + "."; } /** * Check that two decks constructed in succession aren't the same. */ private static void testShuffle() { String[] r = {"ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"}; String[] s = {"spades", "hearts", "diamonds", "clubs"}; int[] v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; Deck d1 = new Deck(r, s, v); Deck d2 = new Deck(r, s, v); assert d1 != d2 : "Decks d1 and d2 are the same physical object."; assert d1.size() == d2.size() : "Deck d1 size of " + d1.size() + " does not match deck d2 size of " + d2.size() + "."; boolean allMatch = true; while (!d1.isEmpty()) { Card c1 = d1.deal(); Card c2 = d2.deal(); if (c1.matches(c2)) { //Line 137 allMatch = false; } } assert !allMatch : "The sequence of cards in d1 and d2 are identical."; } }``` 中为db_name指定的名称。

enter image description here

或者,您可以连接选择的工具而无需数据库名称,执行rds_config.py,其中CREATE DATABASE xxx;是数据库的名称,然后使用可以继续使用该数据库。

来源:https://serverfault.com/a/996423

这也很重要:Why don't I have access to the database from aws lambda but have from a local computer with the same login data?