26/11/2022
Here's a sample code to connect to your relational database, with your db-credentials stored in
import mysql.connector
import boto3
import json
client = boto3.client('secretsmanager')
response = client.get_secret_value(
SecretId='dev/myapp/secret'
)
secretDict = json.loads(response['SecretString'])
mydb = mysql.connector.connect(
host=secretDict['host'],
user=secretDict['username'],
password=secretDict['password'],
database=secretDict['dbname']
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM Persons")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Prerequisite:
Use the AWS Management Console to create and store your database secret, in Secrets Manager. Also, Boto3 will work with minimum Python 3.7 (Refer: https://lnkd.in/dW9r7YTc)
Note:
Use the AWS managed KMS key for Secrets Manager (aws/secretsmanager) to encrypt your secret. There is no cost for using this default KMS key.