Introduction
Tagging your resources in Azure is an essential practice to ensure proper organization, cost management, and governance. If you have rolled out Azure Arc for server agents but forgot to tag the resources, it’s not too late to start. In this post, we’ll walk through a simple PowerShell script to tag Azure Arc-connected servers using the Az and Az.ConnectedMachine modules.
First, we need to ensure that both the Az and Az.ConnectedMachine modules are installed. The script then defines a custom function, Get-ADTieringLevel, which retrieves the tiering level of a server based on its Organizational Unit (OU) in Active Directory. Next, the script queries Azure Arc-connected servers in a specified resource group and tags each server with its tiering level using the New-AzTag cmdlet.
Connect-AzAccount
Set-AzContext XXXXX-XXXXX-XXXX-XXXX-XXXXXXX
Install-Module -Name Az.ConnectedMachine -Force -Verbose
Install-Module -Name Az -Force -Verbose
Function Get-ADTieringLevel
{
Param(
$ServerName
)
$OU = ([adsisearcher]"(&(name=$ServerName)(objectClass=computer))").FindOne().path
If($OU.Contains("Domain Controllers") -or $OU.Contains("Tier0")){
"TIER-0"
}
ElseIf($OU.Contains("Tier1")){
"TIER-1"
}
ElseIf($OU.Contains("Tier2")){
"TIER-2"
}
Else{
"TIERING MISSING"
}
}
$ResourceGroup = "RG-PROD-IT-AZURE-ARC-WE"
$ARCConnectedMachines = Get-AzConnectedMachine -ResourceGroupName $ResourceGroup
foreach($ARCMachine in $ARCConnectedMachines){
$ADTieringLevel = Get-ADTieringLevel -ServerName $ARCMachine.DisplayName
$Tags = @{
"ADTieringLevel" = $ADTieringLevel;
}
New-AzTag -ResourceId $ARCMachine.Id -Tag $Tags
}
By using this script, you can quickly and easily tag your Azure Arc-connected servers based on their Active Directory tiering level. If you haven’t started tagging your resources, we encourage you to do so to improve resource organization and management.