Muokkaa

Jaa


Quickstart: Create a mesh network topology with Azure Virtual Network Manager using Terraform

Get started with Azure Virtual Network Manager by using Terraform to provision connectivity for all your virtual networks.

In this quickstart, you deploy three virtual networks and use Azure Virtual Network Manager to create a mesh network topology. Then, you verify that the connectivity configuration was applied. You can choose from a deployment with a Subscription scope or a management group scope. Learn more about network manager scopes.

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

In this article, you learn how to:

Prerequisites

Implement the Terraform code

This code sample will implement Azure Virtual Network Manager at the subscription scope.

Note

The sample code for this article is located in the Azure Terraform GitHub repo. You can view the log file containing the test results from current and previous versions of Terraform.

See more articles and sample code showing how to use Terraform to manage Azure resources

  1. Create a directory in which to test and run the sample Terraform code and make it the current directory.

  2. Create a file named providers.tf and insert the following code:

    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. Create a file named main.tf and insert the following code:

    
    # 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. Create a file named variables.tf and insert the following code:

    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. Create a file named outputs.tf and insert the following code:

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

Implement the Terraform code

This code sample will implement Azure Virtual Network Manager at the management group scope.

Note

The sample code for this article is located in the Azure Terraform GitHub repo. You can view the log file containing the test results from current and previous versions of Terraform.

See more articles and sample code showing how to use Terraform to manage Azure resources

  1. Create a directory in which to test and run the sample Terraform code and make it the current directory.

  2. Create a file named providers.tf and insert the following code:

    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. Create a file named main.tf and insert the following code:

    # 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. Create a file named variables.tf and insert the following code:

    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. Create a file named outputs.tf and insert the following code:

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

Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.

terraform init -upgrade

Key points:

  • The -upgrade parameter upgrades the necessary provider plugins to the newest version that complies with the configuration's version constraints.

Create a Terraform execution plan

Run terraform plan to create an execution plan.

terraform plan -out main.tfplan

Key points:

  • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
  • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.

Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

terraform apply main.tfplan

Key points:

  • The example terraform apply command assumes you previously ran terraform plan -out main.tfplan.
  • If you specified a different filename for the -out parameter, use that same filename in the call to terraform apply.
  • If you didn't use the -out parameter, call terraform apply without any parameters.

Verify the results

  1. Get the Azure resource group name.

    resource_group_name=$(terraform output -raw resource_group_name)
    
  2. Get the virtual network names.

    terraform output virtual_network_names
    
  3. For each virtual network name printed in the previous step, run az network manager list-effective-connectivity-config to print the effective (applied) configurations. Replace the <virtual_network_name> placeholder with the vnet name.

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

Clean up resources

When you no longer need the resources created via Terraform, do the following steps:

  1. Run terraform plan and specify the destroy flag.

    terraform plan -destroy -out main.destroy.tfplan
    

    Key points:

    • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
    • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.
  2. Run terraform apply to apply the execution plan.

    terraform apply main.destroy.tfplan
    

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure

Next steps