Skip to content

Instantly share code, notes, and snippets.

@kave
Created January 30, 2019 18:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kave/4fcdef69ae3007148190516e1e11b48d to your computer and use it in GitHub Desktop.
Save kave/4fcdef69ae3007148190516e1e11b48d to your computer and use it in GitHub Desktop.
Python MYSQL RDS IAM Auth Example
"""
Python RDS IAM Auth Example
Requirements.txt
pip install boto3==1.9.66
pip install pymysql==0.9.3
"""
import os
import boto3
import pymysql
# rds settings
AWS_PROFILE = os.getenv('AWS_PROFILE')
AWS_REGION = os.getenv('AWS_REGION')
DB_HOST = os.getenv('DB_HOST')
DB_USER = os.getenv('DB_USER')
DB_PORT = os.getenv('DB_PORT')
DB_NAME = os.getenv('DB_NAME')
CERT_PATH = os.getenv('RDS_CERT_PATH')
client = boto3.Session(profile_name=AWS_PROFILE, region_name=AWS_REGION).client('rds')
token = client.generate_db_auth_token(DB_HOST, DB_PORT, DB_USER)
# Download cert: wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
ssl = {'ssl': {'ca': CERT_PATH}}
conn = pymysql.connect(DB_HOST, user=DB_USER, password=token, db=DB_NAME, connect_timeout=5, ssl=ssl)
print("SUCCESS: Connection to RDS mysql instance succeeded")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment