In this post, Sr. Consultant Tim Omta shows how to change Azure Monitor Log Agent Workspace for all VMs in an Azure Subscription.
Background
During a recent engagement, a customer needed to consolidate several Azure Monitor Log Workspaces (aka Log Analytics, aka OMS log workspaces) that had grown up over time in their Azure subscriptions. They wanted to consolidate all these workspaces into one so that they could apply analytics and other powerful tools, such as Azure Security Center and Azure Sentinel.
The customer had a number of VMs and since they were already logging to Azure Monitor Logs (albeit different workspaces), their VMs already had the logging agent installed on them. We needed to change the workspace id and key for all the VM agents so that the VM data would be directed into the new, central, consolidated workspace. The problem we faced was to do this without having to touch each machine by hand.
This can be done in a few different ways, but I chose Azure PowerShell as the most expedient in our situation. I thought this script may be useful as an example for others that may be in a similar situation. The script uses PowerShell jobs to execute the changes to the VM agents in parallel, which is important if you need to change a large number of VM agents.
Script Description
The script requires that you have Azure PowerShell installed. Open a PowerShell prompt and execute Connect-AzAccount to authenticate the PowerShell session with Azure.
The script itself will switch to the subscription containing your VMs. Gather the VM agents that are functional into an array ($extentionList), then start a PowerShell job to change the log workspace information for each agent.
Script Code:
Select-AzSubscription -subscriptionId YourSubscriptionId
$workspaceId='Your workspace Id'
$workspaceKey='Your workspace key'
$secureKey=ConvertTo-SecureString -String $workspaceKey -AsPlainText -Force
$extensionList=Get-AzVm | foreach {
Get-AzVMExtension -ResourceGroupName $_.ResourceGroupName -VMName $_.Name -ExtensionName "MicrosoftMonitoringAgent"
}
$PublicSettings = @{"workspaceId" = $workspaceId}
$ProtectedSettings = @{"workspaceKey" = $workspaceKey}
$jobs=@()
$extensionList | foreach {
$jobs += Set-AzVMExtension -ExtensionName $_.Name `
-ResourceGroupName $_.ResourceGroupName `
-VMName $_.VMName `
-Publisher $_.Publisher `
-ExtensionType $_.ExtensionType `
-TypeHandlerVersion 1.0 `
-Settings $PublicSettings `
-ProtectedSettings $ProtectedSettings `
-Location $_.Location -AsJob
}
Receive-Job -Job $jobs -Wait
0 comments