Create an Azure VM cluster with Terraform and HCL

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

In this article, you see how to create a small compute cluster using HCL.

In this article, you learn how to:

  • Set up Azure authentication.
  • Create a Terraform configuration file.
  • Use a Terraform configuration file to create a load balancer.
  • Use a Terraform configuration file to deploy two Linux VMs in an availability set.
  • Initialize Terraform.
  • Create a Terraform execution plan.
  • Apply the Terraform execution plan to create the Azure resources.

1. Configure your environment

  • Azure subscription: If you don't have an Azure subscription, create a free account before you begin.

2. Implement the code

  1. Create a directory in which to test the sample Terraform code and make it the current directory.

     terraform {
    
       required_version = ">=0.12"
    
       required_providers {
         azurerm = {
           source = "hashicorp/azurerm"
           version = "~>2.0"
         }
       }
     }
    
     provider "azurerm" {
       features {}
     }
    
     resource "azurerm_resource_group" "test" {
       name     = "acctestrg"
       location = "West US 2"
     }
    
     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"]
     }
    
     resource "azurerm_public_ip" "test" {
       name                         = "publicIPForLB"
       location                     = azurerm_resource_group.test.location
       resource_group_name          = azurerm_resource_group.test.name
       allocation_method            = "Static"
     }
    
     resource "azurerm_lb" "test" {
       name                = "loadBalancer"
       location            = azurerm_resource_group.test.location
       resource_group_name = azurerm_resource_group.test.name
    
       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_network_interface" "test" {
       count               = 2
       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"
       }
     }
    
     resource "azurerm_managed_disk" "test" {
       count                = 2
       name                 = "datadisk_existing_${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         = "1023"
     }
    
     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 = 2
       managed                      = true
     }
    
     resource "azurerm_virtual_machine" "test" {
       count                 = 2
       name                  = "acctvm${count.index}"
       location              = azurerm_resource_group.test.location
       availability_set_id   = azurerm_availability_set.avset.id
       resource_group_name   = azurerm_resource_group.test.name
       network_interface_ids = [element(azurerm_network_interface.test.*.id, count.index)]
       vm_size               = "Standard_DS1_v2"
    
       # Uncomment this line to delete the OS disk automatically when deleting the VM
       # delete_os_disk_on_termination = true
    
       # Uncomment this line to delete the data disks automatically when deleting the VM
       # delete_data_disks_on_termination = true
    
       storage_image_reference {
         publisher = "Canonical"
         offer     = "UbuntuServer"
         sku       = "16.04-LTS"
         version   = "latest"
       }
    
       storage_os_disk {
         name              = "myosdisk${count.index}"
         caching           = "ReadWrite"
         create_option     = "FromImage"
         managed_disk_type = "Standard_LRS"
       }
    
       # Optional data disks
       storage_data_disk {
         name              = "datadisk_new_${count.index}"
         managed_disk_type = "Standard_LRS"
         create_option     = "Empty"
         lun               = 0
         disk_size_gb      = "1023"
       }
    
       storage_data_disk {
         name            = element(azurerm_managed_disk.test.*.name, count.index)
         managed_disk_id = element(azurerm_managed_disk.test.*.id, count.index)
         create_option   = "Attach"
         lun             = 1
         disk_size_gb    = element(azurerm_managed_disk.test.*.disk_size_gb, count.index)
       }
    
       os_profile {
         computer_name  = "hostname"
         admin_username = "testadmin"
         admin_password = "Password1234!"
       }
    
       os_profile_linux_config {
         disable_password_authentication = false
       }
    
       tags = {
         environment = "staging"
       }
     }
    

3. Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.

terraform init

4. 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.
  • To read more about persisting execution plans and security, see the security warning section.

5. Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

terraform apply main.tfplan

Key points:

  • The terraform apply command above 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.

6. Verify the results

Run the az vm list command with a JMESPath query to display the VMs created in the resource group.

az vm list -g acctestrg --query "[].{\"VM Name\":name}" -o table

7. 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.
    • To read more about persisting execution plans and security, see the security warning section.
  2. 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

Next steps