Azure Resource Ownership Tagging with PowerShell

Mukesh Kumar Korrapati
3 min readMar 13, 2024

--

Introduction:
Managing ownership and accountability of resources in Azure is a critical aspect of cloud governance. Assigning ownership tags to resources helps in tracking resource creators and administrators, enabling better visibility and control. In this blog post, we’ll explore how to automate the process of assigning ownership tags to Azure resources using PowerShell.

Setting Up the Environment:
Before diving into the automation script, ensure you have PowerShell installed and authenticated to your Azure account using Connect-AzAccount. Once authenticated, set the Azure context to the appropriate subscription using Set-AzContext.

If not installed use the below commands to install

#Set the PowerShell execution policy to remote signed:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

#Use the Install-Module cmdlet to install the Az PowerShell module:
Install-Module -Name Az -Repository PSGallery -Force

Here is the code you can make use of:

# Authenticate to Azure (assuming you've already logged in)
# If not, use 'Connect-AzAccount' to authenticate

$SubscriptionId = "SubscriptionId"

Connect-AzAccount

Set-AzContext -SubscriptionId $SubscriptionId

$activityLogs = @()
# Resource details
$ownerTag = "Owner"

# Subtract one day from the current date to get the start date
$EndDate = Get-Date
$StartDate = (Get-Date).AddHours(-2)

#Fetch all activity log entries for resource creation in the past day
$activityLogs = Get-AzActivityLog -StartTime $StartDate -EndTime $EndDate -Status "Succeeded" | Where-Object {$_.OperationName -contains "Create" -or $_.OperationName -contains "Deployment" -and $_.EventCategory -eq "Administrative" -and $_.Caller -ne "$null" -and $_.Caller -notmatch '\d'}

foreach ($activityLog in $activityLogs) {

$resourceId = $activityLog.ResourceId

# Check if the resource still exists
$existingResource = Get-AzResource -ResourceId $resourceId -ErrorAction SilentlyContinue

if ($existingResource) {
$logDetails = @{
TimeGenerated = $activityLog.TimeGenerated
ResourceGroupName = $activityLog.ResourceGroupName
ResourceId = $activityLog.ResourceId
Caller = $activityLog.Caller
OperationName = $activityLog.OperationName
Status = $activityLog.Status
} | ConvertTo-Json -Depth 5

# Check if the operation name contains "Create"

if ($activityLog.OperationName -contains "Create") {
$resourceGroupName = $activityLog.ResourceGroupName
$resourceName = $activityLog.ResourceId -split '/' | Select-Object -Last 1

# Get the UPN ID of the owner based on caller
$ownerUpn = $activityLog.Caller


$Result = $activityLog.ResourceId -split '/providers/', 3
$ResourceType = ($Result[1] -split '/', 3)[0, 1] -join '/'

$Tags = Get-AzTag -ResourceId $resourceId

if ($Tags.Name -ne $ownerTag -or ($null -eq $Tags)) {
# Add the Owner tag to the resource
$tag = @{ $ownerTag = $ownerUpn }

# Update the resource with the new tags
Update-AzTag -ResourceId $resourceId -Operation Merge -Tag $tag

Write-Host "Added 'Created By' tag with user: $ownerUpn"
}

else {
Write-Host "Tag already exists"
}

Write-Host "Owner tag added to the resource: $resourceName in resource group: $resourceGroupName"
}
}
}

Write-Host "Script execution completed."

Script Overview:

We’ll walk through a PowerShell script designed to retrieve Azure activity logs for resource creation events within a specified timeframe. For each newly created resource, the script identifies the resource owner based on the logged caller’s UPN (User Principal Name) and assigns an “Owner” tag to the resource. This tag helps track ownership responsibility within Azure subscriptions.

Script Overview

The following PowerShell script automates the assignment of an “Owner” tag to newly created Azure resources based on activity logs:

Step 1: Authentication to Azure

Before running the script, ensure you’ve authenticated to Azure using the Connect-AzAccount cmdlet and set the appropriate subscription context using Set-AzContext.

Step 2: Retrieving Activity Logs

The script fetches activity logs for resource creation events within a specified timeframe using Get-AzActivityLog. It filters the logs based on criteria such as successful operations, administrative events, and non-system callers.

Step 3: Identifying Resource Owners

For each activity log entry corresponding to a resource creation event, the script extracts the caller’s UPN (User Principal Name). This UPN serves as the identifier for the resource owner.

Step 4: Assigning Ownership Tags

If the resource does not already have an “Owner” tag assigned, the script adds the UPN of the resource owner as the tag value using Update-AzTag. This ensures that ownership information is consistently attached to each resource.

Note: Start date can be used for hours days or months. Consider based on your requirements.

$StartDate = (Get-Date).Day(-2)
$StartDate = (Get-Date).Month(-1)

By automating ownership tag assignments using PowerShell, you can streamline resource management and enhance accountability within your Azure environment. Remember to adapt the script to your specific use case, adjust the timeframe, and customize the tag values accordingly. Happy tagging! 🚀💻

--

--