Quickstart: Use Terraform to configure private DNS zones in Azure

In this quickstart, you use Terraform to create private DNS zones, network interfaces, Windows virtual machines, a private DNS A record, network security groups, and a network security rule in Azure.

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 China - 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.

  • Create an Azure resource group with a unique name.
  • Establish a virtual network with a specified name and address.
  • Set up a subnet within the created virtual network.
  • Create a private DNS zone.
  • Generate random passwords for the virtual machines.
  • Create two network interfaces.
  • Create two Windows virtual machines, and attach the network interfaces.
  • Create a private DNS A record.
  • Create a network security group and a network security rule to allow ICMP traffic.
  • Output the names and admin credentials of the virtual machines.

Prerequisites

Implement the Terraform code

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 main.tf, and insert the following code:

# Resource Group
resource "random_pet" "rg_name" {
  separator = "-"
}

resource "azurerm_resource_group" "rg" {
  location = var.resource_group_location
  name     = "${var.resource_group_name_prefix}-${random_pet.rg_name.id}"
}

# Random String for unique naming
resource "random_string" "name" {
  length  = 8
  special = false
  upper   = false
  lower   = true
  numeric = false
}

# Virtual Network
resource "azurerm_virtual_network" "vnet" {
  name                = "vnet-${random_string.name.result}"
  address_space       = var.address_space
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
}

# Subnet
resource "azurerm_subnet" "subnet" {
  name                 = "subnet-${random_string.name.result}"
  resource_group_name  = azurerm_resource_group.rg.name
  virtual_network_name = azurerm_virtual_network.vnet.name
  address_prefixes     = var.address_prefixes
}

# Private DNS Zone
resource "azurerm_private_dns_zone" "dns_zone" {
  name                = var.private_dns_zone_name
  resource_group_name = azurerm_resource_group.rg.name
}

# Private DNS Zone Virtual Network Link
resource "azurerm_private_dns_zone_virtual_network_link" "dsn_vnet_link" {
  name                  = "dns-vnet-link-${random_string.name.result}"
  resource_group_name   = azurerm_resource_group.rg.name
  private_dns_zone_name = azurerm_private_dns_zone.dns_zone.name
  virtual_network_id    = azurerm_virtual_network.vnet.id
}

# Random Passwords for VMs
resource "random_password" "vm1_admin_password" {
  length  = 16
  special = true
}

resource "random_password" "vm2_admin_password" {
  length  = 16
  special = true
}

# Network Interfaces
resource "azurerm_network_interface" "nic1" {
  name                = "nic1-${random_string.name.result}"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.subnet.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azurerm_network_interface" "nic2" {
  name                = "nic2-${random_string.name.result}"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.subnet.id
    private_ip_address_allocation = "Dynamic"
  }
}

# Windows Virtual Machines
resource "azurerm_windows_virtual_machine" "vm1" {
  name                = "vm1-${random_string.name.result}"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  size                = "Standard_F2"
  admin_username      = var.admin_username
  admin_password      = random_password.vm1_admin_password.result
  network_interface_ids = [
    azurerm_network_interface.nic1.id,
  ]

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2019-Datacenter"
    version   = "latest"
  }

  # Make idempotent
  vm_agent_platform_updates_enabled = true
}

resource "azurerm_windows_virtual_machine" "vm2" {
  name                = "vm2-${random_string.name.result}"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  size                = "Standard_F2"
  admin_username      = var.admin_username
  admin_password      = random_password.vm1_admin_password.result
  network_interface_ids = [
    azurerm_network_interface.nic2.id,
  ]

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2019-Datacenter"
    version   = "latest"
  }

  # Make idempotent
  vm_agent_platform_updates_enabled = true
}

# Private DNS A Record
resource "azurerm_private_dns_a_record" "pdar" {
  name                = "test"
  zone_name           = azurerm_private_dns_zone.dns_zone.name
  resource_group_name = azurerm_resource_group.rg.name
  ttl                 = 300
  records             = [azurerm_windows_virtual_machine.vm1.private_ip_address]
}

# Network Security Group
resource "azurerm_network_security_group" "nsg" {
  name                = "nsg-${random_string.name.result}"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
}

# Network Security Rule
resource "azurerm_network_security_rule" "nsr_icmp" {
  name                        = "Allow-ICMP"
  priority                    = 100
  direction                   = "Inbound"
  access                      = "Allow"
  protocol                    = "Icmp"
  source_port_range           = "*"
  destination_port_range      = "*"
  source_address_prefix       = "*"
  destination_address_prefix  = "*"
  resource_group_name         = azurerm_resource_group.rg.name
  network_security_group_name = azurerm_network_security_group.nsg.name
}
  1. Create a file named outputs.tf, and insert the following code:
output "resource_group_name" {
  value = azurerm_resource_group.rg.name
}

output "windows_virtual_machine_1_name" {
  value = azurerm_windows_virtual_machine.vm1.name
}

output "windows_virtual_machine_2_name" {
  value = azurerm_windows_virtual_machine.vm2.name
}

output "windows_virtual_machine_1_password" {
  value     = azurerm_windows_virtual_machine.vm1.admin_password
  sensitive = true
}

output "windows_virtual_machine_2_password" {
  value     = azurerm_windows_virtual_machine.vm2.admin_password
  sensitive = true
}

output "windows_virtual_machine_1_admin_username" {
  value     = azurerm_windows_virtual_machine.vm1.admin_username
  sensitive = true
}

output "windows_virtual_machine_2_admin_username" {
  value     = azurerm_windows_virtual_machine.vm2.admin_username
  sensitive = true
}
  1. Create a file named providers.tf, and insert the following code:
terraform {
  required_version = ">=1.0"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>3.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~>3.0"
    }
  }
}

provider "azurerm" {
  features {}
  environment = "china"
}
  1. Create a file named variables.tf, and insert the following code:
variable "resource_group_location" {
  type        = string
  default     = "chinanorth3"
  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 ID so name is unique in your Azure subscription."
}

variable "address_space" {
  type = list(string)
  default = ["10.0.0.0/16"]
  description = "The address space that is used the virtual network."
}

variable "address_prefixes" {
  type = list(string)
  default = ["10.0.2.0/24"]
  description = "The address prefixes to use for the subnet"
}

variable "private_dns_zone_name" {
  type = string
  default = "private.contoso.com"
  description = "The name of the Private DNS Zone. Must be a valid domain name. Changing this value forces a new resource to be created."
}

variable "admin_username" {
  type = string
  default = "adminuser"
  description = "The username for the Windows virtual machines."
}

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. Run az network private-dns zone list to view all DNS zones and find yours.
az network private-dns zone list --output table
  1. Run az network private-dns zone show to view the resource group associate with your DNS zone.
az network private-dns zone show --name $dnsZoneName --resource-group $resourceGroupName

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.
  1. 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.