快速入门:使用 AzAPI Terraform 提供程序部署第一个 Azure 资源操作资源

Terraform 支持云基础结构的定义、预览和部署。 使用 Terraform,可以使用 HCL 语法创建配置文件。 利用 HCL 语法,可指定 Azure 这样的云提供程序和构成云基础结构的元素。 创建配置文件后,请创建一个执行计划,利用该计划,可在部署基础结构更改之前先预览这些更改。 验证了更改后,请应用该执行计划以部署基础结构。

使用 AzAPI Terraform 提供程序将 Azure 资源作为数据源来执行只读操作。 在此示例中,你将列出 Azure 密钥保管库 Keys而不管理其生命周期。

  • 使用 AzureRM 创建密钥库和密钥
  • 请用 azapi_resource_action 列出密钥

先决条件

  • Azure 订阅:如果没有 Azure 订阅,请在开始之前创建 一个免费帐户

使用 Microsoft 帐户登录到 Azure 门户时,将使用该帐户的默认 Azure 订阅。

Terraform 使用默认 Azure 订阅中的信息自动进行身份验证。

运行 az account show 以验证当前Microsoft帐户和 Azure 订阅。

az account show

通过 Terraform 所做的任何更改都显示在显示的 Azure 订阅上。 如果这是你想要的,请跳过本文的其余部分。

实现 Terraform 代码

  1. 创建用于测试和运行示例 Terraform 代码的目录,并将其设为当前目录。

  2. 创建名为 providers.tf 的文件并插入下列代码:

    terraform {
      required_providers {
        azapi = {
          source = "Azure/azapi"
        }
      }
    }
    
    provider "azapi" {}
    
    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
    }
    
  6. 创建名为 main-generic.tf 的文件并插入下列代码:

    data "azapi_resource_action" "example" {
      type                   = "Microsoft.KeyVault/vaults@2023-07-01"
      resource_id            = azurerm_key_vault.vault.id
      action                 = "listKeys"
    }
    

初始化 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

验证结果

要点:

  • 密钥的列表会显示在terraform apply输出中。

清理资源

不再需要通过 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 时的常见问题

后续步骤