Search code examples
azureterraformazure-rm

Azure Virtual Machine Extension file URL location with Terraform


Question is a little confusing but I will explain what I am doing. I am building a new Azure VM in Terraform and calling a script inside of a virtual machine extension. It is a basic powershell script. The issue is, I am currently calling it from a public GitHub account.

resource "azurerm_virtual_machine_extension" "winrm" {
  name                  = "winrm"
  location              = var.location
  resource_group_name   = var.rg_name
  count                 = length(var.vm_name_suffix)
  virtual_machine_name  = azurerm_virtual_machine.vm[count.index].name
  publisher             = "Microsoft.Compute"
  type                  = "CustomScriptExtension"
  type_handler_version  = "1.9"

  settings = <<SETTINGS
  {
    "fileUris": ["https://raw.githubusercontent.com/<name>/master/winrm.ps1"], 
    "commandToExecute": "powershell.exe -ExecutionPolicy unrestricted -NoProfile -NonInteractive -File \"./winrm.ps1\""
  }
  SETTINGS
}

Trying to figure out if there is a way I can call this from somewhere more secure. I have this set up in an Azure DevOps repo but I am not sure how to pass any kind of authentication into the settings block. I could also put this on a private GitHub account but again I would need to provide a way to authenticate to the file.


Solution

  • From the document, you could include data in a protectedSettings, and Azure VM extension protected setting data is encrypted, and only decrypted on the target virtual machine.

    You can store sensitive data in a protected configuration, which is encrypted and only decrypted inside the virtual machine. The protected configuration is useful when the execution command includes secrets such as a password.

    In this case, it's recommended to upload your scripts into blob storage, then call the extension file from that storage account with storage account key.

    For example:

    resource "azurerm_virtual_machine_extension" "winrm" {
    ...
    
      settings = <<SETTINGS
        {
            "fileUris": ["https://mystorageaccountname.blob.core.windows.net/postdeploystuff/winrm.ps1"]
        }
    SETTINGS
      protected_settings = <<PROTECTED_SETTINGS
        {
          "commandToExecute": "powershell -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File winrm.ps1",
          "storageAccountName": "mystorageaccountname",
          "storageAccountKey": "xxxxx"
        }
      PROTECTED_SETTINGS
    
      depends_on = ["azurerm_virtual_machine.vm[count.index].name"]
    
    
    }
    

    For more details, you could refer to blog about using Terraform with Azure VM extensions.