Vault

Vault Dynamic Secrets: Short-Lived Credentials for Production and Exam Prep

2026-04-19
NicheeLab Editorial Team

Dynamic Secrets are short-lived credentials that are issued on demand and automatically revoked when their TTL expires. The biggest win is that they cut both leak risk and operational overhead at the same time.

This article focuses on the concepts and operational patterns most often tested at the Vault Associate / Operations level, with CLI/API walkthroughs, comparison tables, and diagrams that make the full picture click.

1. Dynamic Secrets Basics and the Value of Short-Lived Credentials

Vault's Dynamic Secrets generate unique credentials in the backend on every request, and Vault automatically disables or deletes them once the TTL is reached. This eliminates the long-lived shared passwords that linger because nobody remembers to clean them up, minimizing the blast radius if a credential ever leaks.

The key point is that issuance and revocation are both managed under Vault's lease system. Each credential comes with a lease_id and a lease_duration, and clients can renew or explicitly revoke as needed. This also pairs well with audit logging — you can trace who used which privileges and when.

  • Main targets: Database, Cloud (AWS/Azure/GCP), PKI, SSH
  • Automatic revocation: auto-revoke on TTL expiry; explicit revoke is also supported
  • Least privilege: scoped per role, issued on demand
  • Audit-friendly: issuance, renewal, and revocation are all auditable events
AspectDynamic SecretsLong-lived static secretsManually rotated static
IssuanceOn-demand per requestPre-distributed and sharedPeriodic manual or scripted rotation
LifetimeShort-lived (TTL-managed), auto-revokedIndefinite / long-livedMedium (depends on rotation cycle)
Leak impactLimited (invalidated at expiry)Broad (persists until revoked)Depends on rotation timing
AuditabilityHigh (every issuance is traceable)Low (sharing obscures who used what)Medium (rotation logs only)
Operational costLow after initial setupHigh management load, distribution overheadRequires rotation jobs and coordination

On-demand issuance and automatic revocation flow

ClientVaultSecrets EngineTarget systemDB/Cloud1) Authenticate2) Generate3) Create temp user/token4) Short-lived credential + lease_id + TTLRevoke on TTL expiryDisable privileges/userOn-demand issuance and automatic revocation flow

Minimum configuration example (Database Secrets Engine / Postgres)

vault secrets enable database

vault write database/config/my-postgres \
  plugin_name=postgresql-database-plugin \
  allowed_roles=readonly \
  connection_url="postgresql://{{username}}:{{password}}@db.example.com:5432/postgres?sslmode=verify-full" \
  username="vault_admin" \
  password="s3cr3t"

vault write database/roles/readonly \
  db_name=my-postgres \
  creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO \"{{name}}\";" \
  default_ttl=1h \
  max_ttl=24h

# 短命クレデンシャルの取得
vault read database/creds/readonly
# 出力例: username, password, lease_id, lease_duration, renewable など

2. TTL/Lease Fundamentals: default_ttl, max_ttl, renew, revoke

Every Dynamic Secret comes with a lease_id and a lease_duration. The lease_duration is the effective TTL at issuance, and you can call lease renew when you need more time. Renewals, however, cannot exceed the role's max_ttl or the system-wide max TTL.

Renewal can fail in three situations: leases with renewable=false, extensions that would breach a ceiling, or backend-specific constraints. When the lease expires, Vault disables or deletes the credential on the target system. Token TTLs and secret TTLs are separate — whichever expires first will block further fetches or renewals.

  • Key fields: lease_id, lease_duration (seconds), renewable (true/false)
  • Ceilings: cannot exceed the role's max_ttl or the system-wide max_lease_ttl
  • Renewal: extend with vault lease renew LEASE_ID (when permitted)
  • Revocation: vault lease revoke LEASE_ID, or -prefix for bulk revocation
OperationTargetEffectCaveats
lease renewA specific lease_idExtends TTL (within allowed bounds)Fails when renewable=false or limits are exceeded
lease revokeA specific lease_idImmediate revocationConnected apps must re-fetch credentials
lease revoke -prefixAll leases under a pathBulk revocationWide blast radius — plan the rollout carefully

TTL, renewal, and revocation timeline

t0t1t2t3Issuerenew (extend)UseTTL hit → auto-revokeOn failure: consider re-fetching before expiry

Inspecting, renewing, and revoking leases

# JSON 出力で lease を確認
vault read -format=json database/creds/readonly | jq '.lease_id, .lease_duration, .renewable'

# 更新(延長)
vault lease renew <LEASE_ID>

# 即時取り消し
vault lease revoke <LEASE_ID>

# パス配下を一括取り消し
vault lease revoke -prefix database/creds/readonly

3. Cloud Dynamic Credentials (AWS/Azure/GCP): Key Points

Cloud engines issue short-lived temporary credentials, eliminating the distribution and recovery problems that come with long-lived keys. On AWS, STS-based temporary credentials are the recommended path, with IAM user generation reserved for edge cases. Azure and GCP follow the same pattern, centering on short-lived tokens and ephemeral keys.

From an exam perspective, the points most likely to be tested are: choosing the right credential_type, keeping TTL/Max TTL consistent, scoping role permissions, and understanding what revocation actually does (STS expiry, key deletion, and so on).

  • AWS: credential_type=sts is the short-lived default; iam_user tends to be long-lived
  • Azure: short-lived secrets via service principals; mind the RBAC assignment scope
  • GCP: disposable keys and access tokens; minimize privileges through roleset design
Engine / modeTypeTypical TTLRevocation mechanism
AWS STSTemporary credentials15 min – 1 hourAuto-invalid on expiry
AWS IAM UserLong-lived userFixed (until deletion)Revoke deletes the user/key
Azure (SP)Temp secret / assignmentMinutes to hoursSecret revocation / unassignment
GCP (roleset)Temp key / tokenMinutes to hoursKey revocation / deletion

Issuing temporary cloud credentials through Vault

AppVaultAWS/Azure/GCP engineCloud APIIssue STS / short-lived tokensAuto-invalid on expiry

Example: using STS with the AWS engine

vault secrets enable aws

vault write aws/config/root \
  access_key=AKIA... \
  secret_key=... \
  region=ap-northeast-1

vault write aws/roles/readonly-sts \
  credential_type=sts \
  role_arn=arn:aws:iam::123456789012:role/ReadOnlyRole \
  default_sts_ttl=900 \
  max_sts_ttl=3600

vault read aws/sts/readonly-sts  # AccessKeyId/SecretAccessKey/SessionToken と TTL を取得

4. Application Integration Patterns: Agent/Sidecar, Templates, Wrapping

You can either embed the Vault client directly in your application or deploy Vault Agent as a sidecar/daemon that writes credentials to a file. Because Dynamic Secrets are short-lived, the design around file updates plus signal-based reloads — or reconnection — is critical.

From a zero-trust angle, Response Wrapping reduces exposure of credentials and tokens along the handoff path. The exam often probes the one-time, short-lived nature of wrapping tokens and where the responsibility for unwrap lies.

  • Render environment variables / config files via Vault Agent Template
  • Renew/reload loop: refresh and reload between 1/2 and 2/3 of the TTL
  • Secure handoffs across intermediaries with Response Wrapping
Integration approachProsCaveats
Direct library integrationFine-grained controlImplementation cost; needs language support
Vault Agent (sidecar)No code required; standardizedRequires file distribution and reload control
Init + WrappingSafer initial distributionNeed unwrap procedure and expiry management

Credential delivery via an Agent sidecar

SIGHUP/filecredsAppreads /etc/secrets/db.envVault Agentsidecar / templateVaultTemplate updates /etc/secrets/db.env; SIGHUP or reconnect picks up the new short-lived credentials

Minimum Vault Agent config example (AppRole + Template)

auto_auth {
  method "approle" {
    mount_path = "auth/approle"
    config = {
      role_id_file_path = "/etc/vault/role_id"
      secret_id_file_path = "/etc/vault/secret_id"
    }
  }
  sink "file" {
    config = { path = "/etc/vault/token" }
  }
}

template {
  source      = "/etc/vault/templates/db.tpl"
  destination = "/etc/secrets/db.env"
  command     = "/usr/local/bin/reload-app"
}

vault {
  address = "https://vault.example.com:8200"
}

# db.tpl の例:
# export DB_USER="{{ with secret \"database/creds/readonly\" }}{{ .Data.username }}{{ end }}"
# export DB_PASS="{{ with secret \"database/creds/readonly\" }}{{ .Data.password }}{{ end }}"

5. Security, Audit, and Operational Control: Policies and Bulk Revocation

To enforce least privilege, grant the application token only the read paths it actually needs (e.g. database/creds/role). Administrators can use revoke -prefix to perform planned bulk revocations scoped to a blast radius. Audit logs trace every issuance, renewal, and revocation, making incident response much easier.

Common exam pitfalls include conflating token TTL with secret TTL (they are independent), misunderstanding the relationship between default_ttl and max_ttl, and the behavior of orphan tokens with respect to revoke propagation. Keep each concept cleanly separated in your head.

  • Grant only the minimum capabilities (list/read) in each policy
  • Enable audit via file/socket/sink and keep clocks synchronized
  • revoke -prefix has wide impact — run it during a maintenance window
  • default_ttl ≤ max_ttl; mismatches cause creation/update errors
Command / settingEffectExam pitfall
vault lease revoke -prefix pathBulk-revoke dynamic secrets under the pathUnderestimating the blast radius
vault audit enable fileEnable audit loggingCases where permissions or path issues block writes
Read control via policyRemoves unnecessary privilegesConfusing read capability between creds and roles/config

Lease hierarchy and bulk revocation picture

database/creds/readonly/revoke -prefix targetwriter/revoke -prefix database/creds/readonly bulk-revokes everything underneath

Least-privilege policy and enabling audit

# アプリが readonly 資格情報だけ取得可能にする例
path "database/creds/readonly" {
  capabilities = ["read"]
}

# 監査ログをファイルで有効化
vault audit enable file file_path=/var/log/vault_audit.log

6. Troubleshooting and an Associate/Ops Checklist

Common failures include role name mismatches, renewals that exceed max_ttl, insufficient backend privileges (e.g. no CREATE ROLE on the DB), and insufficient token capabilities (no read). When you see messages like lease TTL too large, permission denied, or no handler for route, suspect TTL ceilings, policy issues, and mount/path mistakes respectively.

In production, the keys to stable operation are: a connection pool refresh strategy (reconnect on rotation), a retry window for network partitions, and visibility into audit logs and metrics (issuance failure rate, renewal failure rate).

  • Check path/role/policy first: surface them via sys/mounts and list
  • For TTL mismatches, adjust the role's default_ttl/max_ttl and the system ceiling
  • Verify backend privileges (e.g. CREATE ROLE on Postgres)
  • Renew between 50–70% of the TTL; fall back to re-fetching on failure
SymptomMain causeFix
lease TTL too largeRequested TTL exceeds max_ttl or system ceilingReview the role's max_ttl and the sys-level ceiling
permission deniedToken capabilities are insufficientUpdate the policy to grant read, etc.
no handler for routeWrong path/mount or engine not enabledRe-check secrets enable and the path

Quick diagnostic flow

Error occursCheck pathCheck policyCheck role/TTLCheck backend privilegesRetry / re-fetchQuick diagnostic flow

Diagnostic command / API snippets

# マウント一覧
vault list sys/mounts

# ロール定義の確認
vault read database/roles/readonly

# API 例: 認証後に creds を取得
curl -s \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  https://vault.example.com/v1/database/creds/readonly | jq

Check Your Understanding

Associate / Ops

問題 1

A team wants to use Vault's Database Secrets Engine to make application DB access short-lived. The requirements are: 1) credentials should expire automatically, 2) operational overhead should be minimal, 3) the credential lifetime should be extended only when the workload is high within the lease window. Which design is most appropriate?

  1. Set a default_ttl on the readonly role and a sufficiently long max_ttl; run on default_ttl normally and extend with lease renew under load
  2. Create a long-lived shared user and rotate the password manually on a schedule
  3. Set the readonly role's default_ttl equal to its max_ttl and handle extensions by issuing new credentials
  4. Make the application's token TTL long and ignore the secret TTL

正解: A

Requirements 1 and 2 are satisfied by the standard Dynamic Secrets behavior. For requirement 3, lease renew lets you extend on top of default_ttl only when needed, with max_ttl giving you headroom as the ceiling. Shared users or extended token TTLs do not actually manage the secret's lifetime.

Frequently Asked Questions

What happens if a network partition prevents lease renewal?

If renewal fails, Vault automatically revokes the lease once the TTL expires. The recommended pattern is to attempt renewal well before expiration and fall back to acquiring a fresh credential on failure — a two-stage retry plus failover design.

How should a DB connection pool handle rotated credentials?

Short-lived credentials require re-authentication. Implement a gradual pool refresh (new connections use the new credentials, old connections are closed) and add an application reload hook to pick up the rotated values.

What is a reasonable TTL?

The guiding principle is least privilege and shortest lifetime. Keep the TTL as short as possible without disrupting steady-state availability, and set max_ttl as a buffer for burst extensions. Tune the trade-off between audit overhead and re-issuance cost through monitoring.

Check what you learned with practice questions

Practice with certification-focused question sets

無料で問題を解いてみる
Author

NicheeLab Editorial Team

NicheeLab editorial team focused on data engineering and cloud certification learning. Content is structured around practical study needs and official exam domains.


Related articles
Vault

Vault Core Concepts: Sealed/Unsealed, Auth, Secrets (2026)

Vault fundamentals — sealed/unsealed state, auth methods, se...

Vault

Vault Operations Professional (VOP-003): Complete Guide (2026)

Pass the Vault Operations Professional exam — enterprise pat...

Vault

Vault Path-Based Routing: API URL Structure (2026)

How Vault's path-based routing works — mount points, sub-pat...

Vault

Vault Tokens: Auth Token Mechanics (2026)

Token fundamentals — service vs. batch tokens, accessor, ren...

Vault

Vault Token Types: Service, Batch, Periodic (2026)

Service vs. batch tokens compared — performance, ACL behavio...

Browse all Vault articles (101)
© 2026 NicheeLab All rights reserved.