To connect your Windows VMs into a log analytics workspace in Azure, the Microsoft monitoring agent (MMA) needs to be installed and configured to point to the workspace.

This can be automated when provisioning a VM using Terraform.

Assuming the resource group and VM config is already done, we create a log analytics workspace using the azurerm_log_analytics_workspace resource block:

resource "azurerm_log_analytics_workspace" "law" {

  name                = lawname
  location            = westeurope
  resource_group_name = azurerm_resource_group.rg.name
  sku                 = "PerGB2018"
  retention_in_days   = 30
  tags = local.tags
}

The ‘azurerm_virtual_machine_extension’ resource block can then be configured as follows and linked to your virtual machine:

resource "azurerm_virtual_machine_extension" "mmaagent" {

  name                 = "mmaagent"
  virtual_machine_id   = azurerm_virtual_machine.windows_vm.id
  publisher            = "Microsoft.EnterpriseCloud.Monitoring"
  type                 = "MicrosoftMonitoringAgent"
  type_handler_version = "1.0"
  auto_upgrade_minor_version = "true"
  settings = <<SETTINGS
    {
      "workspaceId": "${var.workspaceId}"
    }
SETTINGS
   protected_settings = <<PROTECTED_SETTINGS
   {
      "workspaceKey": "${var.workspaceKey}"
   }
PROTECTED_SETTINGS
}

Note the workspaceId and workspaceKey are passed in as variables, so they will need to be defined as follows:

workspaceId = azurerm_log_analytics_workspace.law.workspace_id

workspaceKey = azurerm_log_analytics_workspace.law.primary_shared_key

Be sure to pass in the workspaceId, not the id of the resource as shown above.

Once deployed, in Azure, navigate to your new log analytics workspace and click on ‘agents management’, the number of connected VMs is shown here.

#terraform #azure-devops #devops #azure

Hook your Azure VM into Log Analytics with the MMA agent VM extension… using Terraform!
2.55 GEEK