DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Secrets Rotation

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Secrets Rotation

Secrets Rotation

Secrets Rotation

Secrets Rotation

Secrets Rotation

Secrets Rotation

Secrets Rotation

Secrets Rotation

Secrets Rotation

Why Rotate Secrets?

Secrets rotation limits the damage window if a credential is compromised. Regular rotation reduces the value of stolen secrets and is required by compliance frameworks.

Automated Rotation Strategies

Database Credential Rotation

import hvac

import psycopg2

class DatabaseCredentialRotator:

def init(self, vault_url, vault_token):

self.client = hvac.Client(url=vault_url, token=vault_token)

def rotate_db_credentials(self, db_name, role_name):

Generate new credentials via Vault

creds = self.client.secrets.database.generate_credentials(

mount_point="database",

name=role_name

)

Test new credentials

conn = psycopg2.connect(

host="db.example.com",

port=5432,

user=creds["data"]["username"],

password=creds["data"]["password"],

dbname=db_name

)

conn.close()

Update application configuration

self.update_app_config(db_name, creds["data"])

return creds["data"]

AWS IAM Key Rotation

import boto3

from datetime import datetime, timedelta

class IAMKeyRotator:

def init(self):

self.iam = boto3.client("iam")

def rotate_access_keys(self, username):

List existing keys

keys = self.iam.list_access_keys(UserName=username)["AccessKeyMetadata"]

Create new key

new_key = self.iam.create_access_key(UserName=username)["AccessKeyMetadata"]

Wait for propagation

time.sleep(10)

Update services with new key

self.update_services(username, new_key["AccessKeyId"], new_key["SecretAccessKey"])

Deactivate and delete old keys

for key in keys:

if key["Status"] == "Active":


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)