This tutorial uses the community kumarvna/virtual-machine/azurerm module from the Terraform Registry to deploy two Windows Server 2019 VMs into an existing Azure resource group, virtual network and subnet. The VMs get an availability set, a proximity placement group, public IPs, NSG rules, managed data disks and boot diagnostics. Below the original example you will find the prerequisites, what each part of the configuration does, a safer corrected version and fixes for common errors.
To run this example you need to execute following Terraform commands
terraform init
terraform plan
terraform apply
Run terraform destroy when you don’t need these resources.
What the example above builds
The module wraps many azurerm resources so you can describe a group of VMs in one block. Resources are created in an existing network. The module does not create the resource group, VNet or subnet. It looks them up by name, so they must already exist.
| Input | Effect |
|---|---|
os_flavor, windows_distribution_name | Picks a predefined Windows Server 2019 Datacenter image from the module's image map |
instances_count = 2 | Creates two identical VMs, each with its own network interface |
enable_vm_availability_set | Spreads the VMs across fault and update domains |
enable_proximity_placement_group | Places the VMs physically close together for low latency |
enable_public_ip_address | Gives each VM a public IP |
nsg_inbound_rules | Creates an NSG with the listed allow rules and associates it with every NIC |
data_disks | Creates managed data disks and attaches them to the VMs |
enable_boot_diagnostics | Turns on boot diagnostics using a managed storage account |
log_analytics_workspace_id and agent inputs | Connects monitoring to an existing Log Analytics workspace |
Note: Data disks come attached but are not initialised. Before Windows can use them, connect to each VM and bring them online, partition and format them in Disk Management (or with Initialize-Disk in PowerShell).
Prerequisites
- Terraform CLI installed (
terraform version). - Azure CLI installed and logged in to a subscription where you can create compute and network resources.
- An existing resource group, VNet, subnet and Log Analytics workspace whose names match the ones in
main.tf. - Enough vCPU quota in the target region for two
Standard_A2_v2VMs.
Log in and choose the subscription. azurerm provider 4.x requires a subscription ID, either as subscription_id in the provider block or in the ARM_SUBSCRIPTION_ID environment variable.
az login
az account set --subscription "<subscription-name-or-id>"
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)Code language: HTML, XML (xml)
If you are working in a lab and the shared resources don't exist yet, create them with the exact names the example expects:
az group create --name rg-shared-westeurope-01 --location westeurope
az network vnet create \
--resource-group rg-shared-westeurope-01 \
--name vnet-shared-hub-westeurope-001 \
--address-prefix 10.1.0.0/16 \
--subnet-name snet-management \
--subnet-prefix 10.1.2.0/24
az monitor log-analytics workspace create \
--resource-group rg-shared-westeurope-01 \
--workspace-name loganalytics-we-sharedtest2 \
--location westeurope
Corrected and safer main.tf
The gist works as a demo, but it hardcodes the admin password, opens RDP to the whole internet, does not pin provider versions and deploys the retired Log Analytics agent. The version below fixes those problems and keeps the same layout.
terraform {
required_version = ">= 1.3"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
# Older community modules often use arguments removed in azurerm 4.0.
# Pin to 3.x unless the module release you use supports 4.x.
version = "~> 3.0"
}
}
}
provider "azurerm" {
features {}
}
variable "admin_password" {
description = "Local administrator password for the Windows VMs"
type = string
sensitive = true
}
variable "allowed_admin_cidr" {
description = "Public CIDR allowed to reach RDP, e.g. 203.0.113.10/32"
type = string
}
data "azurerm_log_analytics_workspace" "example" {
name = "loganalytics-we-sharedtest2"
resource_group_name = "rg-shared-westeurope-01"
}
module "virtual-machine" {
source = "kumarvna/virtual-machine/azurerm"
version = "2.3.0"
resource_group_name = "rg-shared-westeurope-01"
location = "westeurope"
virtual_network_name = "vnet-shared-hub-westeurope-001"
subnet_name = "snet-management"
virtual_machine_name = "win-machine"
os_flavor = "windows"
windows_distribution_name = "windows2019dc"
virtual_machine_size = "Standard_A2_v2"
admin_username = "azureadmin"
admin_password = var.admin_password
instances_count = 2
enable_proximity_placement_group = true
enable_vm_availability_set = true
enable_public_ip_address = true
nsg_inbound_rules = [
{
name = "rdp"
destination_port_range = "3389"
source_address_prefix = var.allowed_admin_cidr
},
{
name = "http"
destination_port_range = "80"
source_address_prefix = "*"
},
]
enable_boot_diagnostics = true
data_disks = [
{
name = "disk1"
disk_size_gb = 100
storage_account_type = "StandardSSD_LRS"
},
{
name = "disk2"
disk_size_gb = 200
storage_account_type = "Standard_LRS"
}
]
log_analytics_workspace_id = data.azurerm_log_analytics_workspace.example.id
# The Log Analytics (MMA) agent was retired by Microsoft in August 2024.
# Use Azure Monitor Agent with a data collection rule instead.
deploy_log_analytics_agent = false
tags = {
ProjectName = "demo-project"
Env = "dev"
Owner = "user@example.com"
BusinessUnit = "CORP"
ServiceClass = "Gold"
}
}Code language: PHP (php)
Pass the secrets through environment variables so they never end up in Git. Use single quotes. Inside double quotes the shell expands $$ in a password such as P@$$w0rd1234! to its process ID.
export TF_VAR_admin_password='Use-A-Strong-Unique-Passw0rd!'
export TF_VAR_allowed_admin_cidr="$(curl -s https://ifconfig.me)/32"Code language: JavaScript (javascript)
Note: Marking a variable sensitive hides it in CLI output, but the value is still stored in plain text in the Terraform state. Keep state in a remote backend with restricted access, such as an Azure Storage account with RBAC.
Run the workflow and verify
terraform initdownloads the azurerm provider and module version 2.3.0 into.terraform/.terraform fmtandterraform validatecatch syntax and argument errors before Azure is called.terraform plan -out tfplanshows the VMs, NICs, public IPs, NSG, disks, availability set and proximity placement group to be created. Check it carefully.terraform apply tfplanapplies exactly the plan you reviewed. Windows VMs usually take several minutes.terraform outputlists the module outputs, such as VM IDs and public IPs. The module README lists the exact output names.terraform destroyremoves everything the configuration created. The pre-existing resource group, VNet, subnet and workspace stay, because Terraform only reads them.
terraform init
terraform fmt
terraform validate
terraform plan -out tfplan
terraform apply tfplan
# Confirm in Azure
az vm list -g rg-shared-westeurope-01 -d \
--query "[].{name:name, state:powerState, publicIp:publicIps}" -o tableCode language: CSS (css)
Connect over RDP from the allowed IP with mstsc /v:<public-ip> and log in as azureadmin.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
Resource group, virtual network or subnet not found during plan | The module reads existing network resources and does not create them | Create them first (see prerequisites) or change the names in main.tf |
Log Analytics workspace not found | The data source name or resource group doesn't match | Create the workspace or fix name and resource_group_name |
subscription ID could not be determined | azurerm 4.x requires an explicit subscription | Set ARM_SUBSCRIPTION_ID or add subscription_id to the provider block |
Unsupported argument errors inside the module | The provider version is newer than the one the module was written for | Pin azurerm to ~> 3.0, then run terraform init -upgrade |
SkuNotAvailable or quota exceeded | The VM size is restricted in the region, or vCPU quota has run out | Run az vm list-skus --location westeurope --size Standard_A2 -o table, or request more quota |
| Password rejected by Azure | It doesn't meet Windows complexity rules | Use a long password with upper case, lower case, digits and symbols |
Monitoring after the Log Analytics agent retirement
The example sets deploy_log_analytics_agent = true, which installs the Microsoft Monitoring Agent extension. Microsoft retired that agent on 31 August 2024, so new deployments should use Azure Monitor Agent (AMA). It also means you no longer need to read primary_shared_key into Terraform state.
- Install AMA with an
azurerm_virtual_machine_extension: publisherMicrosoft.Azure.Monitor, typeAzureMonitorWindowsAgent(orAzureMonitorLinuxAgent), andtype_handler_version = "1.0". - Define what to collect in an
azurerm_monitor_data_collection_rulethat sends data to your Log Analytics workspace. - Link each VM to the rule with
azurerm_monitor_data_collection_rule_association. - Alternatively, assign the built-in Azure Policy initiatives that deploy AMA at scale.
Best practices for module-based VM deployments
- Always pin the module
versionand the provider version so runs are repeatable. Read the module changelog before you upgrade. - This is a community module. Check how recently it was maintained, and read its README for supported images and inputs before you rely on it in production.
- Keep RDP and SSH closed to the internet. Use Azure Bastion, a VPN or a
/32source CIDR, and consider settingenable_public_ip_address = false. - Store state remotely with locking, and never commit
terraform.tfstateor*.tfvarsfiles that contain secrets. - Scan the configuration before you apply it. See TFSec for security scanning and pre-commit for Terraform.
- Toggle features per environment with variables and conditional expressions instead of editing the module block by hand.
Frequently asked questions
Does the kumarvna virtual-machine module create the VNet and subnet?
No. It looks up an existing resource group, virtual network and subnet by name, so they must exist before you run terraform plan.
What happens if I don't set admin_password?
The module generates a random administrator password for Windows VMs. You can read it from the module outputs, and like every output value it is stored in Terraform state.
Can I deploy Linux VMs with the same module?
Yes. Set os_flavor = "linux" and choose a Linux distribution from the module README with linux_distribution_name. Use an SSH key instead of a password.
Why does terraform destroy leave the resource group behind?
The resource group, VNet, subnet and Log Analytics workspace are only read through data sources or name lookups. Terraform never created them, so it doesn't delete them.
How do I create more or fewer VMs?
Change instances_count and run terraform plan and terraform apply again. If you lower the count, Terraform destroys the highest-numbered instances.
Related tutorials
- Terraform Tutorials: TFSec for Security Scanning
- How to Configure pre-commit for Terraform: Complete DevOps Guide with 15 Practical Use Cases, Commands, Security Checks, and Best Practices
- Terraform Conditional Expressions and Logic: Complete Guide with Examples
- More Terraform tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals