🔒 Security

Vault

HashiCorp Vault

HashiCorp's secrets management tool. A centralized security solution that securely stores API keys, passwords, certificates, and more, and provides dynamic secret generation, data encryption, and fine-grained access control.

📖 Detailed Explanation

HashiCorp Vault is an open-source tool for securely storing and managing secrets. It centrally manages sensitive data such as API keys, passwords, certificates, and encryption keys, and allows secure access to them only when needed.

In modern cloud-native environments, numerous services need secrets to access databases, external APIs, and other services. Instead of hardcoding these secrets in code or configuration files, Vault manages them in a centralized, secure store and allows every access to be tracked through audit logs.

Vault Workflow

1
🔐
Authentication
(Auth)
→
2
✅
Authorization Check
(Policy)
→
3
🔑
Secret Issuance
(Secret)
→
4
📝
Audit Logging
(Audit)

Vault Architecture

Client
CLI
UI
API
Agent
Auth Methods
Token
LDAP
Kubernetes
AWS IAM
OIDC
Secret Engine
KV
Database
PKI
Transit
AWS
Storage
Consul
Integrated
File
S3
Seal
Shamir
AWS KMS
Azure Key Vault
GCP KMS

🔑 Key Features

📦

Secret Storage (KV Store)

Securely stores API keys, passwords, and the like as key-value pairs. Version control makes it possible to track change history.

🔄

Dynamic Secret Generation

Generates temporary database credentials on request. Automatic revocation after use strengthens security.

🔐

Encryption Service (Transit)

Provides an API to encrypt/decrypt data. Applications do not need to manage keys themselves.

📜

PKI Certificate Management

Operates an internal CA. Automatic issuance and renewal of TLS certificates makes it easy to implement mTLS.

👥

Fine-Grained Access Control

Policy-based permission management. Controls in fine detail who can access which secrets.

📊

Audit Log

Records all access and operations. Meets compliance requirements (SOC2, HIPAA, etc.).

Secret Management Tool Comparison

Feature HashiCorp Vault AWS Secrets Manager Azure Key Vault
Deployment Model Self-hosted / Cloud Managed (AWS only) Managed (Azure only)
Dynamic Secrets DB, AWS, GCP, Azure, etc. RDS only Limited
Multi-Cloud Fully supported AWS only Azure only
Encryption Service Transit Engine KMS separate Supported
PKI/Certificates Built-in CA ACM separate Supported
Cost OSS free / Enterprise paid Billed per secret Billed per operation

💻 Code Example

# Vault CLI 기본 사용법

# 1. Vault 서버 주소 설정
export VAULT_ADDR='https://vault.example.com:8200'

# 2. 로그인 (토큰 방식)
vault login $VAULT_TOKEN

# LDAP 로그인
vault login -method=ldap username=myuser

# 3. 비밀 저장 (KV v2)
vault kv put secret/myapp/config \
    db_host="db.example.com" \
    db_user="admin" \
    db_pass="supersecret123"

# 4. 비밀 읽기
vault kv get secret/myapp/config

# JSON 출력
vault kv get -format=json secret/myapp/config

# 특정 필드만 추출
vault kv get -field=db_pass secret/myapp/config

# 5. 동적 데이터베이스 자격증명 생성
# (사전에 database secret engine 설정 필요)
vault read database/creds/readonly

# 출력 예시:
# lease_id       database/creds/readonly/abc123
# lease_duration 1h
# username       v-token-readonly-xyz789
# password       A1b2C3d4E5f6!

# 6. Transit으로 데이터 암호화
vault write transit/encrypt/my-key \
    plaintext=$(echo "secret data" | base64)

# 7. 정책 확인
vault policy list
vault policy read myapp-policy
# Python에서 Vault 사용 (hvac 라이브러리)
import hvac
import os

# 1. Vault 클라이언트 초기화
client = hvac.Client(
    url=os.environ['VAULT_ADDR'],
    token=os.environ.get('VAULT_TOKEN')
)

# Kubernetes 인증 (Pod 내에서)
def login_with_kubernetes():
    with open('/var/run/secrets/kubernetes.io/serviceaccount/token') as f:
        jwt = f.read()

    client.auth.kubernetes.login(
        role='myapp-role',
        jwt=jwt,
        mount_point='kubernetes'
    )
    return client

# 2. 비밀 읽기 (KV v2)
def get_database_config():
    secret = client.secrets.kv.v2.read_secret_version(
        path='myapp/config',
        mount_point='secret'
    )
    return secret['data']['data']

config = get_database_config()
db_host = config['db_host']
db_pass = config['db_pass']

# 3. 동적 데이터베이스 자격증명
def get_db_credentials():
    creds = client.secrets.database.generate_credentials(
        name='readonly',
        mount_point='database'
    )
    return {
        'username': creds['data']['username'],
        'password': creds['data']['password'],
        'lease_id': creds['lease_id'],
        'lease_duration': creds['lease_duration']
    }

# 4. Transit 암호화
def encrypt_data(plaintext: str) -> str:
    import base64
    encoded = base64.b64encode(plaintext.encode()).decode()

    result = client.secrets.transit.encrypt_data(
        name='my-key',
        plaintext=encoded,
        mount_point='transit'
    )
    return result['data']['ciphertext']

def decrypt_data(ciphertext: str) -> str:
    import base64
    result = client.secrets.transit.decrypt_data(
        name='my-key',
        ciphertext=ciphertext,
        mount_point='transit'
    )
    return base64.b64decode(result['data']['plaintext']).decode()
# External Secrets Operator로 Vault 연동
# Kubernetes Secret을 Vault에서 자동 동기화

# 1. SecretStore 정의 (Vault 연결 설정)
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: vault-backend
  namespace: default
spec:
  provider:
    vault:
      server: "https://vault.example.com:8200"
      path: "secret"
      version: "v2"
      auth:
        kubernetes:
          mountPath: "kubernetes"
          role: "myapp-role"
          serviceAccountRef:
            name: "vault-auth"

---
# 2. ExternalSecret 정의 (동기화할 비밀 지정)
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: myapp-secrets
  namespace: default
spec:
  refreshInterval: "1h"  # 1시간마다 갱신
  secretStoreRef:
    name: vault-backend
    kind: SecretStore
  target:
    name: myapp-secrets  # 생성될 K8s Secret 이름
    creationPolicy: Owner
  data:
    - secretKey: DB_HOST
      remoteRef:
        key: myapp/config
        property: db_host
    - secretKey: DB_PASSWORD
      remoteRef:
        key: myapp/config
        property: db_pass

---
# 3. Pod에서 Secret 사용
apiVersion: v1
kind: Pod
metadata:
  name: myapp
spec:
  containers:
    - name: app
      image: myapp:latest
      envFrom:
        - secretRef:
            name: myapp-secrets  # 자동 동기화된 Secret

💬 Example Conversation in Practice

Junior: Our team manages DB passwords as environment variables, and it's inconvenient because we have to set them manually every time we deploy. Is there a better way?
Senior: Consider adopting Vault. You can manage secrets centrally and have applications fetch them automatically at startup. If you're on Kubernetes, you can integrate easily with External Secrets Operator.
Junior: But what if the DB password is leaked? We'd have to restart all the services to rotate it, right?
Senior: Just use Vault's dynamic secrets feature. It creates a temporary DB account on each request and automatically revokes it after use. Even if it leaks, it's invalidated after an hour, so the risk is greatly reduced.
Junior: If Vault itself gets hacked, wouldn't all the secrets be exposed?
Senior: While Vault is in the sealed (Seal) state, it cannot decrypt the encrypted data. If you manage the unseal key with Shamir key splitting or a cloud KMS, the secrets can't be read even if someone physically seizes the server.

⚠️ Cautions

⚠️ Revoke the Root Token Immediately

Be sure to revoke the Root token after the initial setup. If a token with all privileges is leaked, all secrets are exposed. For regular operations, use policy-based tokens with least privilege.

⚠️ Unseal Key Management

When using the Shamir method, store the Unseal keys securely in a distributed manner. We recommend distributing them among multiple custodians or using Auto-Unseal such as AWS KMS. If a key is lost, data cannot be recovered.

⚠️ Enable Audit Logging

Be sure to enable audit logging in production environments. Only when all access and changes are recorded can incidents be traced when a security incident occurs, and compliance requirements can also be met.

⚠️ High Availability Configuration

If Vault goes down, applications cannot access secrets. In production, be sure to configure it as an HA cluster, and apply a secret caching strategy to applications.

📋 Success Stories

🟢 A Startup's Secret Management Automation

In an environment with more than 20 microservices, secrets that had been managed through environment variables for each service were migrated to Vault + External Secrets Operator. Manual configuration at deployment disappeared, and secret rotation was also automated.

💡 Result: Deployment time reduced by 50%, secret rotation time from several hours → a few minutes

🟢 Dynamic DB Credentials at a Financial Company

To comply with PCI-DSS, the lifetime of DB credentials had to be limited to one hour. Vault's dynamic secrets feature creates temporary accounts on request and revokes them automatically, meeting audit requirements without degrading the developer experience.

💡 Result: PCI-DSS certification obtained, credential leakage risk reduced by 95%

🟢 Unified Secret Management in a Multi-Cloud Environment

In an infrastructure distributed across AWS, GCP, and on-premises, the separate use of each cloud's secret management tools was consolidated into Vault. A single policy and audit log made it possible to manage secrets consistently across all environments.

💡 Result: Management complexity reduced by 70%, unified audit reports automated

🧠 Comprehension Quiz

What is the main advantage of Vault's "Dynamic Secrets" feature?

Secrets can be stored faster
Temporary credentials are generated on request, so even if leaked, automatic expiration minimizes the risk
Secrets can be stored in multiple clouds simultaneously
Secrets can be stored without encryption

🔗 Related Terms

📚 Learning Resources