Understanding the Need for Function App Cleanup

In cloud environments, deprecated or unused resources can accumulate over time, leading to unnecessary costs and management overhead. This guide focuses on implementing automated cleanup of stopped Azure Function Apps that haven’t been active for extended periods.

Identifying Inactive Function Apps

First, we’ll create a PowerShell script to identify Function Apps that have been stopped for more than 45 days:

Get all Function Apps in specified subscription

$functionApps = Get-AzFunctionApp

foreach ($app in $functionApps) { $status = (Get-AzFunctionApp -Name $app.Name -ResourceGroupName $app.ResourceGroup).State $lastModified = (Get-AzResource -ResourceId $app.Id).ChangedTime

if ($status -eq "Stopped" -and $lastModified -lt (Get-Date).AddDays(-45)) {
    Write-Output "Function App $($app.Name) has been stopped for more than 45 days"
}

}

Implementing the Cleanup Process

Here’s an Azure CLI script to safely remove identified Function Apps:

#!/bin/bash

Array of Function Apps to remove

function_apps=($(az functionapp list –query “[?state==‘Stopped’].{name:name, resourceGroup:resourceGroup}” -o tsv))

for app in “${function_apps[@]}”; do # Extract name and resource group name=$(echo $app | cut -f1) resourceGroup=$(echo $app | cut -f2)

# Backup app settings
echo "Backing up settings for $name"
az functionapp config appsettings list \
    --name $name \
    --resource-group $resourceGroup \
    --output json > "${name}_settings_backup.json"

# Delete the Function App
echo "Deleting Function App $name"
az functionapp delete \
    --name $name \
    --resource-group $resourceGroup \
    --yes

done

Best Practices for Function App Lifecycle Management

  1. Documentation: Maintain a registry of Function Apps with their purpose and owners
  2. Tagging: Implement proper tagging strategy for easier identification
  3. Monitoring: Set up alerts for apps that remain in stopped state
  4. Backup: Always backup configurations before deletion
  5. Approval Process: Implement a change management process for deletions

Automating the Process with Azure DevOps

Create a pipeline to automate the cleanup process:

trigger: none

schedules:

  • cron: “0 0 0” displayName: Weekly cleanup branches: include:
    • main always: true

jobs:

  • job: CleanupFunctionApps steps:
    • task: AzurePowerShell@5 inputs: azureSubscription: ‘Your-Azure-Subscription’ ScriptType: ‘FilePath’ ScriptPath: ‘$(System.DefaultWorkingDirectory)/cleanup-script.ps1’ azurePowerShellVersion: ‘LatestVersion’

This automation helps maintain a clean, cost-effective Azure environment while ensuring proper documentation and safety measures are in place.