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

使用Terraform轮换Azure存储账户访问密钥的技术咨询

存储账户密钥轮换并同步至Key Vault的Terraform实现方案

核心思路

AzureRM存储账户资源本身无内置密钥自动轮换配置,需通过azurerm_storage_account_access_key资源手动触发密钥轮换,再将新密钥同步到Key Vault作为新版本机密。


1. 定义存储账户访问密钥资源

添加该资源管理主/次密钥轮换,通过修改rotation_policy的timestamp值触发轮换操作:

# 原有存储账户资源
resource "azurerm_storage_account" "example" {
  name                     = "storageaccrotatekeys"
  resource_group_name      = "accessrotate"
  location                 = "East US"
  account_tier             = "Standard"
  account_replication_type = "LRS"
  public_network_access_enabled = false
}

# 管理主访问密钥轮换
resource "azurerm_storage_account_access_key" "primary" {
  storage_account_id = azurerm_storage_account.example.id
  key                = "primary"

  rotation_policy {
    timestamp = "2024-05-20T00:00:00Z" # 修改此时间戳触发轮换
  }
}

# 管理次访问密钥轮换
resource "azurerm_storage_account_access_key" "secondary" {
  storage_account_id = azurerm_storage_account.example.id
  key                = "secondary"

  rotation_policy {
    timestamp = "2024-05-20T00:00:00Z" # 修改此时间戳触发轮换
  }
}

2. 配置Key Vault及权限

确保Terraform服务主体拥有Key Vault的机密管理权限,同时定义Key Vault资源(若未部署):

resource "azurerm_key_vault" "example" {
  name                       = "kv-storage-rotate"
  location                   = azurerm_storage_account.example.location
  resource_group_name        = azurerm_storage_account.example.resource_group_name
  tenant_id                  = data.azurerm_client_config.current.tenant_id
  soft_delete_retention_days = 7

  sku_name = "standard"

  access_policy {
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azurerm_client_config.current.object_id

    secret_permissions = [
      "Get", "List", "Set", "Delete", "Purge", "Recover"
    ]
  }
}

# 获取当前Terraform使用的客户端配置
data "azurerm_client_config" "current" {}

3. 同步新密钥到Key Vault

将轮换后的主/次密钥自动写入Key Vault,密钥变更时自动生成新版本:

# 存储主访问密钥到Key Vault
resource "azurerm_key_vault_secret" "storage_primary_key" {
  name         = "storage-account-primary-key"
  value        = azurerm_storage_account_access_key.primary.value
  key_vault_id = azurerm_key_vault.example.id
}

# 存储次访问密钥到Key Vault
resource "azurerm_key_vault_secret" "storage_secondary_key" {
  name         = "storage-account-secondary-key"
  value        = azurerm_storage_account_access_key.secondary.value
  key_vault_id = azurerm_key_vault.example.id
}

4. 触发密钥轮换的操作

  • 修改azurerm_storage_account_access_key资源中rotation_policy的timestamp值(例如改为当前UTC时间)
  • 执行terraform apply,Terraform会调用Azure API轮换对应密钥,并自动将新密钥同步到Key Vault生成新版本机密

内容的提问来源于stack exchange,提问作者Abhishek Solanki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:33:30