TL;DR
Never hardcode passwords or API keys directly into your code. Use environment variables, a secrets manager (like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault), or dedicated configuration files that are not checked into version control.
Why You Shouldn’t Hardcode Credentials
Hardcoding credentials is a major security risk:
- Exposure: If your code repository is compromised (even accidentally through public commits), attackers gain immediate access to sensitive information.
- Difficulty Changing: Updating passwords or keys requires modifying the codebase and redeploying, which is slow and error-prone.
- Compliance Issues: Many security standards prohibit storing credentials in code.
How to Store Credentials Securely
- Environment Variables
- What they are: Key-value pairs set outside of your application’s code, accessible at runtime.
- How to use them: Most programming languages provide ways to access environment variables.
# Python exampleimport os api_key = os.environ.get('MY_API_KEY') password = os.environ.get('DATABASE_PASSWORD') - Setting them: How you set environment variables depends on your operating system and deployment environment (e.g., using
exportin Linux/macOS, or setting them through a control panel in cloud providers).
- Secrets Managers
- What they are: Dedicated services for storing and managing sensitive data like passwords, API keys, and certificates. They offer features like encryption, access control, auditing, and versioning.
- Popular options: HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, Google Cloud Secret Manager.
- How to use them (example with AWS Secrets Manager):
- Store your secret in AWS Secrets Manager.
- Grant your application the necessary permissions to access the secret.
- Use the AWS SDK to retrieve the secret at runtime.
# Python example using boto3import boto3 client = boto3.client('secretsmanager') secret_name = 'my-database-credentials' response = client.get_secret_value(SecretId=secret_name) secret = json.loads(response['SecretString']) password = secret['password']
- Configuration Files (with caution)
- What they are: Separate files containing application settings, including credentials.
- Important: Never commit these files to version control! Use a
.gitignorefile to exclude them.# .gitignore exampleconfig.ini secrets.json - Encryption: If you must use configuration files, encrypt them at rest and in transit.
Best Practices
- Least Privilege: Grant your application only the minimum necessary permissions to access credentials.
- Rotation: Regularly rotate passwords and API keys. Secrets managers often automate this process.
- Auditing: Monitor access to sensitive data for suspicious activity.
- Avoid Default Credentials: Never use default usernames or passwords provided by vendors.
- Use a cyber security scanner: Regularly scan your code and infrastructure for exposed credentials.

