你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用 Terraform 通过 Azure Virtual Network Manager 创建网格网络拓扑

在 Terraform 中开始使用 Azure Virtual Network Manager 预配所有虚拟网络的连接。

在本快速入门中,部署三个虚拟网络,并使用 Azure Virtual Network Manager 创建网格网络拓扑。 然后验证是否应用了连接配置。 可以从具有订阅范围或管理组范围的部署中进行选择。 详细了解网络管理器范围

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

在本文中,学习如何:

先决条件

实现 Terraform 代码

此代码示例将在订阅范围内实现 Azure Virtual Network Manager。

注意

本文中的示例代码位于 Azure Terraform GitHub 存储库中。 你可以查看包含当前和以前 Terraform 版本的测试结果的日志文件。

有关更多示例,请参阅演示如何使用 Terraform 管理 Azure 资源的文章和示例代码

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

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

    terraform {
      required_version = ">=1.0"
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = ">= 3.56.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    provider "azurerm" {
      features {}
    }
    
  3. 创建名为 main.tf 的文件并插入下列代码:

    
    # Create the Resource Group
    
    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    # Create three virtual networks
    resource "random_string" "prefix" {
      length = 4
      special = false
      upper = false
    }
    
    resource "random_pet" "virtual_network_name" {
      prefix = "vnet-${random_string.prefix.result}"
    }
    resource "azurerm_virtual_network" "vnet" {
      count = 3
    
      name                = "${random_pet.virtual_network_name.id}-0${count.index}"
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      address_space       = ["10.${count.index}.0.0/16"]
    }
    
    # Add a subnet to each virtual network
    
    resource "azurerm_subnet" "subnet_vnet" {
      count = 3
    
      name                 = "default"
      virtual_network_name = azurerm_virtual_network.vnet[count.index].name
      resource_group_name  = azurerm_resource_group.rg.name
      address_prefixes     = ["10.${count.index}.0.0/24"]
    }
    
    # Create a Virtual Network Manager instance
    
    data "azurerm_subscription" "current" {
    }
    
    resource "azurerm_network_manager" "network_manager_instance" {
      name                = "network-manager"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
      scope_accesses      = ["Connectivity"]
      description         = "example network manager"
      scope {
        subscription_ids = [data.azurerm_subscription.current.id]
      }
    }
    
    # Create a network group
    
    resource "azurerm_network_manager_network_group" "network_group" {
      name               = "network-group"
      network_manager_id = azurerm_network_manager.network_manager_instance.id
    }
    
    # Add three virtual networks to a network group as dynamic members with Azure Policy
    
    resource "random_pet" "network_group_policy_name" {
      prefix = "network-group-policy"
    }
    
    resource "azurerm_policy_definition" "network_group_policy" {
      name         = "${random_pet.network_group_policy_name.id}"
      policy_type  = "Custom"
      mode         = "Microsoft.Network.Data"
      display_name = "Policy Definition for Network Group"
    
      metadata = <<METADATA
        {
          "category": "Azure Virtual Network Manager"
        }
      METADATA
    
      policy_rule = <<POLICY_RULE
        {
          "if": {
            "allOf": [
              {
                  "field": "type",
                  "equals": "Microsoft.Network/virtualNetworks"
              },
              {
                "allOf": [
                  {
                  "field": "Name",
                  "contains": "${random_pet.virtual_network_name.id}"
                  }
                ]
              }
            ]
          },
          "then": {
            "effect": "addToNetworkGroup",
            "details": {
              "networkGroupId": "${azurerm_network_manager_network_group.network_group.id}"
            }
          }
        }
      POLICY_RULE
    }
    
    resource "azurerm_subscription_policy_assignment" "azure_policy_assignment" {
      name                 = "${random_pet.network_group_policy_name.id}-policy-assignment"
      policy_definition_id = azurerm_policy_definition.network_group_policy.id
      subscription_id      = data.azurerm_subscription.current.id
    }
    
    # Create a connectivity configuration
    
    resource "azurerm_network_manager_connectivity_configuration" "connectivity_config" {
      name                  = "connectivity-config"
      network_manager_id    = azurerm_network_manager.network_manager_instance.id
      connectivity_topology = "Mesh"
      applies_to_group {
        group_connectivity = "None"
        network_group_id   = azurerm_network_manager_network_group.network_group.id
      }
    }
    
    
    # Commit deployment
    
    resource "azurerm_network_manager_deployment" "commit_deployment" {
      network_manager_id = azurerm_network_manager.network_manager_instance.id
      location           = azurerm_resource_group.rg.location
      scope_access       = "Connectivity"
      configuration_ids  = [azurerm_network_manager_connectivity_configuration.connectivity_config.id]
    }
    
  4. 创建名为 variables.tf 的文件并插入下列代码:

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    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"
    }
    
  5. 创建名为 outputs.tf 的文件并插入下列代码:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "virtual_network_names" {
      value = azurerm_virtual_network.vnet[*].name
    }
    

实现 Terraform 代码

此代码示例将在管理组范围内实现 Azure Virtual Network Manager。

注意

本文中的示例代码位于 Azure Terraform GitHub 存储库中。 你可以查看包含当前和以前 Terraform 版本的测试结果的日志文件。

有关更多示例,请参阅演示如何使用 Terraform 管理 Azure 资源的文章和示例代码

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

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

    terraform {
      required_version = ">=1.0"
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 3.56.0, < 4.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    provider "azurerm" {
      features {}
    }
    
  3. 创建名为 main.tf 的文件并插入下列代码:

    # Create the Resource Group
    
    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    # Create three virtual networks
    resource "random_string" "prefix" {
      length  = 4
      special = false
      upper   = false
    }
    
    resource "random_pet" "virtual_network_name" {
      prefix = "vnet-${random_string.prefix.result}"
    }
    resource "azurerm_virtual_network" "vnet" {
      count = 3
    
      name                = "${random_pet.virtual_network_name.id}-0${count.index}"
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      address_space       = ["10.${count.index}.0.0/16"]
    }
    
    # Add a subnet to each virtual network
    
    resource "azurerm_subnet" "subnet_vnet" {
      count = 3
    
      name                 = "default"
      virtual_network_name = azurerm_virtual_network.vnet[count.index].name
      resource_group_name  = azurerm_resource_group.rg.name
      address_prefixes     = ["10.${count.index}.0.0/24"]
    }
    
    data "azurerm_subscription" "current" {
    }
    
    # Create a Management Group
    
    resource "random_pet" "management_group_name" {
      prefix = "AVNM-management-group"
    }
    
    resource "azurerm_management_group" "mg" {
      display_name = random_pet.management_group_name.id
    
      subscription_ids = [
        data.azurerm_subscription.current.subscription_id,
      ]
    }
    
    data "azurerm_client_config" "this" {}
    
    resource "azurerm_role_assignment" "management_group_owner" {
      principal_id         = coalesce(var.msi_id, data.azurerm_client_config.this.object_id)
      scope                = azurerm_management_group.mg.id
      role_definition_name = "Contributor"
    }
    
    # register Microsoft.Network to the Management Group
    
    resource "null_resource" "register_rp_to_mg" {
      provisioner "local-exec" {
        command = "az provider register --namespace Microsoft.Network -m ${azurerm_management_group.mg.name}"
      }
      depends_on = [azurerm_role_assignment.management_group_owner]
    }
    
    resource "time_sleep" "wait_5_seconds" {
      create_duration = "5s"
      depends_on      = [null_resource.register_rp_to_mg]
    }
    
    # Create a Virtual Network Manager instance
    
    resource "azurerm_network_manager" "network_manager_instance" {
      name                = "network-manager"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
      scope_accesses      = ["Connectivity"]
      description         = "example network manager"
      scope {
        management_group_ids = [azurerm_management_group.mg.id]
      }
      depends_on = [time_sleep.wait_5_seconds]
    }
    
    # Create a network group
    
    resource "azurerm_network_manager_network_group" "network_group" {
      name               = "network-group"
      network_manager_id = azurerm_network_manager.network_manager_instance.id
    }
    
    # Add three virtual networks to a network group as dynamic members with Azure Policy
    
    resource "random_pet" "network_group_policy_name" {
      prefix = "network-group-policy"
    }
    
    resource "azurerm_policy_definition" "network_group_policy" {
      name         = random_pet.network_group_policy_name.id
      policy_type  = "Custom"
      mode         = "Microsoft.Network.Data"
      display_name = "Policy Definition for Network Group"
    
      metadata = <<METADATA
        {
          "category": "Azure Virtual Network Manager"
        }
      METADATA
    
      policy_rule = <<POLICY_RULE
        {
          "if": {
            "allOf": [
              {
                  "field": "type",
                  "equals": "Microsoft.Network/virtualNetworks"
              },
              {
                "allOf": [
                  {
                  "field": "Name",
                  "contains": "${random_pet.virtual_network_name.id}"
                  }
                ]
              }
            ]
          },
          "then": {
            "effect": "addToNetworkGroup",
            "details": {
              "networkGroupId": "${azurerm_network_manager_network_group.network_group.id}"
            }
          }
        }
      POLICY_RULE
    }
    
    resource "azurerm_subscription_policy_assignment" "azure_policy_assignment" {
      name                 = "${random_pet.network_group_policy_name.id}-policy-assignment"
      policy_definition_id = azurerm_policy_definition.network_group_policy.id
      subscription_id      = data.azurerm_subscription.current.id
    }
    
    # Create a connectivity configuration
    
    resource "azurerm_network_manager_connectivity_configuration" "connectivity_config" {
      name                  = "connectivity-config"
      network_manager_id    = azurerm_network_manager.network_manager_instance.id
      connectivity_topology = "Mesh"
      applies_to_group {
        group_connectivity = "None"
        network_group_id   = azurerm_network_manager_network_group.network_group.id
      }
    }
    
    
    # Commit deployment
    
    resource "azurerm_network_manager_deployment" "commit_deployment" {
      network_manager_id = azurerm_network_manager.network_manager_instance.id
      location           = azurerm_resource_group.rg.location
      scope_access       = "Connectivity"
      configuration_ids  = [azurerm_network_manager_connectivity_configuration.connectivity_config.id]
    }
    
  4. 创建名为 variables.tf 的文件并插入下列代码:

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    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 "msi_id" {
      type    = string
      description = "(Optional) Manage identity id that be used as authentication method. Defaults to `null`."
      default = null
    }
    
  5. 创建名为 outputs.tf 的文件并插入下列代码:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "virtual_network_names" {
      value = azurerm_virtual_network.vnet[*].name
    }
    

初始化 Terraform

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

terraform init -upgrade

要点:

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

创建 Terraform 执行计划

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

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 资源组名称。

    resource_group_name=$(terraform output -raw resource_group_name)
    
  2. 获取虚拟网络名称。

    terraform output virtual_network_names
    
  3. 对于在上一步中打印的每个虚拟网络名称,请运行 az network manager list-effective-connectivity-config 以打印有效(已应用)的配置。 将 <virtual_network_name> 占位符替换为 vnet 名称。

    az network manager list-effective-connectivity-config \
      --resource-group $resource_group_name \
      --vnet-name <virtual_network_name>
    

清理资源

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

后续步骤