Skip to content

Instantly share code, notes, and snippets.

@alexeldeib
Last active June 6, 2018 23:13
Show Gist options
  • Save alexeldeib/f1dcdd087c9edfe5e36affb8c2f25bb7 to your computer and use it in GitHub Desktop.
Save alexeldeib/f1dcdd087c9edfe5e36affb8c2f25bb7 to your computer and use it in GitHub Desktop.
Azure Log Analytics - Create Service Principal and Authenticate to API
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$subscriptionId,
[Parameter(Mandatory=$True)]
[string]$resourceGroupName,
[Parameter(Mandatory=$True)]
[string]$workspaceName,
[Parameter(Mandatory=$True)]
[string]$aadAppName,
[Parameter(Mandatory=$False)]
[string]$aadAppKey
)
Connect-AzureRmAccount
Select-AzureRmSubscription -SubscriptionId $subscriptionId
[Reflection.Assembly]::LoadWithPartialName("System.Web")
if (-Not ($MyInvocation.BoundParameters.Keys -match "aadAppKey")) {
# Generate password for service principal --save this
$aadAppKey = [System.Web.Security.Membership]::GeneratePassword(16,5)
Write-Host "SAVE APP KEY NOW:" $aadAppKey
}
$SecureStringPassword = ConvertTo-SecureString -String $aadAppKey -AsPlainText -Force
# Create service principal
$sp = New-AzureRmADServicePrincipal -DisplayName $aadAppName -Password $SecureStringPassword
# If you get error "Principal <id> not in Tenant <id> or similar, you likely need to sleep/wait a bit for propagation.
Start-Sleep -Seconds 15
# Assign Log Analytics Reader role
New-AzureRmRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Log Analytics Reader" -ResourceGroupName $resourceGroupName -ResourceName $workspaceName -ResourceType Microsoft.OperationalInsights/workspaces
$body = @{
'grant_type'='client_credentials';
'client_id'=$sp.ApplicationId;
'client_secret'=$aadAppKey;
'resource'='https://api.loganalytics.io';
}
$uri = "https://login.microsoftonline.com/$($(Get-AzureRmContext).Tenant)/oauth2/token";
$result = Invoke-WebRequest -UseBasicParsing -Uri $uri -Method Post -Body $body
$token = $($result.Content | ConvertFrom-Json).access_token
$workspaceId = $(Get-AzureRmoperationalinsightsworkspace -Name $workspaceName -ResourceGroupName $resourceGroupName).CustomerId
$apiUrl = "https://api.loganalytics.io/v1/workspaces/$($workspaceId)/query";
$apiHeaders = @{
'Authorization'='Bearer ' + $token;
}
# Sanity check
$apiBody = @'
{
"query": "union * | take 1"
}
'@
$jsonOutput = $(Invoke-WebRequest -UseBasicParsing -ContentType application/json -Uri $apiUrl -Method Post -Body $apiBody -Headers $apiHeaders).Content | ConvertFrom-Json
$jsonOutput
# CLEANUP: deletes the application in AAD and also removes associated service principals.
# Use Remove-AzureRmAdServicePrincipal to just remove the service principal.
Remove-AzureRmADApplication -ObjectId $(Get-AzureRmADApplication -DisplayNameStartWith $aadAppName)[0].ObjectId -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment