The before code shows a secret hardcoded in the source, risking exposure if code leaks. The after code fetches the secret securely at runtime from Vault, avoiding hardcoding and enabling centralized secret management.
### Before: Hardcoded secret in code (bad practice)
class PaymentService:
def __init__(self):
self.api_key = "hardcoded-secret-key"
def process_payment(self):
print(f"Using API key: {self.api_key}")
### After: Fetch secret from Vault dynamically (good practice)
import hvac
class PaymentService:
def __init__(self):
client = hvac.Client(url='https://vault.example.com', token='s.VaultToken')
secret = client.secrets.kv.v2.read_secret_version(path='payment/api_key')
self.api_key = secret['data']['data']['api_key']
def process_payment(self):
print(f"Using API key: {self.api_key}")