Don’t Put Secrets in Code: A Beginner’s Guide to Doing It Right

Let’s be clear from the start: don’t put secrets in your code. That means no passwords in your .py files, no API keys hardcoded in your front-end, and definitely no database credentials tucked inside a GitHub repo. This is the kind of mistake that leads to security breaches, unexpected bills, and a lot of apologizing to your security team.

What Are “Secrets”?

“Secrets” are sensitive data like:

  • API keys
  • Database passwords
  • Encryption keys
  • OAuth tokens
  • Cloud access credentials

These are meant to be tightly controlled — not scattered across your source code or exposed in version control.

Why You Don’t Put Secrets in Code

  1. Security: Anyone with access to your code has access to your secrets. That includes your Git history and CI logs.
  2. Auditability: It’s hard to know who accessed what and when if secrets are just floating in the repo.
  3. Rotation: Changing secrets becomes a nightmare when you have to update every reference across multiple codebases.

So Where Do You Put Them?

You use a secrets manager — a service specifically designed to store and retrieve sensitive information securely. Here are three popular examples:

AWS Secrets Manager

AWS Secrets Manager lets you store and automatically rotate secrets like database credentials and API keys. You retrieve them programmatically like this:

import boto3

client = boto3.client('secretsmanager')
secret_value = client.get_secret_value(SecretId='prod/db-password')

That SecretId stays in your code — not the secret itself.

Azure Key Vault

Azure Key Vault allows you to store keys, secrets, and certificates in a secure way. You access secrets like this:

from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

vault_url = "https://<your-vault-name>.vault.azure.net/"
client = SecretClient(vault_url=vault_url, credential=DefaultAzureCredential())

secret = client.get_secret("MySecretName").value

Again — no secrets in code, just identifiers.

HashiCorp Vault

Vault by HashiCorp provides advanced capabilities like dynamic secrets and access policies. Here’s a simple example in Python using the HVAC client:

import hvac

client = hvac.Client(url='https://vault.example.com', token='VAULT_TOKEN')
secret = client.secrets.kv.v2.read_secret_version(path='apps/payment')['data']['data']

Even better: you can authenticate with a token or AppRole, and rotate secrets on a schedule.