This article has not been completed yet. However, it may already contain helpful Information and therefore it has been published at this stage.
Via Azure Portal / Arc - Management - Portal:
# Retrieve information about the existing Log Analytic Workspaces
Get-AzOperationalInsightsWorkspace
# Read out keys for a specific workspace
Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName "<Ressourcegroup>" -Name "<Workspacename>"
ARM - Template:
Template-File:
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
"contentVersion": "1.0.0.0",
"parameters": {
"vmName": {
"type": "String"
},
"location": {
"type": "String"
},
"workspaceId": {
"type": "String"
},
"workspaceKey": {
"type": "String"
}
},
"resources": [
{
"type": "Microsoft.HybridCompute/machines/extensions",
"apiVersion": "2020-08-02",
"name": "[concat(parameters('vmName'),'/MicrosoftMonitoringAgent')]",
"location": "[parameters('location')]",
"properties": {
"publisher": "Microsoft.EnterpriseCloud.Monitoring",
"type": "MicrosoftMonitoringAgent",
"autoUpgradeMinorVersion": true,
"settings": {
"workspaceId": "[parameters('workspaceId')]"
},
"protectedSettings": {
"workspaceKey": "[parameters('workspaceKey')]"
}
}
}
]
}
Parameter - File:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"vmName": {
"value": "<VM-Name>"
},
"location": {
"value": "<Location>"
},
"workspaceId": {
"value": "<ID>"
},
"workspaceKey": {
"value": "<Key>"
}
}
}
Via Script:
function Install-OMSAgents {
<#
.Synopsis
Used to install OMS Agents
.Description
Used to install OMS Agents locally and remotely. It will download the required installer by
default, but you can also specify a path to the installer if you don't have internet access
for all machines you wish to install it on, or want to save bandwidth.
.Parameter ComputerName
Array of Computer Names to install the OMS agent on.
.Parameter WorkspaceID
Azure Log Analytics Workspace ID.
.Parameter WorkspaceKey
Azure Log Analytics Workspace Key.
.Parameter OMSDownloadPath
Specify the directory on each machine to download the installer to.
.Parameter InstallerPath
Specify a local or UNC path to the MMA installer if you don't want to download it automatically.
Requires all servers you want to be able to install the Agent on to have access to the share hosting
the installer.
.Parameter OverrideExisting
Triggers overriding existing workspaces on machines with the agent already installed.
.Example
Install-OMSAgents -ComputerName Server01 -WorkspaceID xxxxxx -WorkspaceKey xxxxx
This will default to downloading and installing the Microsoft Monitoring Agent
on Server01 from the internet, and configure it to point to the specified
Azure Log Analytics Workspace
.Example
Install-OMSAgents -ComputerName 'Server01','Server02' -InstallerPath \\nas01\share01\MMASetup-AMD64.exe -WorkspaceID xxx -WorkspaceKey xxx
This will install on Server01 and Server02 using the installer found on NAS01.
.Notes
Big shout out to John Savill (@ntfaqguy) for the original script I used
to create this function, it can be found on his website
https://savilltech.com/2018/01/21/deploying-the-oms-agent-automatically/
---------------------------------------------------------------
Version: 1.0.0
Maintained By: Ben Thomas (@NZ_BenThomas)
Last Updated: 2019-05-20
---------------------------------------------------------------
CHANGELOG:
1.0.0
- Initial version
- Updated @ntfaqguy's script to a function
- Added support for remotely running against multiple machines
- Added parameters to specify a central installer rather than
downloading the agent on every machine.
- Added a switch for overridding existing Agent installs with
new workspace details.
.Link
https://bcthomas.com
#>
[cmdletbinding(DefaultParameterSetName = 'Download')]
param(
[string[]]$ComputerName = 'Localhost',
[parameter(Mandatory)]
[string]$WorkspaceID,
[parameter(Mandatory)]
[string]$WorkspaceKey,
[parameter(ParameterSetName = 'Download')]
[string]$OMSDownloadPath = 'C:\Temp',
[parameter(Mandatory, ParameterSetName = 'Offline')]
[string]$InstallerPath,
[switch]$OverrideExisting
)
begin {
#region: Helper Functions
function Get-InstalledSoftware {
param(
[string]$ComputerName = 'localhost',
[string]$ProductName = '*'
)
$UninstallKey = ”SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall”
$reg = [microsoft.win32.registrykey]::OpenRemoteBaseKey(‘LocalMachine’, $ComputerName)
$regkey = $reg.OpenSubKey($UninstallKey)
$subkeys = $regkey.GetSubKeyNames()
foreach ($key in $subkeys) {
$thisKey = $UninstallKey + ”\\” + $key
$thisSubKey = $reg.OpenSubKey($thisKey)
$DisplayName = $($thisSubKey.GetValue(“DisplayName”))
if ($DisplayName -ilike $ProductName) {
[pscustomobject][ordered]@{
ComputerName = $ComputerName
ProductName = $($thisSubKey.GetValue(“DisplayName”))
DisplayVersion = $($thisSubKey.GetValue(“DisplayVersion”))
InstallLocation = $($thisSubKey.GetValue(“InstallLocation”))
Publisher = $($thisSubKey.GetValue(“Publisher”))
}
}
}
}
#endregion
Write-Verbose "Establish Sessions to target machines"
$Sessions = @{ }
$ExcludedComputers = @()
$OverrideComputers = @()
$Results = @()
foreach ($Computer in $ComputerName) {
try {
$NewSession = New-PSSession -ComputerName $Computer -Name $Computer -ErrorAction Stop
Write-verbose "Checking if OMS Agent is installed on $Computer"
$MMAObj = Get-InstalledSoftware -ProductName 'Microsoft Monitoring Agent' -ComputerName $Computer
if ($MMAObj -and ( -not $OverrideExisting) ) {
throw "Agent is already installed"
}
elseif ($MMAObj -and $OverrideExisting) {
Write-Warning "Agent found on $Computer, the existing settings on this`nMachine will be overridden."
$OverrideComputers += $Computer
}
else {
Write-Verbose "No Agent found, install scheduled."
}
$Sessions.Add($Computer, $NewSession)
}
catch {
Write-Warning "An error occured and $Computer will be excluded.`nError Details: $($PSItem.ToString())"
$ExcludedComputers += $Computer
Continue
}
}
}
Process {
Foreach ($Computer in $ComputerName) {
if ($Computer -iin $ExcludedComputers) {
Write-Warning "Skipping $Computer as it's excluded"
}
else {
try {
$Install = $true
if ($Computer -iin $OverrideComputers) {
$Install = $false
}
if ($PSCmdlet.ParameterSetName -eq 'Download') {
# Download the required installer onto the remove machine
Write-Verbose "Downloading MMASetup-AMD64.exe to $Computer $OMSDownloadPath"
$InstallerPath = Invoke-Command -session $Sessions[$computer] `
-ArgumentList $OMSDownloadPath, $Install `
-ErrorAction Stop `
-ScriptBlock {
param(
$OMSDownloadPath,
$Install
)
$OMS64bitDownloadURL = "https://go.microsoft.com/fwlink/?LinkId=828603"
$OMSDownloadFileName = "MMASetup-AMD64.exe"
$OMSDownloadFullPath = "$OMSDownloadPath\$OMSDownloadFileName"
if ($Install) {
#Create temporary folder if it does not exist
if (-not (Test-Path -Path $OMSDownloadPath)) {
New-Item -Path $OMSDownloadPath -ItemType Directory | Out-Null
}
Write-host "$env:computername - Downloading the agent..."
#Download to the temporary folder
Invoke-WebRequest -Uri $OMS64bitDownloadURL -OutFile $OMSDownloadFullPath | Out-Null
}
"$OMSDownloadFullPath"
}
}
$Workspaces = Invoke-Command -Session $Sessions[$Computer] `
-ArgumentList $InstallerPath, $WorkspaceID, $WorkspaceKey, $OverrideExisting, $Install `
-ErrorAction Stop `
-ScriptBlock {
Param(
$InstallerPath,
$WorkspaceID,
$WorkspaceKey,
$OverrideExisting,
$Install
)
Write-host "$env:computername - Installing the agent..."
if ((-Not (Test-Path -Path $InstallerPath)) -and $Install ) {
throw "$ComputerName cannot access $InstallerPath"
}
elseif ($Install) {
#Install the agent
$ArgumentList = '/C:"setup.exe /qn ADD_OPINSIGHTS_WORKSPACE=0 AcceptEndUserLicenseAgreement=1"'
Start-Process $InstallerPath -ArgumentList $ArgumentList -ErrorAction Stop -Wait | Out-Null
}
#Check if the CSE workspace is already configured
$AgentCfg = New-Object -ComObject AgentConfigManager.MgmtSvcCfg
$OMSWorkspaces = $AgentCfg.GetCloudWorkspaces()
$CSEWorkspaceFound = $false
foreach ($OMSWorkspace in $OMSWorkspaces) {
if ($OMSWorkspace.workspaceId -eq $WorkspaceID) {
$CSEWorkspaceFound = $true
}
elseif ($OverrideExisting) {
$AgentCfg.RemoveCloudWorkspace($OMSWorkspace.workspaceId)
$AgentCfg.ReloadConfiguration()
}
}
if (!$CSEWorkspaceFound) {
Write-host "$env:computername - Adding CSE OMS Workspace..."
$AgentCfg.AddCloudWorkspace($WorkspaceID, $WorkspaceKey)
Restart-Service HealthService
}
else {
Write-Warning "CSE OMS Workspace already configured"
}
# Get all configured OMS Workspaces
sleep 5
$AgentCfg.GetCloudWorkspaces()
}
$Results += [pscustomobject][ordered]@{
ComputerName = $Computer
AgentID = $Workspaces.AgentID
WorkspaceID = $Workspaces.WorkspaceID
Status = $Workspaces.ConnectionStatusText
}
}
catch {
Write-Warning "Installation failed on $Computer`nRan into an issue: $($PSItem.ToString())"
Continue
}
}
}
}
End {
foreach ($connection in $Sessions.Keys) {
$Sessions[$connection] | Remove-PSSession -Confirm:$false
}
$Results
}
}
# Installation and configuration
Install-OMSAgents -ComputerName $env:computername -OMSDownloadPath "C:\temp" -WorkspaceID "<ID>" -WorkspaceKey "<Key>"
<#
.DESCRIPTION
Long description
.PARAMETER Servers
Script expect server names it can connect to over the network (Servername.Domain.local)
Invoke-command uses the WinRM ports.
TCP/5985 = HTTP
TCP/5986 = HTTPS
Parameter accepts an array.
.PARAMETER WorkSpaceID
This is the workspaceDI
.PARAMETER WorkSpaceKey
This is the WorkSpaceKey.
.EXAMPLE
$servers = Get-ADComputer -Filter {operatingsystem -like "*server*"}
Update-OMSWorkSpace -Servers $Servers -WorkSpaceID 'XXXXXXXXXXXXXXXXXX' -WorkSpaceKey 'XXXXXXXXXXXXXXXXXX'
.LINK
https://bwit.blog/bulk-update-oms-workspace-key-powershell/
#>
function Update-OMSWorkSpace
{
[CmdletBinding()]
param (
[Parameter (Mandatory = $true)]
[string[]]
$Server,
[Parameter (Mandatory = $true)]
$WorkSpaceID,
[Parameter (Mandatory = $true)]
$WorkSpaceKey
)
begin
{
Write-Verbose 'Update-OMSWorkSpaceKey: begin: Creating Scriptblock for remote servers.'
$Scriptblock = {
$WorkspaceID = $WorkSpaceID
$WorkspaceKey = $WorkSpaceKey
$AgentCfg = New-Object -ComObject AgentConfigManager.MgmtSvcCfg
$AgentCfg.GetCloudWorkspaces()
$AgentCfg.AddCloudWorkspace($WorkspaceID, $WorkspaceKey)
Restart-Service HealthService
}
}
process
{
Write-Verbose 'Update-OMSWorkSpaceKey: process: Starting script to invoke scriptblock to serverlist.'
#foreach ($Srv in $Server)
#{
Write-Verbose "Update-OMSWorkSpaceKey: process: Invoke-Command on srv: $Server"
try
{
Invoke-Command -ComputerName $Server -ScriptBlock $scriptblock
}
catch
{
continue
}
#}
}
end
{
return "Script finished updating keys."
}
}
# OMSWorkSpace Config Update
Update-OMSWorkSpace -Servers <Server Names> -WorkspaceID "<ID>" -WorkspaceKey "<Key>"
Via Policy:
Options:
- Recommended: "Configure Log Analytics extension on Azure Arc enabled Windows servers" ( Part of the "Enable Azure Monitor for VMs" - Initiative Definition)
- Custom - Policy (based on "[Preview]: Configure Azure Arc-enabled Windows machines with Log Analytics agents connected to default Log Analytics workspace" - see Link)
Adjust the following variables:
- <Location>
- <RG Name>
- < Workspace Name>
{
"properties": {
"displayName": "[CUSTOM]: Configure Azure Arc-enabled Windows machines with Log Analytics agents connected to a specified LAW",
"policyType": "Custom",
"mode": "Indexed",
"metadata": {
"category": "Monitoring",
"createdBy": "6663633e-3aec-4262-8922-753ee3bfc7f9",
"createdOn": "2022-02-02T11:55:34.7796738Z",
"updatedBy": "6663633e-3aec-4262-8922-753ee3bfc7f9",
"updatedOn": "2022-02-02T14:06:49.028555Z"
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
}
},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.HybridCompute/machines"
},
{
"field": "Microsoft.HybridCompute/machines/osName",
"equals": "windows"
}
]
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"deploymentScope": "subscription",
"type": "Microsoft.HybridCompute/machines/extensions",
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
],
"existenceCondition": {
"allOf": [
{
"field": "Microsoft.HybridCompute/machines/extensions/type",
"equals": "MicrosoftMonitoringAgent"
},
{
"field": "Microsoft.HybridCompute/machines/extensions/publisher",
"equals": "Microsoft.EnterpriseCloud.Monitoring"
},
{
"field": "Microsoft.HybridCompute/machines/extensions/provisioningState",
"equals": "Succeeded"
}
]
},
"deployment": {
"location": "<Location>",
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"type": "string"
},
"vmName": {
"type": "string"
},
"vmResourceGroup": {
"type": "string"
}
},
"variables": {
"subscriptionId": "[subscription().subscriptionId]",
"defaultRGName": "<RG Name>",
"defaultRGLocation": "[parameters('location')]",
"workspaceName": "<Workspace Name>",
"deployWorkspace": "[concat('deployWorkspace-', uniqueString(deployment().name))]",
"deployExtension": "[concat('deployExtension-', uniqueString(deployment().name))]"
},
"resources": [
{
"type": "Microsoft.Resources/resourceGroups",
"apiVersion": "2020-06-01",
"name": "[variables('defaultRGName')]",
"location": "[variables('defaultRGLocation')]"
},
{
"type": "Microsoft.Resources/deployments",
"apiVersion": "2020-06-01",
"name": "[variables('deployWorkspace')]",
"dependsOn": [
"[resourceId('Microsoft.Resources/resourceGroups', variables('defaultRGName'))]"
],
"properties": {
"mode": "Incremental",
"expressionEvaluationOptions": {
"scope": "inner"
},
"parameters": {
"defaultRGLocation": {
"value": "[variables('defaultRGLocation')]"
},
"workspaceName": {
"value": "[variables('workspaceName')]"
}
},
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"defaultRGLocation": {
"type": "string"
},
"workspaceName": {
"type": "string"
}
},
"resources": [
{
"type": "Microsoft.OperationalInsights/workspaces",
"name": "[parameters('workspaceName')]",
"apiVersion": "2015-11-01-preview",
"location": "[parameters('defaultRGLocation')]",
"properties": {
"sku": {
"name": "pernode"
},
"retentionInDays": 30,
"features": {
"searchVersion": 1
}
}
}
]
}
},
"resourceGroup": "[variables('defaultRGName')]"
},
{
"type": "Microsoft.Resources/deployments",
"apiVersion": "2020-06-01",
"name": "[variables('deployExtension')]",
"dependsOn": [
"[variables('deployWorkspace')]"
],
"properties": {
"mode": "Incremental",
"expressionEvaluationOptions": {
"scope": "inner"
},
"parameters": {
"workspaceId": {
"value": "[concat(subscription().id,'/resourceGroups/', variables('defaultRGName'), '/providers/Microsoft.OperationalInsights/workspaces/', variables('workspaceName'))]"
},
"vmName": {
"value": "[parameters('vmName')]"
},
"location": {
"value": "[parameters('location')]"
}
},
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"workspaceId": {
"type": "string"
},
"vmName": {
"type": "string"
},
"location": {
"type": "string"
}
},
"variables": {
"vmExtensionName": "MicrosoftMonitoringAgent",
"vmExtensionPublisher": "Microsoft.EnterpriseCloud.Monitoring",
"vmExtensionType": "MicrosoftMonitoringAgent",
"vmExtensionTypeHandlerVersion": "1.0"
},
"resources": [
{
"name": "[concat(parameters('vmName'), '/', variables('vmExtensionName'))]",
"type": "Microsoft.HybridCompute/machines/extensions",
"location": "[parameters('location')]",
"apiVersion": "2019-12-12",
"properties": {
"publisher": "[variables('vmExtensionPublisher')]",
"type": "[variables('vmExtensionType')]",
"typeHandlerVersion": "[variables('vmExtensionTypeHandlerVersion')]",
"autoUpgradeMinorVersion": true,
"settings": {
"workspaceId": "[reference(parameters('workspaceId'), '2015-03-20').customerId]",
"stopOnMultipleConnections": "true"
},
"protectedSettings": {
"workspaceKey": "[listKeys(parameters('workspaceId'), '2015-03-20').primarySharedKey]"
}
}
}
]
}
},
"resourceGroup": "[parameters('vmResourceGroup')]"
}
]
},
"parameters": {
"location": {
"value": "[field('location')]"
},
"vmName": {
"value": "[field('name')]"
},
"vmResourceGroup": {
"value": "[resourceGroup().name]"
}
}
}
}
}
}
}
},
"id": "/subscriptions/31c82c65-e216-421b-b29a-3aa473d097aa/providers/Microsoft.Authorization/policyDefinitions/33a813b4-86b3-4f91-8a11-52b48f16c064",
"type": "Microsoft.Authorization/policyDefinitions",
"name": "33a813b4-86b3-4f91-8a11-52b48f16c064",
"systemData": {
"createdBy": "t.bruendl@iv-bruendl.at",
"createdByType": "User",
"createdAt": "2022-02-02T11:55:34.7589311Z",
"lastModifiedBy": "t.bruendl@iv-bruendl.at",
"lastModifiedByType": "User",
"lastModifiedAt": "2022-02-02T14:06:48.9683487Z"
}
}
Azure Policy evaluates resource compliance automatically every 24 hours for already assigned policies or initiatives.
New policy or initiative assignments start the evaluation after the assignment has been applied to the defined scope which might take up to 30 minutes.
# Trigger Policy Scan
az policy state trigger-scan --resource-group <RG - Name>
Source:
Link: https://www.danielstechblog.io/trigger-an-on-demand-azure-policy-compliance-evaluation-scan/