共用方式為


快速入門:使用 Terraform 建立 Azure 金鑰保存庫和金鑰

Azure Key Vault 是雲端服務,可為秘密提供安全存放區,例如密鑰、密碼和憑證。 本文著重於部署 Terraform 檔案以建立金鑰保存庫和金鑰的流程。

Terraform 可啟用雲端基礎結構的定義、預覽和部署。 使用 Terraform,您可以使用 HCL 語法建立組態檔。 HCL 語法可讓您指定雲端提供者,例如 Azure,以及構成雲端基礎結構的專案。 建立組態檔之後,您會建立一個 執行計劃 ,讓您在部署基礎結構變更之前先預覽這些變更。 驗證變更之後,您會套用執行計劃來部署基礎結構。

在本文中,您將學會如何:

先決條件

實作 Terraform 程式碼

  1. 建立目錄,在其中測試並執行範例 Terraform 程式代碼,並將其設為目前目錄。

  2. 建立名為 providers.tf 的檔案,並插入下列程序代碼:

    terraform {
      required_version = ">=1.0"
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>3.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    provider "azurerm" {
      features {}
    }
    
  3. 建立名為 main.tf 的檔案,並插入下列程序代碼:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      name     = random_pet.rg_name.id
      location = var.resource_group_location
    }
    
    data "azurerm_client_config" "current" {}
    
    resource "random_string" "azurerm_key_vault_name" {
      length  = 13
      lower   = true
      numeric = false
      special = false
      upper   = false
    }
    
    locals {
      current_user_id = coalesce(var.msi_id, data.azurerm_client_config.current.object_id)
    }
    
    resource "azurerm_key_vault" "vault" {
      name                       = coalesce(var.vault_name, "vault-${random_string.azurerm_key_vault_name.result}")
      location                   = azurerm_resource_group.rg.location
      resource_group_name        = azurerm_resource_group.rg.name
      tenant_id                  = data.azurerm_client_config.current.tenant_id
      sku_name                   = var.sku_name
      soft_delete_retention_days = 7
    
      access_policy {
        tenant_id = data.azurerm_client_config.current.tenant_id
        object_id = local.current_user_id
    
        key_permissions    = var.key_permissions
        secret_permissions = var.secret_permissions
      }
    }
    
    resource "random_string" "azurerm_key_vault_key_name" {
      length  = 13
      lower   = true
      numeric = false
      special = false
      upper   = false
    }
    
    resource "azurerm_key_vault_key" "key" {
      name = coalesce(var.key_name, "key-${random_string.azurerm_key_vault_key_name.result}")
    
      key_vault_id = azurerm_key_vault.vault.id
      key_type     = var.key_type
      key_size     = var.key_size
      key_opts     = var.key_ops
    
      rotation_policy {
        automatic {
          time_before_expiry = "P30D"
        }
    
        expire_after         = "P90D"
        notify_before_expiry = "P29D"
      }
    }
    
  4. 建立名為 variables.tf 的檔案,並插入下列程序代碼:

    variable "resource_group_location" {
      type        = string
      description = "Location for all resources."
      default     = "eastus"
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
      default     = "rg"
    }
    
    variable "vault_name" {
      type        = string
      description = "The name of the key vault to be created. The value will be randomly generated if blank."
      default     = ""
    }
    
    variable "key_name" {
      type        = string
      description = "The name of the key to be created. The value will be randomly generated if blank."
      default     = ""
    }
    
    variable "sku_name" {
      type        = string
      description = "The SKU of the vault to be created."
      default     = "standard"
      validation {
        condition     = contains(["standard", "premium"], var.sku_name)
        error_message = "The sku_name must be one of the following: standard, premium."
      }
    }
    
    variable "key_permissions" {
      type        = list(string)
      description = "List of key permissions."
      default     = ["List", "Create", "Delete", "Get", "Purge", "Recover", "Update", "GetRotationPolicy", "SetRotationPolicy"]
    }
    
    variable "secret_permissions" {
      type        = list(string)
      description = "List of secret permissions."
      default     = ["Set"]
    }
    
    variable "key_type" {
      description = "The JsonWebKeyType of the key to be created."
      default     = "RSA"
      type        = string
      validation {
        condition     = contains(["EC", "EC-HSM", "RSA", "RSA-HSM"], var.key_type)
        error_message = "The key_type must be one of the following: EC, EC-HSM, RSA, RSA-HSM."
      }
    }
    
    variable "key_ops" {
      type        = list(string)
      description = "The permitted JSON web key operations of the key to be created."
      default     = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"]
    }
    
    variable "key_size" {
      type        = number
      description = "The size in bits of the key to be created."
      default     = 2048
    }
    
    variable "msi_id" {
      type        = string
      description = "The Managed Service Identity ID. If this value isn't null (the default), 'data.azurerm_client_config.current.object_id' will be set to this value."
      default     = null
    }
    
  5. 建立名為 outputs.tf 的檔案,並插入下列程序代碼:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "azurerm_key_vault_name" {
      value = azurerm_key_vault.vault.name
    }
    
    output "azurerm_key_vault_id" {
      value = azurerm_key_vault.vault.id
    }
    

初始化 Terraform

執行 terraform init 以初始化 Terraform 部署。 此命令會下載管理 Azure 資源所需的 Azure 提供者。

terraform init -upgrade

要點:

  • -upgrade 參數會將必要的提供者外掛程式升級至符合組態版本條件約束的最新版本。

建立 Terraform 執行計劃

執行 terraform 計劃 以建立執行計劃。

terraform plan -out main.tfplan

要點:

  • terraform plan 命令會建立執行計劃,但不會執行它。 然而,它會決定哪些動作是必要的,以建立您組態檔中所指定的設定。 此模式可讓您在對實際資源進行任何變更之前,先確認執行計劃是否符合您的預期。
  • 選擇性 -out 參數可讓您指定計劃的輸出檔。 使用 -out 參數可確保您查看的計劃確切地被套用。

套用 Terraform 執行計劃

執行 terraform apply 將執行計劃套用至您的雲端基礎結構。

terraform apply main.tfplan

要點:

  • 範例 terraform apply 命令假設您先前已執行 terraform plan -out main.tfplan
  • 如果您為 -out 參數指定了不同的檔案名,請在呼叫 terraform apply時使用相同的檔案名。
  • 如果您未使用 -out 參數,請呼叫沒有任何參數的 terraform apply

確認結果

  1. 取得 Azure 金鑰保存庫名稱。

    azurerm_key_vault_name=$(terraform output -raw azurerm_key_vault_name)
    
  2. 執行 az keyvault key list 以顯示金鑰保存庫金鑰的相關信息。

    az keyvault key list --vault-name $azurerm_key_vault_name
    

清理資源

當您不再需要透過 Terraform 建立的資源時,請執行下列步驟:

  1. 執行 terraform 計劃 並指定 destroy 旗標。

    terraform plan -destroy -out main.destroy.tfplan
    

    要點:

    • terraform plan 命令會建立執行計劃,但不會執行它。 然而,它會決定哪些動作是必要的,以建立您組態檔中所指定的設定。 此模式可讓您在對實際資源進行任何變更之前,先確認執行計劃是否符合您的預期。
    • 選擇性 -out 參數可讓您指定計劃的輸出檔。 使用 -out 參數可確保您查看的計劃確切地被套用。
  2. 執行 terraform apply 以套用計畫。

    terraform apply main.destroy.tfplan
    

排除 Azure 上 Terraform 的故障

針對在 Azure 上使用 Terraform 時的常見問題進行疑難解答

後續步驟