Here’s a basic example of how you might set up an Azure Automation Runbook to handle this:
# Import the module
Import-Module Az.Accounts
Import-Module Az.Compute
# Connect to Azure with Managed Identity
$AzureContext = (Connect-AzAccount -Identity).context
# Specify the VMSS and resource group
$vmssName = "<Your VMSS Name>"
$resourceGroupName = "<Your Resource Group Name>"
# Get the VMSS
$vmss = Get-AzVmss -ResourceGroupName $resourceGroupName -VMScaleSetName $vmssName
# Loop through the VMSS instances
foreach ($instance in $vmss.VirtualMachines) {
# Check if the instance is in a 'Deleting' state
if ($instance.ProvisioningState -eq 'Deleting') {
# Get the instance ID
$instanceId = $instance.InstanceId
# Remove the domain object associated with the instance
# Note: You'll need to replace this with the actual command to remove your domain object
# Remove-DomainObject -InstanceId $instanceId
# Output the instance ID
Write-Output "Removed domain object for instance: $instanceId"
}
}
Please replace <Your VMSS Name> and <Your Resource Group Name> with your actual VMSS name and resource group name. Also, replace Remove-DomainObject with the actual command to remove your domain object. This script connects to Azure using Managed Identity, retrieves the specified VMSS, and loops through its instances. If an instance is in a ‘Deleting’ state (indicating that it’s being scaled in), the script removes the associated domain object. Remember to test this script thoroughly and make any necessary adjustments to fit your specific use case. Always ensure you have appropriate error handling in place when working with automation scripts.