19 October, 2022

Azure Automation : Periodically delete log files in Virtual Machines

It's vary common that you are running multiple agents in your virtual machines. Microsoft also deploys several agents behind the scene in your VMs to satisfy various configurations requirements. Now the problem starts when these agents start generating logs files locally and eventually starts eating up the disk space. 

You naturally by instinct jumps in to scale up your VMs or starts adding more disks to it inorder to maintain the performance. But this approach would cost your dearly as your Azure bill would shoot up substantially. Why not clean up those logs periodically with a scheduler and make your boss happy 😀

Azure Automation with runbook type PowerShell is there to make you achieve this very comfortably. Create an automation account with a PowerShell runbook. The script is given below. Copy-Paste it >> Test it >> Schedule it. Done! Smart work isn't it 👍


$ResourceGroup = '<<resource group name>>'
$FolderPath = 'rm /<<log folder path>>/*' #E.g. rm /home/user/temp/*

try
{
	Write-Output "Connecting ..."
	$message = Connect-AzAccount -Identity 
	Write-Output "Connection successful"

	#Get all Azure VMs which are in running state and are running Linux
	$myAzureVMs = Get-AzVM -status | Where-Object {$_.PowerState -eq "VM running" -and $_.StorageProfile.OSDisk.OSType -eq "Linux"}
	Write-Output "Total Linux VMs detected : $($myAzureVMs.Name.Count)"
	Write-Output "VM Names : $($myAzureVMs.Name)" 

	# Run the script against all the listed VMs
	if($myAzureVMs.Name.Count -gt 1)
	{
		For($val = 0; $val -le $myAzureVMs.Name.Count-1; $val++)
		{
			Write-Output "Target VM : $($myAzureVMs.Name[$val]), File deletion in progress ..."
			$message = Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroup -Name $myAzureVMs.Name[$val] -CommandId 'RunShellScript' -ScriptString $FolderPath
			Write-Output "Operation completed successfully" 
		}	
	}
	else {
		Write-Output "Target VM : $($myAzureVMs.Name), File deletion in progress ..."
		$message = Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroup -Name $myAzureVMs.Name -CommandId 'RunShellScript' -ScriptString $FolderPath
		Write-Output "Operation completed successfully" 
	}
}
catch
{
	Write-Error -Message $_.Exception
    throw $_.Exception
}