import random import string import boto3 DATABASES = [ 'qa-art-relations' ] def get_db_type(db_name, client): """Determine database identifier from supplied name.""" response = client.describe_db_instances( Filters=[{'Name': 'db-cluster-id', 'Values': [db_name]}] ) if response['DBInstances']: db_type = 'cluster' return db_type else: # See if it is a non-cluster standalone instance response = client.describe_db_instances( Filters=[{'Name': 'db-instance-id', 'Values': [db_name]}]) if response['DBInstances']: db_type = 'standalone' return db_type else: raise 'Database not found' def generate_complex_password(): """Generate a complex random password.""" password = '' while len(password) < 20: upper = random.choice(string.ascii_uppercase) lower = random.choice(string.ascii_lowercase) num = random.choice(string.digits) symbol = random.choice('#$^()') chars = upper + lower + num + symbol password += ''.join(random.sample(chars, len(chars))) return password def main(): rds_client = boto3.client('rds') for database in DATABASES: db_type = get_db_type(database, rds_client) if db_type == 'cluster': print(f'Database {database} is a cluster') db_cluster_info = rds_client.describe_db_clusters(DBClusterIdentifier=database) db_endpoint = db_cluster_info['DBClusters'][0]['Endpoint'] master_username = db_cluster_info['DBClusters'][0]['MasterUsername'] else: print(f'Database {database} is an instance') db_instance_info = rds_client.describe_db_instances(DBInstanceIdentifier=database) db_endpoint = db_instance_info['DBInstances'][0]['Endpoint']['Address'] master_username = db_instance_info['DBInstances'][0]['MasterUsername'] new_password = generate_complex_password() if db_type == 'cluster': rds_client.modify_db_cluster( DBClusterIdentifier=database, MasterUserPassword=new_password, ApplyImmediately=True, ) else: rds_client.modify_db_instance( DBInstanceIdentifier=database, MasterUserPassword=new_password, ApplyImmediately=True, ) print(f'mysql -h {db_endpoint} -u {master_username} -p\nPassword: {new_password}\n') if __name__ == '__main__': main()