You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过Terraform的vault_generic_secret资源编程访问Vault密钥前一个版本?如何动态获取版本号为当前版本减1的旧密钥?

Dynamically Fetch the Previous Version of a Vault Secret in Terraform

Absolutely! You don’t have to hardcode the previous version number—you can dynamically calculate it by first pulling the current version’s metadata, then subtracting 1. Here’s a practical implementation tailored to your use case:

Step 1: Retrieve the Current Secret Version

First, fetch the latest (current) version of your secret. By omitting the version argument, Terraform automatically pulls the most recent version, and the data source exposes the version attribute which holds the current version number:

data "vault_generic_secret" "ssh_key_current" {
  path = "kv/dev/ssh/var.ssh_key_name"
}

Step 2: Fetch the Previous Version Using Dynamic Calculation

Next, reference the current version number and subtract 1 to target the immediate prior version:

data "vault_generic_secret" "ssh_key_previous_version" {
  path    = "kv/dev/ssh/var.ssh_key_name"
  version = data.vault_generic_secret.ssh_key_current.version - 1
}

Handle Edge Cases

Keep in mind that if the current version is 1, subtracting 1 will result in 0—which isn’t a valid Vault secret version. To avoid errors in this scenario, use a conditional to only create the previous version data source when the current version is greater than 1:

data "vault_generic_secret" "ssh_key_previous_version" {
  count   = data.vault_generic_secret.ssh_key_current.version > 1 ? 1 : 0
  path    = "kv/dev/ssh/var.ssh_key_name"
  version = data.vault_generic_secret.ssh_key_current.version - 1
}

When using this conditional approach, reference the secret data with an index (e.g., data.vault_generic_secret.ssh_key_previous_version[0].data) since count creates a list of resources.

Important Note

This method only works with Vault KV Version 2 engines—KV v1 doesn’t support secret versioning at all, so the version argument won’t have any effect there. Double-check that your secret path is associated with a KV v2 engine before using this setup.

内容的提问来源于stack exchange,提问作者Theo Sweeny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:22:47