Created
February 23, 2024 10:12
-
-
Save andrewmatveychuk/3a747949610efb23fd39617395027e68 to your computer and use it in GitHub Desktop.
A basic Azure Automation runbook that sends custom logs to a Log Analytics workspace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region Creating your log entries | |
$logEntry1 = [PSCustomObject]@{ | |
OperationResult = 'Disabled' | |
OperationDetails = 'Some operation details goes here...' | |
} | |
$logEntry2 = [PSCustomObject]@{ | |
OperationResult = 'Deleted' | |
OperationDetails = 'Some operation details goes here...' | |
} | |
# Wrapping the log entries into an array, as the JSON payload expected by DCR should be a JSON array even for a single item | |
$logEntries =@($logEntry1, $logEntry2) | |
# Converting your array of log entries to a JSON payload | |
$body = $logEntries | ConvertTo-Json -AsArray -Compress | |
#endregion | |
#region Connecting to Azure | |
# Ensures you do not inherit an AzContext in your runbook | |
Disable-AzContextAutosave -Scope Process | |
# Connect to Azure with system-assigned managed identity | |
$AzureContext = (Connect-AzAccount -Identity).context | |
# set and store context | |
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext | |
#endregion | |
#region Pushing you logs to the Logs Ingestion API in Azure Monitor | |
# Acquiring an authentication token from the obtained Azure context | |
# https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview#headers | |
$token = (Get-AzAccessToken -ResourceUrl "https://monitor.azure.com/").Token | ConvertTo-SecureString -AsPlainText -Force | |
# Setting the variables for the target DCR to use | |
$dceEndpoint = Get-AutomationVariable -Name "dceEndpoint" # DCE URL | |
$dcrImmutableId = Get-AutomationVariable -Name "dcrImmutableId" # DCR immutable ID | |
$streamName = "Custom-Runbook1Operations_CL" # Stream in the DCR that represents the destination table | |
$headers = @{"Content-Type"="application/json"} # Defining the content type for the request | |
$uri = "$dceEndpoint/dataCollectionRules/$dcrImmutableId/streams/$($streamName)?api-version=2023-01-01" # Assembling the API connection URI | |
# Finally, sending your logs to the target DCR | |
Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body -StatusCodeVariable 'responseStatusCode' -ResponseHeadersVariable 'responseHeaders' -Authentication Bearer -Token $token | |
# Outputting the request results for troubleshooting purposes | |
$responseStatusCode | |
$responseHeaders | |
#endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment