Skip to content

Instantly share code, notes, and snippets.

@lukemurraynz
Last active March 12, 2022 06:37
Show Gist options
  • Save lukemurraynz/079f6f5a8df03fcc1826f89115a35e45 to your computer and use it in GitHub Desktop.
Save lukemurraynz/079f6f5a8df03fcc1826f89115a35e45 to your computer and use it in GitHub Desktop.
#requires -Version 1.0
# Variables
#Enter your subscription name
$subscriptionName = 'luke.geek.nz'
#Enter the name of yuour
$policyDisplayName = 'Deploy - Log Analytics' #Cant Exceed 24 characters
$location = 'australiaeast'
$resourceGroup = 'aoegeek-rg'
$UsrIdentityName = 'AOE_ManagedIdentityUsr'
$param = @{
logAnalytics = 'aoegeek-la'
}
# Get a reference to the subscription that will be the scope of the assignment
$sub = Get-AzSubscription -SubscriptionName $subscriptionName
$subid = $sub.Id
#Creates User Managed identity
$AzManagedIdentity = New-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $UsrIdentityName
#Adds Contributor rights to User Managed identity to Subscription
#Waits 10 seconds to allow for Azure AD to replicate and recognise Managed identity has been created.
Start-Sleep -Seconds '10'
#Assigns role assignement to managed identity
New-AzRoleAssignment -Objectid $AzManagedIdentity.PrincipalId -scope ('/subscriptions/' + $subid ) -RoleDefinitionName 'Log Analytics Contributor'
# Get a reference to the built-in policy definition that will be assigned
$definition = Get-AzPolicyDefinition | Where-Object -FilterScript {
$_.Properties.DisplayName -eq 'Deploy - Configure Log Analytics extension to be enabled on Windows virtual machines'
}
# Create the policy assignment with the built-in definition against your subscription
New-AzPolicyAssignment -Name $policyDisplayName -DisplayName $policyDisplayName -Scope ('/subscriptions/' + $subid ) -PolicyDefinition $definition -IdentityType 'UserAssigned' -IdentityId $AzManagedIdentity.id -location $location -PolicyParameterObject $param
#Creates R3mediation task, to deploy the extension to the VM
$policyAssignmentID = Get-AzPolicyAssignment -Name $policyDisplayName | Select-Object -Property PolicyAssignmentId
Start-AzPolicyRemediation -Name 'Deploy - LA Agent' -PolicyAssignmentId $policyAssignmentID.PolicyAssignmentId -ResourceDiscoveryMode ReEvaluateCompliance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment