Files
code-dumps/py/mysql-proxy.py
T
2024-12-19 20:14:00 +08:00

41 lines
1.4 KiB
Python

import json
import pymysql
import pymysql.cursors
import boto3
import traceback
def lambda_handler(event, context):
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name='ap-east-1'
)
secret = client.get_secret_value(
SecretId='your-mysql-proxy-secret'
)
#print(secret.get("SecretString"))
secret_dict = json.loads(secret.get("SecretString"))
print("* Retrieved secret from sm. DB username is", secret_dict.get('username'))
print("* Trying to connect to rds proxy...")
try:
# Connect to the database
connection = pymysql.connect(host="xxxx.ap-east-1.rds.amazonaws.com",
user=secret_dict.get('username'),
password=secret_dict.get('password'),
database="mysql",
cursorclass=pymysql.cursors.DictCursor,
connect_timeout=10,
ssl_ca="global-bundle.pem",
ssl_verify_identity=False)
print("* Connected to rds proxy. Running query...")
cur = db.cursor(pymysql.cursors.DictCursor)
sql = "SELECT User from mysql.user"
cur.execute(sql)
for row in cur:
print(row)
except pymysql.err.OperationalError as e1:
print("* Connection failed - ", e1)