{"id":31286,"date":"2026-11-22T22:09:35","date_gmt":"2026-11-22T22:09:35","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=31286"},"modified":"2026-11-22T22:09:35","modified_gmt":"2026-11-22T22:09:35","slug":"terraform-example-code-for-create-multiple-azure-linux-vms","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/terraform-example-code-for-create-multiple-azure-linux-vms\/","title":{"rendered":"Terraform: Example Code for Create Multiple Azure Linux Vms"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the <code>count<\/code> 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.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1 &#8211; Install terraform<\/h2>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-devopsschool-com wp-block-embed-devopsschool-com\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"7Com2Qe5O6\"><a href=\"https:\/\/www.devopsschool.com\/blog\/terraform-install-configurations\/\">Terraform Tutorials: Installation &#038; Configurations<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; visibility: hidden;\" title=\"&#8220;Terraform Tutorials: Installation &#038; Configurations&#8221; &#8212; \" src=\"https:\/\/www.devopsschool.com\/blog\/terraform-install-configurations\/embed\/#?secret=k6Cwf00TMO#?secret=7Com2Qe5O6\" data-secret=\"7Com2Qe5O6\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2 &#8211; Copy a followng code into new directory in file called &#8220;main.tf&#8221;<\/h2>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/234668d5690733e6ac9c548910526c18.js\"><\/script>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3 &#8211; Create IAM user and assign Service Principal Access?<\/h2>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-devopsschool-com wp-block-embed-devopsschool-com\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"pfbhaotfc5\"><a href=\"https:\/\/www.devopsschool.com\/blog\/azure-how-to-create-iam-user-and-assign-service-principal-access\/\">Azure Tutorials &#8211; How to create IAM user and assign Service Principal Access?<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; visibility: hidden;\" title=\"&#8220;Azure Tutorials &#8211; How to create IAM user and assign Service Principal Access?&#8221; &#8212; \" src=\"https:\/\/www.devopsschool.com\/blog\/azure-how-to-create-iam-user-and-assign-service-principal-access\/embed\/#?secret=KY4SvHwEbD#?secret=pfbhaotfc5\" data-secret=\"pfbhaotfc5\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Step 4 &#8211; update main.tf with following entry<\/h2>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">  subscription_id = <span class=\"hljs-string\">\"\"<\/span>\r\n  client_id       = <span class=\"hljs-string\">\"\"<\/span>\r\n  client_secret   = <span class=\"hljs-string\">\"\"<\/span>\r\n  tenant_id       = <span class=\"hljs-string\">\"\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 5 &#8211; Go inside a directory and run following command<\/h2>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">$ terraform init\r\n$ terraform plan \r\n$ terraform apply \r\n$ terraform destroy<\/code><\/span><\/pre>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the example above builds<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>count = 7<\/code> to create seven network interfaces, seven managed disks and seven VMs. Inside each copy, <code>count.index<\/code> (0 to 6) gives every resource a unique name, such as <code>acctvm0<\/code> to <code>acctvm6<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Problems in the original gist<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Line in the gist<\/th><th>Problem<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>version = &quot;3.12.0&quot;s<\/code><\/td><td>The stray <code>s<\/code> is an HCL syntax error, so <code>terraform init<\/code> fails<\/td><td><code>version = &quot;~&gt; 4.0&quot;<\/code><\/td><\/tr><tr><td>Credentials in the <code>provider<\/code> block<\/td><td>Secrets end up in Git and in shared files<\/td><td>Use <code>ARM_*<\/code> environment variables or <code>az login<\/code><\/td><\/tr><tr><td><code>private_ip_address_allocation = &quot;dynamic&quot;<\/code><\/td><td>Since azurerm 3.0 the value is case-sensitive<\/td><td><code>&quot;Dynamic&quot;<\/code><\/td><\/tr><tr><td><code>platform_fault_domain_count = 7<\/code><\/td><td>Azure allows at most 2 or 3 fault domains, depending on the region<\/td><td><code>2<\/code> (or <code>3<\/code> where the region supports it)<\/td><\/tr><tr><td>Public IP and load balancer without <code>sku<\/code><\/td><td>The 3.x provider defaults to Basic. Azure has retired both the Basic public IP and the Basic Load Balancer<\/td><td><code>sku = &quot;Standard&quot;<\/code> on both<\/td><\/tr><tr><td>Backend pool with no members<\/td><td>The load balancer forwards no traffic to the VMs<\/td><td>Add NIC-to-pool associations, a probe and a rule<\/td><\/tr><tr><td><code>azurerm_virtual_machine<\/code><\/td><td>A legacy resource that the provider no longer develops<\/td><td><code>azurerm_linux_virtual_machine<\/code><\/td><\/tr><tr><td><code>UbuntuServer<\/code> \/ <code>16.04-LTS<\/code><\/td><td>Ubuntu 16.04 is end of life<\/td><td>Ubuntu 22.04 LTS Gen2 image<\/td><\/tr><tr><td><code>computer_name = &quot;hostname&quot;<\/code><\/td><td>All seven VMs get the same hostname<\/td><td><code>&quot;acctvm${count.index}&quot;<\/code><\/td><\/tr><tr><td>Hard-coded <code>admin_password<\/code><\/td><td>A weak, published password, and SSH accepts password logins<\/td><td>SSH key authentication only<\/td><\/tr><tr><td><code>element(azurerm_network_interface.test.*.id, count.index)<\/code><\/td><td>Legacy splat syntax that is harder to read<\/td><td><code>azurerm_network_interface.test[count.index].id<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Step 4 above suggests adding the four credential lines to <code>main.tf<\/code>. They are already inside the gist&#039;s <code>provider &quot;azurerm&quot;<\/code> block, and they only work inside that block. The safer method below removes them from the file completely.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected main.tf for azurerm 4.x<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">terraform {\n  required_version = <span class=\"hljs-string\">\"&gt;= 1.5.0\"<\/span>\n  required_providers {\n    azurerm = {\n      source  = <span class=\"hljs-string\">\"hashicorp\/azurerm\"<\/span>\n      version = <span class=\"hljs-string\">\"~&gt; 4.0\"<\/span>\n    }\n  }\n}\n\n<span class=\"hljs-comment\"># Credentials come from ARM_* environment variables or the Azure CLI login<\/span>\nprovider <span class=\"hljs-string\">\"azurerm\"<\/span> {\n  features {}\n}\n\nvariable <span class=\"hljs-string\">\"vm_count\"<\/span> {\n  type    = number\n  <span class=\"hljs-keyword\">default<\/span> = <span class=\"hljs-number\">3<\/span>\n}\n\nvariable <span class=\"hljs-string\">\"location\"<\/span> {\n  type    = string\n  <span class=\"hljs-keyword\">default<\/span> = <span class=\"hljs-string\">\"West US 2\"<\/span>\n}\n\nvariable <span class=\"hljs-string\">\"admin_username\"<\/span> {\n  type    = string\n  <span class=\"hljs-keyword\">default<\/span> = <span class=\"hljs-string\">\"azureuser\"<\/span>\n}\n\nvariable <span class=\"hljs-string\">\"ssh_public_key_path\"<\/span> {\n  type    = string\n  <span class=\"hljs-keyword\">default<\/span> = <span class=\"hljs-string\">\"~\/.ssh\/id_rsa.pub\"<\/span>\n}\n\nresource <span class=\"hljs-string\">\"azurerm_resource_group\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  name     = <span class=\"hljs-string\">\"acctestrg\"<\/span>\n  location = <span class=\"hljs-keyword\">var<\/span>.location\n}\n\nresource <span class=\"hljs-string\">\"azurerm_virtual_network\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  name                = <span class=\"hljs-string\">\"acctvn\"<\/span>\n  address_space       = &#91;<span class=\"hljs-string\">\"10.0.0.0\/16\"<\/span>]\n  location            = azurerm_resource_group.test.location\n  resource_group_name = azurerm_resource_group.test.name\n}\n\nresource <span class=\"hljs-string\">\"azurerm_subnet\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  name                 = <span class=\"hljs-string\">\"acctsub\"<\/span>\n  resource_group_name  = azurerm_resource_group.test.name\n  virtual_network_name = azurerm_virtual_network.test.name\n  address_prefixes     = &#91;<span class=\"hljs-string\">\"10.0.2.0\/24\"<\/span>]\n}\n\n<span class=\"hljs-comment\"># Standard SKU resources block inbound traffic unless an NSG allows it<\/span>\nresource <span class=\"hljs-string\">\"azurerm_network_security_group\"<\/span> <span class=\"hljs-string\">\"web\"<\/span> {\n  name                = <span class=\"hljs-string\">\"acctnsg\"<\/span>\n  location            = azurerm_resource_group.test.location\n  resource_group_name = azurerm_resource_group.test.name\n\n  security_rule {\n    name                       = <span class=\"hljs-string\">\"allow-http\"<\/span>\n    priority                   = <span class=\"hljs-number\">100<\/span>\n    direction                  = <span class=\"hljs-string\">\"Inbound\"<\/span>\n    access                     = <span class=\"hljs-string\">\"Allow\"<\/span>\n    protocol                   = <span class=\"hljs-string\">\"Tcp\"<\/span>\n    source_port_range          = <span class=\"hljs-string\">\"*\"<\/span>\n    destination_port_range     = <span class=\"hljs-string\">\"80\"<\/span>\n    source_address_prefix      = <span class=\"hljs-string\">\"*\"<\/span>\n    destination_address_prefix = <span class=\"hljs-string\">\"*\"<\/span>\n  }\n}\n\nresource <span class=\"hljs-string\">\"azurerm_subnet_network_security_group_association\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  subnet_id                 = azurerm_subnet.test.id\n  network_security_group_id = azurerm_network_security_group.web.id\n}\n\nresource <span class=\"hljs-string\">\"azurerm_public_ip\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  name                = <span class=\"hljs-string\">\"publicIPForLB\"<\/span>\n  location            = azurerm_resource_group.test.location\n  resource_group_name = azurerm_resource_group.test.name\n  allocation_method   = <span class=\"hljs-string\">\"Static\"<\/span>\n  sku                 = <span class=\"hljs-string\">\"Standard\"<\/span>\n}\n\nresource <span class=\"hljs-string\">\"azurerm_lb\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  name                = <span class=\"hljs-string\">\"loadBalancer\"<\/span>\n  location            = azurerm_resource_group.test.location\n  resource_group_name = azurerm_resource_group.test.name\n  sku                 = <span class=\"hljs-string\">\"Standard\"<\/span>\n\n  frontend_ip_configuration {\n    name                 = <span class=\"hljs-string\">\"publicIPAddress\"<\/span>\n    public_ip_address_id = azurerm_public_ip.test.id\n  }\n}\n\nresource <span class=\"hljs-string\">\"azurerm_lb_backend_address_pool\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  loadbalancer_id = azurerm_lb.test.id\n  name            = <span class=\"hljs-string\">\"BackEndAddressPool\"<\/span>\n}\n\nresource <span class=\"hljs-string\">\"azurerm_lb_probe\"<\/span> <span class=\"hljs-string\">\"http\"<\/span> {\n  loadbalancer_id = azurerm_lb.test.id\n  name            = <span class=\"hljs-string\">\"http-probe\"<\/span>\n  protocol        = <span class=\"hljs-string\">\"Tcp\"<\/span>\n  port            = <span class=\"hljs-number\">80<\/span>\n}\n\nresource <span class=\"hljs-string\">\"azurerm_lb_rule\"<\/span> <span class=\"hljs-string\">\"http\"<\/span> {\n  loadbalancer_id                = azurerm_lb.test.id\n  name                           = <span class=\"hljs-string\">\"http\"<\/span>\n  protocol                       = <span class=\"hljs-string\">\"Tcp\"<\/span>\n  frontend_port                  = <span class=\"hljs-number\">80<\/span>\n  backend_port                   = <span class=\"hljs-number\">80<\/span>\n  frontend_ip_configuration_name = <span class=\"hljs-string\">\"publicIPAddress\"<\/span>\n  backend_address_pool_ids       = &#91;azurerm_lb_backend_address_pool.test.id]\n  probe_id                       = azurerm_lb_probe.http.id\n}\n\nresource <span class=\"hljs-string\">\"azurerm_network_interface\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  count               = <span class=\"hljs-keyword\">var<\/span>.vm_count\n  name                = <span class=\"hljs-string\">\"acctni${count.index}\"<\/span>\n  location            = azurerm_resource_group.test.location\n  resource_group_name = azurerm_resource_group.test.name\n\n  ip_configuration {\n    name                          = <span class=\"hljs-string\">\"testConfiguration\"<\/span>\n    subnet_id                     = azurerm_subnet.test.id\n    private_ip_address_allocation = <span class=\"hljs-string\">\"Dynamic\"<\/span>\n  }\n}\n\n<span class=\"hljs-comment\"># Puts every NIC into the load balancer backend pool<\/span>\nresource <span class=\"hljs-string\">\"azurerm_network_interface_backend_address_pool_association\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  count                   = <span class=\"hljs-keyword\">var<\/span>.vm_count\n  network_interface_id    = azurerm_network_interface.test&#91;count.index].id\n  ip_configuration_name   = <span class=\"hljs-string\">\"testConfiguration\"<\/span>\n  backend_address_pool_id = azurerm_lb_backend_address_pool.test.id\n}\n\nresource <span class=\"hljs-string\">\"azurerm_availability_set\"<\/span> <span class=\"hljs-string\">\"avset\"<\/span> {\n  name                         = <span class=\"hljs-string\">\"avset\"<\/span>\n  location                     = azurerm_resource_group.test.location\n  resource_group_name          = azurerm_resource_group.test.name\n  platform_fault_domain_count  = <span class=\"hljs-number\">2<\/span>\n  platform_update_domain_count = <span class=\"hljs-number\">5<\/span>\n  managed                      = <span class=\"hljs-keyword\">true<\/span>\n}\n\nresource <span class=\"hljs-string\">\"azurerm_linux_virtual_machine\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  count                 = <span class=\"hljs-keyword\">var<\/span>.vm_count\n  name                  = <span class=\"hljs-string\">\"acctvm${count.index}\"<\/span>\n  computer_name         = <span class=\"hljs-string\">\"acctvm${count.index}\"<\/span>\n  location              = azurerm_resource_group.test.location\n  resource_group_name   = azurerm_resource_group.test.name\n  availability_set_id   = azurerm_availability_set.avset.id\n  size                  = <span class=\"hljs-string\">\"Standard_B2s\"<\/span>\n  admin_username        = <span class=\"hljs-keyword\">var<\/span>.admin_username\n  network_interface_ids = &#91;azurerm_network_interface.test&#91;count.index].id]\n\n  disable_password_authentication = <span class=\"hljs-keyword\">true<\/span>\n\n  admin_ssh_key {\n    username   = <span class=\"hljs-keyword\">var<\/span>.admin_username\n    public_key = file(pathexpand(<span class=\"hljs-keyword\">var<\/span>.ssh_public_key_path))\n  }\n\n  os_disk {\n    name                 = <span class=\"hljs-string\">\"myosdisk${count.index}\"<\/span>\n    caching              = <span class=\"hljs-string\">\"ReadWrite\"<\/span>\n    storage_account_type = <span class=\"hljs-string\">\"Standard_LRS\"<\/span>\n  }\n\n  source_image_reference {\n    publisher = <span class=\"hljs-string\">\"Canonical\"<\/span>\n    offer     = <span class=\"hljs-string\">\"0001-com-ubuntu-server-jammy\"<\/span>\n    sku       = <span class=\"hljs-string\">\"22_04-lts-gen2\"<\/span>\n    version   = <span class=\"hljs-string\">\"latest\"<\/span>\n  }\n\n  custom_data = base64encode(&lt;&lt;-EOF\n    <span class=\"hljs-comment\">#cloud-config<\/span>\n    packages:\n      - nginx\n    EOF\n  )\n\n  tags = {\n    environment = <span class=\"hljs-string\">\"staging\"<\/span>\n  }\n}\n\nresource <span class=\"hljs-string\">\"azurerm_managed_disk\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  count                = <span class=\"hljs-keyword\">var<\/span>.vm_count\n  name                 = <span class=\"hljs-string\">\"datadisk${count.index}\"<\/span>\n  location             = azurerm_resource_group.test.location\n  resource_group_name  = azurerm_resource_group.test.name\n  storage_account_type = <span class=\"hljs-string\">\"Standard_LRS\"<\/span>\n  create_option        = <span class=\"hljs-string\">\"Empty\"<\/span>\n  disk_size_gb         = <span class=\"hljs-number\">100<\/span>\n}\n\nresource <span class=\"hljs-string\">\"azurerm_virtual_machine_data_disk_attachment\"<\/span> <span class=\"hljs-string\">\"test\"<\/span> {\n  count              = <span class=\"hljs-keyword\">var<\/span>.vm_count\n  managed_disk_id    = azurerm_managed_disk.test&#91;count.index].id\n  virtual_machine_id = azurerm_linux_virtual_machine.test&#91;count.index].id\n  lun                = <span class=\"hljs-number\">0<\/span>\n  caching            = <span class=\"hljs-string\">\"ReadWrite\"<\/span>\n}\n\noutput <span class=\"hljs-string\">\"load_balancer_ip\"<\/span> {\n  value = azurerm_public_ip.test.ip_address\n}\n\noutput <span class=\"hljs-string\">\"vm_private_ips\"<\/span> {\n  value = azurerm_network_interface.test&#91;*].private_ip_address\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>var.vm_count<\/code> sets the number of VMs. Change the default, or pass <code>-var=&quot;vm_count=7&quot;<\/code>, to match the seven VMs in the original.<\/li>\n\n\n<li>The <code>azurerm_network_interface_backend_address_pool_association<\/code>, <code>azurerm_lb_probe<\/code> and <code>azurerm_lb_rule<\/code> resources are what make the load balancer actually send traffic to the VMs.<\/li>\n\n\n<li>With <code>azurerm_linux_virtual_machine<\/code>, you attach data disks through <code>azurerm_virtual_machine_data_disk_attachment<\/code>. Inline <code>storage_data_disk<\/code> 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 <code>lun = 1<\/code>.<\/li>\n\n\n<li><code>file(pathexpand(...))<\/code> reads your local public key. <code>pathexpand<\/code> is needed because <code>file()<\/code> does not expand <code>~<\/code>.<\/li>\n\n\n<li>Image offers can change over time. To check what is currently available, run <code>az vm image list --publisher Canonical --all --output table<\/code>. The output is long, so filter it if you can.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Authenticate without putting secrets in main.tf<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Step 3 above creates a service principal. The original heading calls this an &quot;IAM user&quot;, but in Azure it is an app registration in Microsoft Entra ID. The service principal needs a role such as <strong>Contributor<\/strong> 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:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">export ARM_SUBSCRIPTION_ID=<span class=\"hljs-string\">\"&lt;subscription-id&gt;\"<\/span>\nexport ARM_TENANT_ID=<span class=\"hljs-string\">\"&lt;tenant-id&gt;\"<\/span>\nexport ARM_CLIENT_ID=<span class=\"hljs-string\">\"&lt;appId of the service principal&gt;\"<\/span>\nexport ARM_CLIENT_SECRET=<span class=\"hljs-string\">\"&lt;client secret&gt;\"<\/span>\n\n<span class=\"hljs-comment\"># Create the SSH key pair if you do not have one<\/span>\nssh-keygen -t rsa -b <span class=\"hljs-number\">4096<\/span> -f ~\/.ssh\/id_rsa<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">On a workstation, you can skip the service principal entirely. Run <code>az login<\/code>, then set only <code>ARM_SUBSCRIPTION_ID<\/code>, 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 <code>ARM_SUBSCRIPTION_ID<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Run it and check the result<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Run <code>terraform init<\/code> to download the azurerm 4.x provider. It should end with <code>Terraform has been successfully initialized!<\/code><\/li>\n\n\n<li>Run <code>terraform fmt<\/code> and <code>terraform validate<\/code> to catch syntax mistakes before calling Azure.<\/li>\n\n\n<li>Run <code>terraform plan -out=tfplan<\/code>. With the default <code>vm_count = 3<\/code>, it should report <code>Plan: 26 to add, 0 to change, 0 to destroy.<\/code><\/li>\n\n\n<li>Run <code>terraform apply tfplan<\/code>. Applying a saved plan does not ask for confirmation. The run ends with <code>Apply complete!<\/code> and prints the outputs.<\/li>\n\n\n<li>Wait a minute or two for cloud-init to install nginx. Then run <code>curl http:\/\/$(terraform output -raw load_balancer_ip)<\/code>, which should return the nginx welcome page.<\/li>\n\n\n<li>Run <code>terraform destroy<\/code> only when you are finished. It deletes every resource in the configuration.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The steps above list <code>terraform destroy<\/code> straight after <code>apply<\/code>. Run it only when you want to remove the lab, because it deletes the VMs and their disks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>terraform init<\/code> fails with an invalid expression or syntax error<\/td><td>The stray <code>s<\/code> after <code>&quot;3.12.0&quot;<\/code> in the gist<\/td><td>Remove it and pin <code>&quot;~&gt; 4.0&quot;<\/code><\/td><\/tr><tr><td>Error that <code>private_ip_address_allocation<\/code> must be <code>Dynamic<\/code> or <code>Static<\/code><\/td><td>Lower-case <code>dynamic<\/code><\/td><td>Use <code>&quot;Dynamic&quot;<\/code><\/td><\/tr><tr><td>Availability set creation fails on the fault domain count<\/td><td><code>platform_fault_domain_count<\/code> is higher than the region allows<\/td><td>Use 2, or 3 where the region supports it<\/td><\/tr><tr><td>Public IP or load balancer creation is rejected<\/td><td>Basic SKU, which Azure has retired<\/td><td>Set <code>sku = &quot;Standard&quot;<\/code> on both<\/td><\/tr><tr><td><code>AuthorizationFailed<\/code><\/td><td>The service principal has no role on the subscription<\/td><td>Assign the Contributor role at the right scope<\/td><\/tr><tr><td>Quota or <code>SkuNotAvailable<\/code> errors<\/td><td>Not enough vCPU quota, or the VM size is not offered in the region<\/td><td>Lower <code>vm_count<\/code>, change <code>size<\/code> or <code>location<\/code>, or request more quota<\/td><\/tr><tr><td>Error saying <code>subscription_id<\/code> is required<\/td><td>Provider 4.x needs a subscription ID<\/td><td>Export <code>ARM_SUBSCRIPTION_ID<\/code><\/td><\/tr><tr><td><code>curl<\/code> times out<\/td><td>The NSG is not associated with the subnet, or nginx is still installing<\/td><td>Check the NSG association and wait for cloud-init to finish<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices for multi-VM Terraform code<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>for_each<\/code> with a map or set when VMs have different roles or names. With <code>count<\/code>, removing an item from the middle of a list shifts the indexes, and Terraform then replaces VMs you did not intend to change. The <a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-do-looping-iterations-in-terraform\/\">Terraform loops guide<\/a> compares the two approaches.<\/li>\n\n\n<li>Pin the provider with <code>~&gt;<\/code> and commit <code>.terraform.lock.hcl<\/code> so every run uses the same provider version.<\/li>\n\n\n<li>Store state in a remote backend, such as an Azure Storage account with state locking. State files can contain sensitive values.<\/li>\n\n\n<li>For identical, autoscaling VMs, consider <code>azurerm_linux_virtual_machine_scale_set<\/code> instead of individual VMs.<\/li>\n\n\n<li>Run <code>terraform fmt<\/code>, <code>validate<\/code> and security scanners before every commit. A <a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-configure-pre-commit-for-terraform-complete-devops-guide-with-15-practical-use-cases-commands-security-checks-and-best-practices\/\">pre-commit setup for Terraform<\/a> automates this.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">How do I create multiple Azure VMs with Terraform?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add <code>count<\/code> (or <code>for_each<\/code>) to the network interface and VM resources, and use <code>count.index<\/code> to give each copy a unique name. Then reference the matching NIC with <code>azurerm_network_interface.test[count.index].id<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use azurerm_virtual_machine or azurerm_linux_virtual_machine?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>azurerm_linux_virtual_machine<\/code> for new code. <code>azurerm_virtual_machine<\/code> is a legacy resource that the provider no longer develops, and it uses an older block structure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does the availability set fail with platform_fault_domain_count = 7?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I change the number of VMs without editing the code?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Make the count a variable and pass a value at run time, for example <code>terraform apply -var=&quot;vm_count=5&quot;<\/code>. When you lower the number, Terraform destroys the VMs with the highest indexes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Where should I put the Azure service principal credentials?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Put them in the <code>ARM_CLIENT_ID<\/code>, <code>ARM_CLIENT_SECRET<\/code>, <code>ARM_TENANT_ID<\/code> and <code>ARM_SUBSCRIPTION_ID<\/code> environment variables, or in your CI system&#039;s secret store, not in <code>main.tf<\/code>. On a workstation, <code>az login<\/code> plus <code>ARM_SUBSCRIPTION_ID<\/code> is enough.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-do-looping-iterations-in-terraform\/\">Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-configure-pre-commit-for-terraform-complete-devops-guide-with-15-practical-use-cases-commands-security-checks-and-best-practices\/\">How to Configure pre-commit for Terraform: Complete DevOps Guide with 15 Practical Use Cases, Commands, Security Checks, and Best Practices<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/infrastructure-as-code\/terraform\/\">More Terraform tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/cloud-computing\/azure\/\">More Azure tutorials<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[5129,7853],"tags":[26253,26224],"class_list":["post-31286","post","type-post","status-publish","format-standard","hentry","category-terraform","category-azure","tag-azure-virtual-machines","tag-hcl"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31286","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=31286"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31286\/revisions"}],"predecessor-version":[{"id":80132,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31286\/revisions\/80132"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=31286"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=31286"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=31286"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}