Skip to content

Instantly share code, notes, and snippets.

@gaurish
Last active March 7, 2023 17:29
Show Gist options
  • Save gaurish/784be8b6bf44010307fac1aaa9961fcc to your computer and use it in GitHub Desktop.
Save gaurish/784be8b6bf44010307fac1aaa9961fcc to your computer and use it in GitHub Desktop.
Sample App to show how to use SSL / Secure connection to connect to AWS RDS using Python

Sample App to show how to use SSL / Secure connection to connect to AWS RDS using Python

$ docker build --build-arg DATABASE_URL=mysql2://user:[email protected]/gaurish -t mysql-python-app .

$ docker run -it --rm image id

Congrats, Connected to MySQL Server over SSL!

5.7.38-log

MySQL connection is closed

FROM python:3
WORKDIR /usr/src/app
ADD https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem .
ARG DATABASE_URL
ENV DATABASE_URL=$DATABASE_URL
COPY requirements.txt ./
RUN pip install mysql-connector-python
ADD mysql_connect.py .
CMD [ "python", "./mysql_connect.py" ]
#!/usr/bin/env python
import os
import mysql.connector
from mysql.connector.constants import ClientFlag
from urllib.parse import urlparse, unquote
# Get the database connection details from the DATABASE_URL environment variable
database_url = os.environ['DATABASE_URL']
url_parts = urlparse(database_url)
db_name = url_parts.path.lstrip('/')
db_user = unquote(url_parts.username)
db_password = unquote(url_parts.password)
db_endpoint = url_parts.hostname
db_port = url_parts.port or 3306
try:
config ={
'host': db_endpoint,
'user': db_user,
'password': db_password,
'database': db_name,
'port': db_port,
'client_flags': [ClientFlag.SSL],
'ssl_ca': 'global-bundle.pem',
'compress': True,
'ssl_verify_cert': True,
'ssl_verify_identity': True,
}
connection = mysql.connector.connect(**config)
if connection:
print("Congrats, Connected to MySQL Server over SSL!")
cursor = connection.cursor()
# cursor.execute("SELECT 'connected!'")
# record = connection.store_result()
print(connection.get_server_info())
except Exception as e:
print("Error while connecting to MySQL", e)
finally:
if connection:
cursor.close()
connection.close()
print("MySQL connection is closed")
mysql-connector-python
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment