Enabling "Azure Analytics" on an Azure VM typically refers to integrating it with Azure Monitor and specifically sending its logs and performance metrics to a Log Analytics Workspace. The modern and recommended way to do this for a VM is by using the Azure Monitor Agent (AMA), which is configured via Data Collection Rules (DCRs).
Here's how you can achieve this using Terraform with azurerm_windows_virtual_machine:
Core Components Involved
azurerm_log_analytics_workspace: The central hub where all your logs and metrics will be stored and analyzed.
azurerm_virtual_machine_extension: To install the Azure Monitor Agent (AMA) on your Windows VM.
azurerm_monitor_data_collection_rule: Defines what data to collect (e.g., performance counters, Windows event logs) and where to send it (your Log Analytics Workspace).
azurerm_monitor_data_collection_rule_association: Links the Data Collection Rule to your specific VM.
Terraform Code Structure
You'll typically organize your Terraform code into main.tf, variables.tf, and outputs.tf.
1. variables.tf
terraform
# variables.tf
variable "resource_group_name" {
description = "Name of the resource group."
type = string
default = "rg-monitoring-demo"
}
variable "location" {
description = "Azure region to deploy resources."
type = string
default = "East US"
}
variable "vm_name" {
description = "Name of the Windows Virtual Machine."
type = string
default = "my-windows-vm"
}
variable "admin_username" {
description = "Admin username for the VM."
type = string
default = "demoadmin"
}
variable "admin_password" {
description = "Admin password for the VM."
type = string
sensitive = true # Mark as sensitive to prevent showing in logs
}
variable "log_analytics_workspace_name" {
description = "Name of the Log Analytics Workspace."
type = string
default = "law-monitoring-demo"
}
variable "dcr_name" {
description = "Name of the Data Collection Rule."
type = string
default = "dcr-windows-vm-monitoring"
}
2. main.tf
terraform
3. outputs.tf
terraform
# outputs.tf
output "vm_public_ip_address" {
description = "The public IP address of the Windows VM."
value = azurerm_public_ip.public_ip.ip_address
}
output "log_analytics_workspace_id" {
description = "The ID of the Log Analytics Workspace."
value = azurerm_log_analytics_workspace.law.id
}
output "log_analytics_workspace_name" {
description = "The name of the Log Analytics Workspace."
value = azurerm_log_analytics_workspace.law.name
}
Steps to Deploy
Save the files:
variables.tf
main.tf
outputs.tf
Initialize Terraform:
bash
terraform init
Plan the deployment:
bash
terraform plan -var="admin_password=YourStrongPasswordHere!"
Replace YourStrongPasswordHere! with a strong password that meets Azure's requirements (e.g., 12-72 characters, 3 of 4: lowercase, uppercase, number, special character).
Connect to the VM: Use the vm_public_ip_address output and the admin_username/admin_password to RDP into your Windows VM.
Check AMA Agent Status: Inside the VM, you should see "Azure Monitor Agent" listed under "Services" (services.msc).
Verify Data in Log Analytics:
Go to the Azure portal.
Navigate to your Log Analytics Workspace (search for law-monitoring-demo or whatever you named it).
Go to "Logs" under "General".
Run queries like:
Perf | take 10 (for performance counters)
Event | where Source == "Application" | take 10 (for application events)
It might take a few minutes for the first data to arrive.
VM Insights: If you navigate to your VM in the Azure portal and select "Insights" under "Monitoring", you should eventually see data populating there, as VM Insights leverages the AMA and Log Analytics Workspace.
This setup provides a robust and modern way to collect detailed telemetry from your Azure Windows VMs using Terraform.
# main.tf
provider "azurerm" {
features {}
}
# 1. Create a Resource Group
resource "azurerm_resource_group" "rg" {
name = var.resource_group_name
location = var.location
}
# 2. Create a Virtual Network and Subnet for the VM
resource "azurerm_virtual_network" "vnet" {
name = "${var.vm_name}-vnet"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
}
resource "azurerm_subnet" "subnet" {
name = "${var.vm_name}-subnet"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.2.0/24"]
}
# 3. Create a Network Interface for the VM
resource "azurerm_network_interface" "nic" {
name = "${var.vm_name}-nic"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.subnet.id
private_ip_address_allocation = "Dynamic"
# To access the VM via RDP, you'd typically add a Public IP and associate it here:
# public_ip_address_id = azurerm_public_ip.public_ip.id
}
}
# (Optional) Public IP for RDP access
resource "azurerm_public_ip" "public_ip" {
name = "${var.vm_name}-pip"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
allocation_method = "Dynamic"
sku = "Basic"
}
# (Optional) Network Security Group to allow RDP (port 3389)
resource "azurerm_network_security_group" "nsg" {
name = "${var.vm_name}-nsg"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
security_rule {
name = "AllowRDP"
priority = 1001
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "3389"
source_address_prefix = "*" # Be cautious with "*" in production; ideally restrict to trusted IPs
destination_address_prefix = "*"
}
}
resource "azurerm_network_interface_security_group_association" "nic_nsg_association" {
network_interface_id = azurerm_network_interface.nic.id
network_security_group_id = azurerm_network_security_group.nsg.id
}
# 4. Create the Windows Virtual Machine
resource "azurerm_windows_virtual_machine" "vm" {
name = var.vm_name
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
size = "Standard_DS1_v2"
admin_username = var.admin_username
admin_password = var.admin_password
network_interface_ids = [azurerm_network_interface.nic.id]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2019-Datacenter"
version = "latest"
}
# Enable Boot Diagnostics (optional, but good for troubleshooting)
boot_diagnostics {
storage_account_uri = azurerm_storage_account.boot_diag_sa.primary_blob_endpoint
}
}
# Storage Account for Boot Diagnostics (if enabled above)
resource "azurerm_storage_account" "boot_diag_sa" {
name = "${lower(replace(var.vm_name, "-", ""))}bootdiag" # Must be globally unique, 3-24 chars, lowercase letters/numbers
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
account_tier = "Standard"
account_replication_type = "LRS"
}
# --- Azure Monitor / Log Analytics Configuration ---
# 5. Create a Log Analytics Workspace
resource "azurerm_log_analytics_workspace" "law" {
name = var.log_analytics_workspace_name
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
sku = "PerGB2018"
retention_in_days = 30
}
# 6. Install the Azure Monitor Agent (AMA) extension on the VM
# This agent is required for the Data Collection Rule to function.
resource "azurerm_virtual_machine_extension" "ama_extension" {
name = "AzureMonitorWindowsAgent"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
publisher = "Microsoft.Azure.Monitor"
type = "AzureMonitorWindowsAgent"
type_handler_version = "1.0"
auto_upgrade_minor_version = true # Keep agent updated
}
# 7. Create a Data Collection Rule (DCR)
# This defines what data to collect and where to send it.
resource "azurerm_monitor_data_collection_rule" "dcr" {
name = var.dcr_name
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
kind = "Windows" # Specify "Linux" for Linux VMs
# Define the destinations for the collected data
destinations {
log_analytics {
workspace_resource_id = azurerm_log_analytics_workspace.law.id
name = "myLogAnalyticsDestination"
}
}
# Define the data streams and where they should go
data_flow {
streams = ["Microsoft-Perf", "Microsoft-WindowsEvent"]
destinations = ["myLogAnalyticsDestination"]
}
# Define the data sources to collect
data_sources {
# Collect performance counters
performance_counter {
streams = ["Microsoft-Perf"]
sampling_frequency_in_seconds = 60 # Collect every 60 seconds
counter_specifiers = [
"\\Processor(_Total)\\% Processor Time",
"\\Memory\\Available Bytes",
"\\LogicalDisk(_Total)\\% Free Space",
"\\Network Interface(*)\\Bytes Total/sec"
]
name = "myPerformanceCounters"
}
# Collect Windows Event Logs
windows_event_log {
streams = ["Microsoft-WindowsEvent"]
data_sources = ["Application", "System"] # You can add "Security" too, but might require enabling auditing
x_path_queries = ["Application!*", "System!*"] # Collect all events from these sources
name = "myWindowsEventLogs"
}
# You can add more data sources here, e.g., for custom text logs (file_system_log)
# file_system_log {
# streams = ["Microsoft-Textlog"]
# file_paths = ["C:\\mylogs\\*.log"]
# name = "myCustomLogs"
# }
}
}
# 8. Associate the Data Collection Rule with the VM
resource "azurerm_monitor_data_collection_rule_association" "dcr_association" {
name = "${var.vm_name}-dcr-association"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
data_collection_rule_id = azurerm_monitor_data_collection_rule.dcr.id
description = "Associate DCR with VM for performance and event log collection."
}