快速入门:使用 AzAPI Terraform 提供程序列出Azure资源

使用 Terraform 可以定义、预览和部署云基础结构。 使用 Terraform 时,请使用 HCL 语法来创建配置文件。 HCL 语法允许你指定云提供商(如 Azure)和构成云基础结构的元素。 创建配置文件后,可以创建 一个执行计划 ,以便在部署基础结构更改之前预览这些更改。 验证更改后,应用执行计划来部署基础结构。

本文使用 azapi_resource_list 数据源列出Azure资源,并使用 JMESPath 表达式筛选结果。 创建两个存储帐户,然后使用 azapi_resource_list 列出并提取其属性。

  • 使用 AzureRM 提供程序创建资源组和两个存储帐户
  • 用于 azapi_resource_list 列出存储帐户,并使用 JMESPath 提取其名称和位置

先决条件

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

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

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

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

az account show

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

了解 response_export_values

response_export_values 属性控制从 API 响应中提取哪些属性,并使其在数据源的 output 属性中可用。 它接受列表或映射表:

  • 列表:指定要提取的 JSON 路径。 用于 ["*"] 导出完整响应正文。
  • 映射:使用 JMESPath 表达式筛选和重塑响应。 键是结果的名称,值为 JMESPath 表达式。

需要提取特定字段或转换列表响应时,首选映射窗体,因为它生成更简洁、更可用的输出值。

实现 Terraform 代码

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

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

    terraform {
      required_providers {
        azapi = {
          source  = "Azure/azapi"
          version = "~> 2.0"
        }
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~> 3.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    provider "azapi" {}
    
  3. 创建名为 variables.tf 的文件并插入下列代码:

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random value to create a unique name."
    }
    
  4. 创建名为 main.tf 的文件并插入下列代码:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "random_string" "storage_suffix" {
      length  = 8
      upper   = false
      special = false
    }
    
    resource "azurerm_resource_group" "example" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    resource "azurerm_storage_account" "example" {
      count                    = 2
      name                     = "st${random_string.storage_suffix.result}${count.index}"
      resource_group_name      = azurerm_resource_group.example.name
      location                 = azurerm_resource_group.example.location
      account_tier             = "Standard"
      account_replication_type = "LRS"
    }
    

运行 terraform init,将 Terraform 部署进行初始化。 此命令下载 Azure 提供程序,以便管理您的 Azure 资源。

terraform init -upgrade

要点:

  • 参数 -upgrade 可将必要的提供程序插件升级到符合配置版本约束的最新版本。

运行 terraform plan 以创建执行计划。

terraform plan -out main.tfplan

要点:

  • terraform plan 命令创建执行计划,但不执行它。 相反,它会确定需要执行哪些操作,以创建配置文件中指定的配置。 此模式允许你在对实际资源进行任何更改之前验证执行计划是否符合预期。
  • 使用可选 -out 参数可以为计划指定输出文件。 使用 -out 参数可以确保所查看的计划与所应用的计划完全一致。

运行 terraform apply 以将执行计划应用到您的云基础架构。

terraform apply main.tfplan

要点:

  • 示例 terraform apply 命令假设你先前运行了 terraform plan -out main.tfplan。
  • 如果为 -out 参数指定了不同的文件名,请在对 terraform apply 的调用中使用该相同文件名。
  • 如果未使用参数 -out ,则无需任何参数即可调用 terraform apply 。

使用 azapi_resource_list 列出资源

创建存储帐户后,请添加数据源以列出它们并使用 JMESPath 提取属性。

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

    data "azapi_resource_list" "storage_accounts" {
      type      = "Microsoft.Storage/storageAccounts@2023-01-01"
      parent_id = azurerm_resource_group.example.id
    
      # Use JMESPath expressions to extract specific fields from the response.
      # The API returns a list of resources in a top-level "value" array.
      response_export_values = {
        "names"     = "value[].name"
        "locations" = "value[].location"
        "skus"      = "value[].sku.name"
      }
    }
    
  2. 创建名为 outputs.tf 的文件并插入下列代码:

    output "resource_group_name" {
      value = azurerm_resource_group.example.name
    }
    
    output "storage_account_names" {
      value = data.azapi_resource_list.storage_accounts.output.names
    }
    
    output "storage_account_locations" {
      value = data.azapi_resource_list.storage_accounts.output.locations
    }
    
    output "storage_account_skus" {
      value = data.azapi_resource_list.storage_accounts.output.skus
    }
    
  3. 再次运行 terraform apply 以创建数据源并提取输出:

    terraform apply
    

关于 azapi_resource_list 的要点

  • 该 type 字段标识要列出的资源类型和 API 版本。
  • 字段 parent_id 设置范围:要列出资源组中的资源组 ID、要跨订阅列出的订阅 ID,或用于列出子资源的父资源 ID(例如,VNet 下的子网)。
  • 使用 JMESPath 表达式来操作response_export_values 的映射形式,以处理原始 API 响应。 存储帐户列表 API 返回顶级 value 数组的结果,因此表达式以 value[] 开始。

列出不同范围内的资源

确定 parent_id 列表范围。 示例:

# List all storage accounts in a subscription
data "azapi_resource_list" "all_storage" {
  type      = "Microsoft.Storage/storageAccounts@2023-01-01"
  parent_id = "/subscriptions/${var.subscription_id}"
  response_export_values = {
    "names" = "value[].name"
  }
}

# List subnets in a virtual network (child resource listing)
data "azapi_resource_list" "subnets" {
  type      = "Microsoft.Network/virtualNetworks/subnets@2023-11-01"
  parent_id = azurerm_virtual_network.example.id
  response_export_values = ["*"]
}

清理资源

如果不再需要通过 Terraform 创建的资源,请执行以下步骤:

  1. 运行 terraform plan 并指定 destroy 标志。

    terraform plan -destroy -out main.destroy.tfplan
    

    要点:

    • terraform plan 命令创建执行计划,但不执行它。 相反,它会确定需要执行哪些操作,以创建配置文件中指定的配置。 此模式允许你在对实际资源进行任何更改之前验证执行计划是否符合预期。
    • 使用可选 -out 参数可以为计划指定输出文件。 使用 -out 参数可以确保所查看的计划与所应用的计划完全一致。
  2. 运行 terraform apply 来应用执行计划。

    terraform apply main.destroy.tfplan
    

解决 Azure 上的 Terraform 问题

排查在 Azure 上使用 Terraform 时遇到的常见问题

后续步骤