MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform: Azure VM using virtual-machine Module

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.

InputEffect
os_flavor, windows_distribution_namePicks a predefined Windows Server 2019 Datacenter image from the module's image map
instances_count = 2Creates two identical VMs, each with its own network interface
enable_vm_availability_setSpreads the VMs across fault and update domains
enable_proximity_placement_groupPlaces the VMs physically close together for low latency
enable_public_ip_addressGives each VM a public IP
nsg_inbound_rulesCreates an NSG with the listed allow rules and associates it with every NIC
data_disksCreates managed data disks and attaches them to the VMs
enable_boot_diagnosticsTurns on boot diagnostics using a managed storage account
log_analytics_workspace_id and agent inputsConnects 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_v2 VMs.

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

  1. terraform init downloads the azurerm provider and module version 2.3.0 into .terraform/.
  2. terraform fmt and terraform validate catch syntax and argument errors before Azure is called.
  3. terraform plan -out tfplan shows the VMs, NICs, public IPs, NSG, disks, availability set and proximity placement group to be created. Check it carefully.
  4. terraform apply tfplan applies exactly the plan you reviewed. Windows VMs usually take several minutes.
  5. terraform output lists the module outputs, such as VM IDs and public IPs. The module README lists the exact output names.
  6. terraform destroy removes 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

SymptomCauseFix
Resource group, virtual network or subnet not found during planThe module reads existing network resources and does not create themCreate them first (see prerequisites) or change the names in main.tf
Log Analytics workspace not foundThe data source name or resource group doesn't matchCreate the workspace or fix name and resource_group_name
subscription ID could not be determinedazurerm 4.x requires an explicit subscriptionSet ARM_SUBSCRIPTION_ID or add subscription_id to the provider block
Unsupported argument errors inside the moduleThe provider version is newer than the one the module was written forPin azurerm to ~> 3.0, then run terraform init -upgrade
SkuNotAvailable or quota exceededThe VM size is restricted in the region, or vCPU quota has run outRun az vm list-skus --location westeurope --size Standard_A2 -o table, or request more quota
Password rejected by AzureIt doesn't meet Windows complexity rulesUse 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: publisher Microsoft.Azure.Monitor, type AzureMonitorWindowsAgent (or AzureMonitorLinuxAgent), and type_handler_version = "1.0".
  • Define what to collect in an azurerm_monitor_data_collection_rule that 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 version and 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 /32 source CIDR, and consider setting enable_public_ip_address = false.
  • Store state remotely with locking, and never commit terraform.tfstate or *.tfvars files 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Terraform: Azure VM using terraform-azurerm-compute Module

The example above uses the community Azure/compute/azurerm and Azure/network/azurerm Terraform modules to build one Linux VM and one Windows VM in Azure. Both share a virtual network…

Read More

Terraform Project โ€“ Assignment โ€“ Exercise โ€“ Lab#2: Modules

How to submit Assignment? Please submit assignment @https://www.debug.school/ and POST url share in the comments of this post. Project 1 – Create a terraform Module in which…

Read More

Terraform: Create Azure Windows VM with file, remote-exec & local-exec provisioner

This page shows how to create an Azure Windows Server VM with Terraform and run all three provisioner types on it: file copies a script to the…

Read More

Terraform: Example Code for Create Multiple Azure Linux Vms

This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the count meta-argument. The VMs sit behind a load balancer…

Read More

Terraform Tools for Developer Productivity Master Guide

Tools, Workflow, Security, Testing, CI/CD, Automation, AI Assistance, Governance, and Production Best Practices Verified baseline: 5 September 2026Audience: Terraform developers, DevOps/SRE, platform/cloud engineers, module authors, DevSecOps teams, and engineering…

Read More

AWS EKS: How to enable Auto Mode using Terraform?

Letโ€™s clarify the reality for July 2026: EKS โ€œAuto Modeโ€ vs. โ€œKarpenter Auto Computeโ€ in Terraform 1. The Real EKS Auto Mode (Serverless) 2. cluster_compute_config in terraform-aws-modules/eks…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x