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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

19 lines
Python 3.9+
import 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

stdout
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

  1. Use environment variables for the old/new keys so the script works in CI without hardcoding secrets.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.