Are you storing database usernames and passwords directly in your Python scripts? If so, this is a security practice you should stop.
Hardcoding database credentials may seem convenient, especially when developing or testing a simple script. However, once that code is shared, committed to Git, or deployed to production, those credentials can become exposed and put your databases at risk.
A common recommendation is to move passwords into environment variables. While this is generally better than keeping them directly in source code, environment variables are not a complete security solution either. Secrets stored this way may still be exposed through process environments, diagnostic tools, or application logs.
For production applications, a better approach is to use dedicated secret management services, such as Azure Key Vault, or eliminate stored database passwords altogether through passwordless authentication, such as Microsoft Entra ID with Managed Identity.
In this article, we’ll explore why hardcoding database credentials is dangerous, why environment variables have limitations, and how to implement more secure database authentication in Python applications.
Separate configuration from program logic
A good security practice is to keep configuration separate from application code. However, not all configuration values should be treated the same way.
Environment variables can be useful for non-sensitive settings, such as database server names, database names, or application environment settings.
For example:
import os
server = os.environ["SQL_SERVER"]
database = os.environ["SQL_DATABASE"]
However, storing database passwords or complete connection strings containing credentials in environment variables introduces security risks.
Although this approach keeps passwords out of your Python source code, environment variables are not a secure secret vault. Depending on the environment, their values may be exposed through process inspection, diagnostic tools, logs, or misconfigured deployment systems.
For production applications, avoid storing database passwords in environment variables when more secure alternatives are available.
Prefer passwordless authentication with Managed Identity
Whenever possible, the best approach is to avoid storing database passwords altogether.
For Python applications running on supported Azure services, Microsoft Entra ID with Managed Identity provides a secure way to authenticate to Azure SQL Database without managing traditional database passwords.
For example, using pyodbc with Microsoft ODBC Driver 18 for SQL Server:
import os
import pyodbc
server = os.environ["SQL_SERVER"]
database = os.environ["SQL_DATABASE"]
connection_string = (
"Driver={ODBC Driver 18 for SQL Server};"
f"Server=tcp:{server},1433;"
f"Database={database};"
"Authentication=ActiveDirectoryMsi;"
"Encrypt=yes;"
"TrustServerCertificate=no;"
)
with pyodbc.connect(connection_string) as connection:
cursor = connection.cursor()
cursor.execute("SELECT 1")
print(cursor.fetchone())
This example uses a system-assigned Managed Identity and assumes that the identity has already been enabled and granted the necessary database permissions.
Notice that no database username or password is stored in the Python code or connection string.
However, enabling Managed Identity alone is not enough. You must also configure the appropriate database principal and grant only the permissions the application requires.
For environments where Managed Identity is not supported, consider other suitable authentication methods, such as Windows Integrated Authentication or an approved centralized identity solution.
Use a secret manager when passwords are unavoidable
Not every application can use passwordless authentication.
If your application must use database credentials, avoid storing those credentials directly in source code, environment variables, or unprotected configuration files.
Instead, use a dedicated secret management solution, such as Azure Key Vault.
Azure Key Vault provides centralized secret storage, access controls, auditing, and support for secret rotation.
A Python application can retrieve the required credentials using the Azure Key Vault SDK, provided that it has been granted the appropriate access.
Ideally, the application should authenticate to Key Vault using Managed Identity. This avoids introducing another long-lived password simply to retrieve the database password.
Remember that using a secret manager does not eliminate the need for proper security controls. The application’s identity, permissions, logging, and handling of retrieved secrets must still be carefully managed.
Plan for credential rotation
Protecting database credentials is not just about where they are stored. It is also about how they are maintained.
If a password is compromised, it must be changed or revoked promptly. Applications must then be able to use the new credential without unnecessary disruption.
A proper rotation strategy should consider how the application retrieves updated credentials, whether secrets are cached, and when existing database connections need to be refreshed.
For applications that retrieve credentials only during startup, a restart may be necessary after rotation.
Always test the rotation process in a non-production environment and verify that the old credentials can no longer be used.
Also, remember that removing an exposed password from the latest version of your source code does not make previously exposed copies safe. The affected credential must be revoked or rotated, and potentially exposed locations should be reviewed.
Apply the principle of least privilege
Even when database credentials are securely managed, an account with excessive permissions can still introduce significant security risks.
Always follow the principle of least privilege.
Give each application or script only the database permissions it actually needs.
For example, a Python script that generates reports should not automatically have permission to modify database tables or perform administrative operations.
Whenever practical, use separate database identities for different applications and workloads.
This limits the potential impact if an application or its credentials are compromised.
Review the complete security picture
Securing Python database connections requires more than removing passwords from source code.
Review how your application handles credentials throughout their lifecycle, including development, deployment, execution, logging, monitoring, and rotation.
Pay particular attention to source control repositories, local configuration files, CI/CD pipelines, application logs, diagnostic dumps, and access permissions.
Also consider who can modify or execute the application code. Anyone with sufficient control over a privileged application may be able to access the secrets or database resources available to that application.
Where supported, prefer passwordless authentication. Where passwords remain necessary, use a dedicated secret manager and appropriate access controls.
The goal is not simply to hide database passwords. It is to reduce credential exposure, control database access, and make your Python applications more secure throughout their lifecycle.
Technical references
- OWASP: Secrets Management Cheat Sheet
- Microsoft Learn: Using Microsoft Entra ID with the ODBC Driver for SQL Server
- Microsoft Learn: Azure Key Vault Secrets Client Library for Python
- Microsoft Learn: Connect to Azure SQL Database Using Python
Continue learning
To develop your Python database-access skills through connections, queries and stored procedures, explore my course Working with Python on Windows and SQL Server Databases on Udemy. Review the curriculum and preview to see whether it fits your next learning goal.
Read Also
- How to Connect to SQL Server Databases from a Python Program
- What is Data Security and which are its Main Characteristics?
- Mastering Python & SQL Server: Best Practices
Stay connected
Subscribe to the GnoelixiAI Hub newsletter on LinkedIn for practical insights on AI, data and technology.
Watch more on YouTube: SQLNetHub TV and my personal channel.
Originally published on SQLNetHub.
© SQLNetHub
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.