Rotate API keys in Python by updating an .env template
Replace an old API key with a new one inside an .env template file, with a guard for missing keys.
Python code
19 linesimport json
from pathlib import Path
def rotate_api_keys(env_template_path: Path, old_key: str, new_key: str) -> None:
"""Replace an old API key with a new one in an .env template file."""
content = env_template_path.read_text()
if old_key not in content:
print(f"Error: '{old_key}' not found in {env_template_path}")
return
updated = content.replace(old_key, new_key)
env_template_path.write_text(updated)
print(f"Rotated API key in {env_template_path.name}")
if __name__ == "__main__":
template = Path(".env.example")
if not template.exists():
template.write_text("API_KEY=old-api-key-12345\nDB_PASSWORD=secret\n")
rotate_api_keys(template, "old-api-key-12345", "new-api-key-67890")
print(template.read_text())
Output
Rotated API key in .env.example
API_KEY=new-api-key-67890
DB_PASSWORD=secret
How it works
The script reads the template file as plain text using Path.read_text, then uses str.replace to swap every occurrence of the old key for the new one. Writing back with Path.write_text persists the change. The existence check guarantees you never rotate a key that isn't present, which prevents silent mistakes. Because replace replaces all instances, rotating a key that appears multiple times in the template is handled automatically.
Common mistakes
- Assuming `Path` methods return content; you must call `.read_text()` and `.write_text()` explicitly.
- Forgetting to check if the old key exists before replacing, leading to false 'success' messages.
- Using `replace` on binary files without decoding; the template must be text (UTF-8).
Variations
- Use environment variables for the old/new keys so the script works in CI without hardcoding secrets.
- Read the template with `with open(...) as f` and `f.read()` if you prefer the built-in `open` over `pathlib`.
Real-world use cases
- Automating key rotation in a deployment pipeline to update `.env.example` before a feature release.
- Updating `.env.template` files in a monorepo when a shared API credential changes across multiple services.
- Refreshing placeholder keys in a repository template after a security audit to prevent stale secrets from being copied.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.