Use the AzAPI provider to deploy Virtual Network Manager with Terraform

  • August 4, 2022

I believe most of us who works with Azure have felt the frustration of managing virtual networks as they grow in complexity. It’s easy to make mistakes when configuring peering and route tables and end up spending too much time running queries in Network Watcher to figure out what’s going on. Azure Virtual Network Manager aims to make this a lot easier and let us configure both Hub-Spoke and Mesh networks, as well as central management of security rules for all virtual networks.

As this new service is still in preview, there is no support for using the AzureRM provider in Terraform to configure it, but by using the AzAPI we can get up and running without diving into scripty shenanigans that breaks or otherwise declarative approach to infrastructure as code

Let’s start our example with defining our required providers, some basic configuration, and deploy a resource group, a hub network and two spoke networks. To save some typing (and make it a bit easier when creating a network group later on) we define the spoke networks in a local value and use for_each to create multiple networks.

terraform {
  required_providers {
    azapi = {
      source  = "azure/azapi"
      version = "= 0.4.0"
    }
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "= 3.16.0"
    }
  }
}

provider "azurerm" {
  features {}
}

data "azurerm_subscription" "current" {}

locals {
  spoke_subnets = {
    "spoke1" = {
      address_space = ["10.11.0.0/16"]
    }
    "spoke2" = {
      address_space = ["10.12.0.0/16"]
    }
  }
}

resource "azurerm_resource_group" "test" {
  name     = "NetworkManager"
  location = "westeurope"
}

resource "azurerm_virtual_network" "hub" {
  name                = "hub"
  resource_group_name = azurerm_resource_group.test.name
  location            = azurerm_resource_group.test.location
  address_space       = ["10.10.0.0/16"]

  subnet {
    name           = "GatewaySubnet"
    address_prefix = "10.10.0.0/24"
  }
}

resource "azurerm_virtual_network" "spokes" {
  for_each            = local.spoke_subnets
  name                = each.key
  resource_group_name = azurerm_resource_group.test.name
  location            = azurerm_resource_group.test.location
  address_space       = each.value.address_space
}

Deploy Network Manager

We can then proceed with the more interesting part and deploy our Azure Virtual Network Manager. A common downside to using Terraform is that everyone will run into a case where the relevant provider not yet have support for the feature you wish to utilize. As preview-features in public cloud are subjected to many changes before they eventually become production ready (or deprecated and deleted) it makes sense that third party tools don’t focus on supporting these services, but even with features that have become generally available it can be annoying waiting periods as maintainers resolve dependencies, prioritize other improvements etc. As a work-around for this issue in Azure Microsoft has released the AzAPI provider.

All azapi_resource-blocks have the same set of required and optional parameters. As a minimum we have to supply body, name, parent_id, and type:

resource "azapi_resource" "name" {
    type = "Provider/resource-type@api-version"
    name = ""
    parent_id = 
    body = 
}
  • body: JSON object that contains the request body used to create and update azure resource
  • name: Specifies the name of the azure resource
  • parent_id: The ID of the azure resource in which this resource is created. Most common is using the either azurerm_resource_group.<name>.id or to the parent azapi_resource
  • type: Reference to the resource-type and api version for the resource created

As this provider is a very thin layer on top of the Azure Resource Manager REST APIs it also means that we need to get familiar with reading the API documentation to translate the API calls into Terraform code. For most of the resources a good tip is to start with the documentation for ARM Templates & Bicep.

To deploy a Network Manager we can go to Microsoft.Network networkManagers to get the API endpoint we will use as type and the structure of the body for the API endpoint. Using the jsonencode function in Teraform is very helpful when it comes to writing human readble code:

resource "azapi_resource" "network_manager" {
  type      = "Microsoft.Network/networkManagers@2022-04-01-preview"
  name      = "networkmanager"
  parent_id = azurerm_resource_group.test.id
  location  = azurerm_resource_group.test.location

  body = jsonencode({
    properties = {
      networkManagerScopeAccesses = [
        "Connectivity",
        "SecurityAdmin"
      ]
      networkManagerScopes = {
        subscriptions = [
          data.azurerm_subscription.current.id
        ]
      }
    }
  })
}

Network Groups and Hub-Spoke configuration

We can now proceed with adding configuration to the Network Manager. To set up a Hub-Spoke architecture we will need to complete the following steps:

  1. Create a Network Group
  2. Add the spoke networks to the group
  3. Create a Hub-Spoke configuration
resource "azapi_resource" "spoke_group" {
  type      = "Microsoft.Network/networkManagers/networkGroups@2022-04-01-preview"
  name      = "spokes"
  parent_id = azapi_resource.network_manager.id

  body = jsonencode({
    properties = {
      memberType = "Static"
    }
  })
}

resource "azapi_resource" "spoke_group_members" {
  type      = "Microsoft.Network/networkManagers/networkGroups/staticMembers@2022-04-01-preview"
  for_each  = azurerm_virtual_network.spokes
  name      = each.value.name
  parent_id = azapi_resource.spoke_group.id

  body = jsonencode({
    properties = {
      resourceId = each.value.id
    }
  })
}

resource "azapi_resource" "hub_spoke_configuration" {
  type      = "Microsoft.Network/networkManagers/connectivityConfigurations@2022-04-01-preview"
  name      = "hub-spoke"
  parent_id = azapi_resource.network_manager.id

  body = jsonencode({
    properties = {
      appliesToGroups = [
        {
          groupConnectivity = "None"
          isGlobal          = "False"
          networkGroupId    = azapi_resource.spoke_group.id
          useHubGateway     = "True"
        }
      ]
      connectivityTopology  = "HubAndSpoke"
      deleteExistingPeering = "True"
      hubs = [
        {
          resourceId   = azurerm_virtual_network.hub.id
          resourceType = "Microsoft.Network/virtualNetworks"
        }
      ]
      isGlobal = "False"
    }
  })
}

Worth mentioning here is that we can define members of a network group in two ways: Either static (like in this example), or dynamic (similar to dynamic memberships in Azure AD-groups). After creating a network group and adding members we create a Hub-Spoke configuration and apply it to the network group. Omitted from this post is the creation of a virtual network gateway used for transitive routing between spokes. The complete example can be copied from GitHub Gist

Commit configuration to Network Manager

Finally we have one last (annoying) hurdle to overcome before the Network Manager is operational. After creating the Hub-Spoke configuration and assigning it to a group of virtual networks we need to deploy the configuration. The bad news is that there is no good way of doing this with the AzAPI provider. Our choices are limited to:

In any way this means we fall back to our last resort and utilize a provisioner. In my opinion the lesser of three evils here is to use the third option and not introduce preview versions of Azure CLI/Azure Powershell as dependencies. To avoid having to replace the Hub-Spoke configuration we use a null_resource so we can easily run terraform apply -replace=null_resource.network_manager_commit to trigger the provisioner again if necessary

resource "null_resource" "network_manager_commit" {
  depends_on = [
    azapi_resource.hub_spoke_configuration
  ]

  provisioner "local-exec" {
    command = <<CMD
            AccessToken=$(az account get-access-token --query accessToken --output tsv) && \
            curl -X POST https://management.azure.com${data.azurerm_subscription.current.id}/resourceGroups/${azurerm_resource_group.test.name}/providers/Microsoft.Network/networkManagers/${azapi_resource.network_manager.name}/commit?api-version=2021-02-01-preview \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $AccessToken" \
            -d '{"targetLocations": [ "${azurerm_resource_group.test.location}" ], "configurationIds": [ "${azapi_resource.hub_spoke_configuration.id}" ], "commitType": "Connectivity"}' \
            -v
        CMD
  }
}

And there you have it. An easier way to manage complex networks in Azure. There is a lot more nice functionality in Azure Virtual Network Manager to check out. Instead of creating Hub-Spoke architectures you could create a mesh, you can create security rules that are evaluated before any network security groups (so you can let developers manage their NSG’s without being paranoid about them doing stupid things like opening RDP from the internet) +++