8000 Create awsrdsmysqlp.py · techiescamp/python-for-devops@3d437a0 · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 3d437a0

Browse files
authored
Create awsrdsmysqlp.py
Created a python script to execute query on mysql RDS instance on AWS using boto3,mysql.connector and tabulate module
1 parent 4909d07 commit 3d437a0

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

awsrdsmysqlp.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import boto3
2+
import json
3+
import mysql.connector
4+
import tabulate
5+
6+
# Initialize AWS Secrets Manager client
7+
secrets_manager = boto3.client('secretsmanager')
8+
db_host = "DB_HOST"
9+
10+
def get_secretvalue():
11+
secret_name = secrets_manager.get_secret_value(SecretId='YOUR_SECRET_ARN')
12+
secret_dict = json.loads(secret_name['SecretString'])
13+
db_username = secret_dict['username']
14+
db_password = secret_dict['password']
15+
return db_username, db_password
16+
17+
def execute_query(db_name, query):
18+
db_username, db_password = get_secretvalue()
19+
20+
for db in db_name:
21+
try:
22+
connection = mysql.connector.connect(
23+
host=db_host,
24+
user=db_username,
25+
password=db_password,
26+
database=db
27+
)
28+
cursor = connection.cursor()
29+
cursor.execute(query)
30+
result = cursor.fetchall()
31+
row_count = cursor.rowcount
32+
33+
if query.upper().startswith(("SELECT", "SHOW", "DESCRIBE")):
34+
if result:
35+
header = [column_name[0] for column_name in cursor.description]
36+
table_output = [header] + list(result)
37+
print(f"Running query on: {db}")
38+
print(tabulate.tabulate(table_output, tablefmt="pipe"))
39+
else:
40+
print("Empty result")
41+
else:
42+
print(f"{row_count} rows affected in {db}")
43+
44+
except Exception as e:
45+
print("Error:", e)
46+
finally:
47+
if 'connection' in locals():
48+
connection.close()
49+
50+
db_names = input("Enter the DB names followed by space:").split()
51+
query = input("Enter the query:")
52+
execute_query(db_names, query)

0 commit comments

Comments
 (0)
0