|
| 1 | +import json |
| 2 | +import boto3 |
| 3 | +from os import environ |
| 4 | +import pymysql |
| 5 | + |
| 6 | +client = boto3.client('rds') # get the rds object |
| 7 | + |
| 8 | + |
| 9 | +def create_connection_token(): |
| 10 | + |
| 11 | + # get the required parameters to create a token |
| 12 | + region = environ.get('region') # get the region |
| 13 | + hostname = environ.get('rds_endpoint') # get the rds proxy endpoint |
| 14 | + port = environ.get('port') # get the databse port |
| 15 | + username = environ.get('username') # get the database username |
| 16 | + |
| 17 | + # generate the authentication token -- temporary password |
| 18 | + token = client.generate_db_auth_token( |
| 19 | + DBHostname=hostname, |
| 20 | + Port=port, |
| 21 | + DBUsername=username, |
| 22 | + Region=region |
| 23 | + ) |
| 24 | + |
| 25 | + return token |
| 26 | + |
| 27 | + |
| 28 | +def db_ops(): |
| 29 | + # get the temporary password |
| 30 | + token = create_connection_token() |
| 31 | + try: |
| 32 | + # create a connection object |
| 33 | + connection = pymysql.connect( |
| 34 | + host=environ.get('your rds proxy endpoint'), # getting the rds proxy endpoint from the environment variables |
| 35 | + user=environ.get('your database user'), # get the database user from the environment variables |
| 36 | + password=token, |
| 37 | + db=environ.get('your database'), |
| 38 | + charset='utf8mb4', |
| 39 | + cursorclass=pymysql.cursors.DictCursor, |
| 40 | + ssl={"use": True } |
| 41 | + ) |
| 42 | + except pymysql.MySQLError as e: |
| 43 | + return e |
| 44 | + |
| 45 | + return connection |
| 46 | + |
| 47 | + |
| 48 | +def lambda_handler(event, context): |
| 49 | + # TODO implement |
| 50 | + conn = db_ops() |
| 51 | + cursor = conn.cursor() |
| 52 | + query = "SELECT count(*) FROM customer_entity" |
| 53 | + cursor.execute(query) |
| 54 | + results = cursor.fetchmany(4) |
| 55 | + |
| 56 | + return { |
| 57 | + 'statusCode': 200, |
| 58 | + 'body': json.dumps(results) |
| 59 | + } |
0 commit comments