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: 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 in an availability set. Below the original steps you will find a corrected, current version of the gist for the azurerm 4.x provider, a safer way to handle credentials, the output to expect, and fixes for the errors you are most likely to see.


Step 1 – Install terraform

Step 2 – Copy a followng code into new directory in file called “main.tf”

Step 3 – Create IAM user and assign Service Principal Access?

Step 4 – update main.tf with following entry


  subscription_id = ""
  client_id       = ""
  client_secret   = ""
  tenant_id       = ""Code language: JavaScript (javascript)

Step 5 – Go inside a directory and run following command


$ terraform init
$ terraform plan 
$ terraform apply 
$ terraform destroy

What the example above builds

The gist creates one resource group, one virtual network and subnet, a public IP with a load balancer, and an availability set. It then uses count = 7 to create seven network interfaces, seven managed disks and seven VMs. Inside each copy, count.index (0 to 6) gives every resource a unique name, such as acctvm0 to acctvm6.

The idea is sound, but the gist will not run as published. It has a syntax error, values the current provider rejects, a retired Ubuntu image and Azure SKUs that no longer exist. The load balancer also never receives any traffic, because no NIC is added to its backend pool and it has no rule or health probe. The sections below fix all of this.

Problems in the original gist

Line in the gistProblemFix
version = "3.12.0"sThe stray s is an HCL syntax error, so terraform init failsversion = "~> 4.0"
Credentials in the provider blockSecrets end up in Git and in shared filesUse ARM_* environment variables or az login
private_ip_address_allocation = "dynamic"Since azurerm 3.0 the value is case-sensitive"Dynamic"
platform_fault_domain_count = 7Azure allows at most 2 or 3 fault domains, depending on the region2 (or 3 where the region supports it)
Public IP and load balancer without skuThe 3.x provider defaults to Basic. Azure has retired both the Basic public IP and the Basic Load Balancersku = "Standard" on both
Backend pool with no membersThe load balancer forwards no traffic to the VMsAdd NIC-to-pool associations, a probe and a rule
azurerm_virtual_machineA legacy resource that the provider no longer developsazurerm_linux_virtual_machine
UbuntuServer / 16.04-LTSUbuntu 16.04 is end of lifeUbuntu 22.04 LTS Gen2 image
computer_name = "hostname"All seven VMs get the same hostname"acctvm${count.index}"
Hard-coded admin_passwordA weak, published password, and SSH accepts password loginsSSH key authentication only
element(azurerm_network_interface.test.*.id, count.index)Legacy splat syntax that is harder to readazurerm_network_interface.test[count.index].id

Note: Step 4 above suggests adding the four credential lines to main.tf. They are already inside the gist's provider "azurerm" block, and they only work inside that block. The safer method below removes them from the file completely.

Corrected main.tf for azurerm 4.x

This version keeps the same design: a load-balanced set of Ubuntu VMs in an availability set, each with an extra 100 GB data disk. The number of VMs is a variable instead of a fixed number. A short cloud-init script installs nginx on each VM, so you can confirm through the load balancer that everything works.

terraform {
  required_version = ">= 1.5.0"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.0"
    }
  }
}

# Credentials come from ARM_* environment variables or the Azure CLI login
provider "azurerm" {
  features {}
}

variable "vm_count" {
  type    = number
  default = 3
}

variable "location" {
  type    = string
  default = "West US 2"
}

variable "admin_username" {
  type    = string
  default = "azureuser"
}

variable "ssh_public_key_path" {
  type    = string
  default = "~/.ssh/id_rsa.pub"
}

resource "azurerm_resource_group" "test" {
  name     = "acctestrg"
  location = var.location
}

resource "azurerm_virtual_network" "test" {
  name                = "acctvn"
  address_space       = ["10.0.0.0/16"]
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name
}

resource "azurerm_subnet" "test" {
  name                 = "acctsub"
  resource_group_name  = azurerm_resource_group.test.name
  virtual_network_name = azurerm_virtual_network.test.name
  address_prefixes     = ["10.0.2.0/24"]
}

# Standard SKU resources block inbound traffic unless an NSG allows it
resource "azurerm_network_security_group" "web" {
  name                = "acctnsg"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name

  security_rule {
    name                       = "allow-http"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "80"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

resource "azurerm_subnet_network_security_group_association" "test" {
  subnet_id                 = azurerm_subnet.test.id
  network_security_group_id = azurerm_network_security_group.web.id
}

resource "azurerm_public_ip" "test" {
  name                = "publicIPForLB"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name
  allocation_method   = "Static"
  sku                 = "Standard"
}

resource "azurerm_lb" "test" {
  name                = "loadBalancer"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name
  sku                 = "Standard"

  frontend_ip_configuration {
    name                 = "publicIPAddress"
    public_ip_address_id = azurerm_public_ip.test.id
  }
}

resource "azurerm_lb_backend_address_pool" "test" {
  loadbalancer_id = azurerm_lb.test.id
  name            = "BackEndAddressPool"
}

resource "azurerm_lb_probe" "http" {
  loadbalancer_id = azurerm_lb.test.id
  name            = "http-probe"
  protocol        = "Tcp"
  port            = 80
}

resource "azurerm_lb_rule" "http" {
  loadbalancer_id                = azurerm_lb.test.id
  name                           = "http"
  protocol                       = "Tcp"
  frontend_port                  = 80
  backend_port                   = 80
  frontend_ip_configuration_name = "publicIPAddress"
  backend_address_pool_ids       = [azurerm_lb_backend_address_pool.test.id]
  probe_id                       = azurerm_lb_probe.http.id
}

resource "azurerm_network_interface" "test" {
  count               = var.vm_count
  name                = "acctni${count.index}"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name

  ip_configuration {
    name                          = "testConfiguration"
    subnet_id                     = azurerm_subnet.test.id
    private_ip_address_allocation = "Dynamic"
  }
}

# Puts every NIC into the load balancer backend pool
resource "azurerm_network_interface_backend_address_pool_association" "test" {
  count                   = var.vm_count
  network_interface_id    = azurerm_network_interface.test[count.index].id
  ip_configuration_name   = "testConfiguration"
  backend_address_pool_id = azurerm_lb_backend_address_pool.test.id
}

resource "azurerm_availability_set" "avset" {
  name                         = "avset"
  location                     = azurerm_resource_group.test.location
  resource_group_name          = azurerm_resource_group.test.name
  platform_fault_domain_count  = 2
  platform_update_domain_count = 5
  managed                      = true
}

resource "azurerm_linux_virtual_machine" "test" {
  count                 = var.vm_count
  name                  = "acctvm${count.index}"
  computer_name         = "acctvm${count.index}"
  location              = azurerm_resource_group.test.location
  resource_group_name   = azurerm_resource_group.test.name
  availability_set_id   = azurerm_availability_set.avset.id
  size                  = "Standard_B2s"
  admin_username        = var.admin_username
  network_interface_ids = [azurerm_network_interface.test[count.index].id]

  disable_password_authentication = true

  admin_ssh_key {
    username   = var.admin_username
    public_key = file(pathexpand(var.ssh_public_key_path))
  }

  os_disk {
    name                 = "myosdisk${count.index}"
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-jammy"
    sku       = "22_04-lts-gen2"
    version   = "latest"
  }

  custom_data = base64encode(<<-EOF
    #cloud-config
    packages:
      - nginx
    EOF
  )

  tags = {
    environment = "staging"
  }
}

resource "azurerm_managed_disk" "test" {
  count                = var.vm_count
  name                 = "datadisk${count.index}"
  location             = azurerm_resource_group.test.location
  resource_group_name  = azurerm_resource_group.test.name
  storage_account_type = "Standard_LRS"
  create_option        = "Empty"
  disk_size_gb         = 100
}

resource "azurerm_virtual_machine_data_disk_attachment" "test" {
  count              = var.vm_count
  managed_disk_id    = azurerm_managed_disk.test[count.index].id
  virtual_machine_id = azurerm_linux_virtual_machine.test[count.index].id
  lun                = 0
  caching            = "ReadWrite"
}

output "load_balancer_ip" {
  value = azurerm_public_ip.test.ip_address
}

output "vm_private_ips" {
  value = azurerm_network_interface.test[*].private_ip_address
}Code language: PHP (php)
  • var.vm_count sets the number of VMs. Change the default, or pass -var="vm_count=7", to match the seven VMs in the original.
  • The azurerm_network_interface_backend_address_pool_association, azurerm_lb_probe and azurerm_lb_rule resources are what make the load balancer actually send traffic to the VMs.
  • With azurerm_linux_virtual_machine, you attach data disks through azurerm_virtual_machine_data_disk_attachment. Inline storage_data_disk blocks belong to the legacy resource. The original attached two data disks to each VM. To do the same, add a second disk resource and attachment with lun = 1.
  • file(pathexpand(...)) reads your local public key. pathexpand is needed because file() does not expand ~.
  • Image offers can change over time. To check what is currently available, run az vm image list --publisher Canonical --all --output table. The output is long, so filter it if you can.

Authenticate without putting secrets in main.tf

Step 3 above creates a service principal. The original heading calls this an "IAM user", but in Azure it is an app registration in Microsoft Entra ID. The service principal needs a role such as Contributor on the subscription or resource group. Rather than pasting its values into the provider block, export them as environment variables. The azurerm provider reads these automatically:

export ARM_SUBSCRIPTION_ID="<subscription-id>"
export ARM_TENANT_ID="<tenant-id>"
export ARM_CLIENT_ID="<appId of the service principal>"
export ARM_CLIENT_SECRET="<client secret>"

# Create the SSH key pair if you do not have one
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsaCode language: PHP (php)

On a workstation, you can skip the service principal entirely. Run az login, then set only ARM_SUBSCRIPTION_ID, and the provider uses your Azure CLI session. From provider version 4.0, a subscription ID is mandatory: set it either in the provider block or through ARM_SUBSCRIPTION_ID.

Note: If credentials were ever committed to a repository, rotate the client secret in Entra ID. Removing the lines from the file is not enough, because the old values stay in Git history.

Run it and check the result

  1. Run terraform init to download the azurerm 4.x provider. It should end with Terraform has been successfully initialized!
  2. Run terraform fmt and terraform validate to catch syntax mistakes before calling Azure.
  3. Run terraform plan -out=tfplan. With the default vm_count = 3, it should report Plan: 26 to add, 0 to change, 0 to destroy.
  4. Run terraform apply tfplan. Applying a saved plan does not ask for confirmation. The run ends with Apply complete! and prints the outputs.
  5. Wait a minute or two for cloud-init to install nginx. Then run curl http://$(terraform output -raw load_balancer_ip), which should return the nginx welcome page.
  6. Run terraform destroy only when you are finished. It deletes every resource in the configuration.

Note: The steps above list terraform destroy straight after apply. Run it only when you want to remove the lab, because it deletes the VMs and their disks.

The VMs have no public IPs, and the NSG opens only port 80. For SSH access, use Azure Bastion, add load balancer inbound NAT rules, or temporarily add an NSG rule for port 22 that is limited to your own IP address.

Common errors and fixes

SymptomCauseFix
terraform init fails with an invalid expression or syntax errorThe stray s after "3.12.0" in the gistRemove it and pin "~> 4.0"
Error that private_ip_address_allocation must be Dynamic or StaticLower-case dynamicUse "Dynamic"
Availability set creation fails on the fault domain countplatform_fault_domain_count is higher than the region allowsUse 2, or 3 where the region supports it
Public IP or load balancer creation is rejectedBasic SKU, which Azure has retiredSet sku = "Standard" on both
AuthorizationFailedThe service principal has no role on the subscriptionAssign the Contributor role at the right scope
Quota or SkuNotAvailable errorsNot enough vCPU quota, or the VM size is not offered in the regionLower vm_count, change size or location, or request more quota
Error saying subscription_id is requiredProvider 4.x needs a subscription IDExport ARM_SUBSCRIPTION_ID
curl times outThe NSG is not associated with the subnet, or nginx is still installingCheck the NSG association and wait for cloud-init to finish

Best practices for multi-VM Terraform code

  • Use for_each with a map or set when VMs have different roles or names. With count, removing an item from the middle of a list shifts the indexes, and Terraform then replaces VMs you did not intend to change. The Terraform loops guide compares the two approaches.
  • Pin the provider with ~> and commit .terraform.lock.hcl so every run uses the same provider version.
  • Store state in a remote backend, such as an Azure Storage account with state locking. State files can contain sensitive values.
  • For identical, autoscaling VMs, consider azurerm_linux_virtual_machine_scale_set instead of individual VMs.
  • Run terraform fmt, validate and security scanners before every commit. A pre-commit setup for Terraform automates this.

Frequently asked questions

How do I create multiple Azure VMs with Terraform?

Add count (or for_each) to the network interface and VM resources, and use count.index to give each copy a unique name. Then reference the matching NIC with azurerm_network_interface.test[count.index].id.

Should I use azurerm_virtual_machine or azurerm_linux_virtual_machine?

Use azurerm_linux_virtual_machine for new code. azurerm_virtual_machine is a legacy resource that the provider no longer develops, and it uses an older block structure.

Why does the availability set fail with platform_fault_domain_count = 7?

Azure availability sets support at most 2 or 3 fault domains, depending on the region. Update domains can go up to 20. Set the fault domain count to 2, or 3 where the region supports it.

How do I change the number of VMs without editing the code?

Make the count a variable and pass a value at run time, for example terraform apply -var="vm_count=5". When you lower the number, Terraform destroys the VMs with the highest indexes.

Where should I put the Azure service principal credentials?

Put them in the ARM_CLIENT_ID, ARM_CLIENT_SECRET, ARM_TENANT_ID and ARM_SUBSCRIPTION_ID environment variables, or in your CI system's secret store, not in main.tf. On a workstation, az login plus ARM_SUBSCRIPTION_ID is enough.

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: 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…

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 Error Handing with Try Catch

Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates…

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

Terraform Conditional Expressions and Logic: Complete Guide with Examples

Terraform Conditional Expressions and Logic โ€” Summary Table # Concept Purpose Example Creates Resources? 1 Ternary operator Choose between two values var.env == “prod” ? “t3.large” :…

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Akhil
Akhil
3 years ago

PS D:\Devops Codes> terraform plan

Planning failed. Terraform encountered an error while generating this plan.

โ•ท
โ”‚ Error: building account: getting authenticated object ID: listing Service Principals: ServicePrincipalsClient.BaseClient.Get(): clientCredentialsToken: received HTTP status 401 with response: {“error”:”invalid_client”,”error_description”:”AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID, for a secret added to app ’27cbb9f1-be27-49e8-aee0-7ac8e7032efd’.\r\nTrace ID: 28a73c19-bbc4-45e1-aae0-ead5ac800e00\r\nCorrelation ID: 46b12c2d-aabc-47da-b8fd-ba3498320195\r\nTimestamp: 2023-04-27 05:05:54Z”,”error_codes”:[7000215],”timestamp”:”2023-04-27 05:05:54Z”,”trace_id”:”28a73c19-bbc4-45e1-aae0-ead5ac800e00″,”correlation_id”:”46b12c2d-aabc-47da-b8fd-ba3498320195″,”error_uri”:”https://login.microsoftonline.com/error?code=7000215″}
โ”‚
โ”‚  with provider[“registry.terraform.io/hashicorp/azurerm”],
โ”‚  on terraform.tf line 11, in provider “azurerm”:
โ”‚  11: provider “azurerm” {
โ”‚
โ•ต
PS D:\Devops Codes> 

1
0
Would love your thoughts, please comment.x
()
x