Skip to content
BotServBotServ
Secret RotationAutomationCronn8nSecret Management

Automate Secret Rotation

Automatically rotate API keys and passwords. Scripts, cronjobs, secret managers, and workflows for local AI.

S

schutzgeist

4 min read
Automate Secret Rotation

Automating Secret Rotation

What this article covers

  • Why manual rotation doesn’t scale.
  • How to automate rotation with scripts and cron jobs.
  • How secret managers handle rotation.
  • How to trigger rotation with n8n or CI/CD workflows.
  • Common pitfalls and best practices.

Introduction

Regular rotation of API keys, tokens, and passwords is essential, but doing it manually becomes tedious fast. The more services and agents you run, the quicker rotation becomes a burden. Automation reduces mistakes, saves time, and ensures no secret outlives its intended lifespan.

This article shows how to automate secret rotation in local AI projects, whether through simple scripts, secret managers, or workflow tools.

Key concepts

  • Rotation: Replacing an old secret with a new one.
  • Automation: Regular or event-driven replacement without manual intervention.
  • Cron job: Time-scheduled task on Linux.
  • Webhook: HTTP callback that triggers actions.
  • Secret manager: Centralized secret storage and management.
  • CI/CD: Automated build and deployment pipelines.
  • Grace period: Transition window where both old and new secrets remain valid.

Why automation matters

  • Scalability: Many secrets require many steps.
  • Reliability: Deadlines are never missed.
  • Response time: Compromised credentials can be swapped instantly.
  • Consistency: The same process applies to every service.
  • Audit trail: Automatic logging of all rotations.

Scripting secret rotation

A straightforward Bash approach for Ollama API keys or tokens:

#!/bin/bash
set -e

# Configuration
SECRET_FILE="/etc/openclaw/secrets.env"
BACKUP_DIR="/backup/secrets"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Backup
mkdir -p "$BACKUP_DIR"
cp "$SECRET_FILE" "$BACKUP_DIR/secrets.env.$TIMESTAMP"

# Generate new secret
NEW_KEY=$(openssl rand -hex 32)

# Update configuration file
sed -i "s/^API_KEY=.*/API_KEY=$NEW_KEY/" "$SECRET_FILE"

# Restart service
systemctl restart openclaw

# Disable old secret after grace period
# Note: Requires provider-specific steps
echo "Rotated at $TIMESTAMP" >> /var/log/secret-rotation.log

This script backs up the file, generates a new key, updates the configuration, and restarts the service.

Cron jobs

Schedule regular rotations with a cron entry:

0 3 * * 0 /usr/local/bin/rotate-secrets.sh

This runs weekly on Sunday at 3 AM. Redirect output to a log file:

0 3 * * 0 /usr/local/bin/rotate-secrets.sh >> /var/log/secret-rotation.log 2>&1

Python automation

import secrets
import os
import shutil
import subprocess
from datetime import datetime

SECRET_FILE = "/etc/myapp/secrets.env"
BACKUP_DIR = "/backup/secrets"
SERVICE = "myapp"

def rotate_secret():
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    os.makedirs(BACKUP_DIR, exist_ok=True)
    shutil.copy(SECRET_FILE, f"{BACKUP_DIR}/secrets.env.{timestamp}")

    new_key = secrets.token_urlsafe(32)
    with open(SECRET_FILE, "w") as f:
        f.write(f"API_KEY={new_key}\n")

    subprocess.run(["systemctl", "restart", SERVICE], check=True)
    print(f"Rotated at {timestamp}")

if __name__ == "__main__":
    rotate_secret()

Secret managers with built-in rotation

  • HashiCorp Vault: Dynamic database credentials with TTL.
  • Infisical: Integrations for automatic rotation with select providers.
  • Cloud providers: AWS Secrets Manager, Azure Key Vault, and GCP Secret Manager all offer native rotation.

With secret managers, applications fetch the current secret dynamically instead of reading it from files.

Workflow automation with n8n

n8n can trigger rotation on a schedule or in response to webhooks:

  1. Trigger: Schedule or webhook on suspected breach.
  2. Generate new secret: HTTP node to provider.
  3. Update configuration: SSH node or API call.
  4. Restart service: SSH node.
  5. Disable old secret: After grace period expires.
  6. Send notification: Email or messaging service.

CI/CD integration

Define a rotation job in GitHub Actions or GitLab CI that runs on schedule or on demand:

rotate-secrets:
  schedule:
    - cron: '0 3 * * 0'
  steps:
    - name: Rotate API key
      run: ./scripts/rotate-api-key.sh

Rollback strategy

Always create a backup before rotation. If a service fails after rotation, you can quickly restore the previous version:

cp "$BACKUP_DIR/secrets.env.20260907_030000" "$SECRET_FILE"
systemctl restart openclaw

Grace period and cleanup

Keep both old and new secrets valid temporarily to avoid downtime. A cleanup step disables the old secret after a set time, preventing failures when a service still has the old secret cached.

Common pitfalls

  • No backup: Rotation errors cause outages.
  • Grace period too short: Services still load the old secret.
  • Hardcoded secrets: Applications that embed keys in code cannot be rotated.
  • No testing: Verify everything works after rotation.
  • Secrets in logs: Never write keys to log files.
  • Manual approval steps: These block full automation.

Further reading

FAQ: Automating secret rotation

Should I really automate rotation? Yes, once you have more than a handful of secrets in use.

How often should rotation happen? Weekly or monthly, depending on your risk tolerance.

Can I automate rotation without a secret manager? Yes, with scripts, cron jobs, or CI/CD, but it requires more custom work.

What happens if rotation fails? A backup and rollback step minimize downtime.

Are auto-generated passwords secure? Yes, if they’re cryptographically strong, using tools like openssl or secrets.token_urlsafe.

Sources and references

Summary

Manual secret rotation doesn’t scale. Scripts, cron jobs, secret managers, and workflows enable reliable, regular rotation. Key requirements include backups, grace periods, post-rotation testing, and clean logs free of secrets. Done right, automation significantly reduces breach risk while cutting administrative overhead.

Back to Blog
Share:

Related Posts