Mounting Disks on Azure VMs

March 16, 2022

I wanted to mount managed storage on an Azure VM, whilst still scripting setup of the VM from Terraform.

The terraform uses a remote-exec script as part of the MV setup:

provisioner "remote-exec" {
    inline = [
        "chmod a+x /tmp/bootstrap.sh",
        "/tmp/bootstrap.sh"
    ]
}

Unfortunately, the disk isn't mounted at this point, even when using a terraform azurerm_virtual_machine_data_disk_attachment

data "azurerm_managed_disk" "web-data-disk" {
    name                = "web-${var.deployment_id}-disk"
    resource_group_name = "web-${var.deployment_id}"
}

resource "azurerm_virtual_machine_data_disk_attachment" "web-mount" {
  managed_disk_id    = data.azurerm_managed_disk.hm-web-data-disk.id
  virtual_machine_id = azurerm_linux_virtual_machine.hm-my-vm.id
  lun                = "10"
  caching            = "ReadWrite"
}

To get around this, and make sure the disk is mounted after the VM has started and the remote-exec has finished, it's possible to use a null_resource:

resource "null_resource" "mount-disk" {

    depends_on = [azurerm_linux_virtual_machine.my-vm]

    connection {
        type = "ssh"
        user = "drumcoder"
        host = data.azurerm_public_ip.web-public-ip.ip_address
        private_key = tls_private_key.drumcoder-sshkey.private_key_pem
    }

    provisioner "remote-exec" {
        inline = [
            "sudo chmod a+x /home/drumcoder/source/scripts/mount-storage.sh",
            "sudo /home/drumcoder/source/scripts/mount-storage.sh"
        ]
    }
}

The mount-storage.sh script is as follows:

#!/bin/bash
counter=0

while [ ! -e /dev/sdc1 ]; do
    sleep 5s
    counter=$((counter + 1))
    if [ $counter -ge 50 ]; then
        exit
    fi
done

mount /dev/sdc1 /var/mail
chmod a+rwx /var/mail