Daniel's Tech Blog

Cloud Computing, Cloud Native & Kubernetes

Optimize your Azure Function PowerShell run duration in the consumption plan

Since PowerShell is available on Azure Functions this is the way to go for automating things in Azure. Especially running the function in the consumption plan and with a managed identity enabled.

Per default an Azure Function in the consumption plan is restricted to a run duration of 5 minutes but can be extended to 10 minutes.

That said I like to share some optimizations with you getting the most out of the 10 minutes run duration in the consumption plan.

First, we set the default run duration in the host.json from 5 to 10 minutes.

-> https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json#functiontimeout

{
  "version": "2.0",
  "managedDependency": {
    "enabled": true
  },
  "functionTimeout": "00:10:00"
}

The next thing is more a general best practice for automation tasks in Azure: Tag your resources. This is the most underestimated Azure feature, when you need to identify resources quickly.

-> https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/tag-resources

Next one. Make use of the -NoWait parameter, if the Azure PowerShell cmdlet has it. For instance, the Stop-AzVm cmdlet lets you use this parameter. Instead of waiting for the VM to deallocate and get a success response, you just fire the command to do so. But you do not wait for the response.

Deallocating large VMs in Azure can take sometimes up to 10 or 15 minutes. Using -NoWait it is just seconds.

Starts the operation and returns immediately, before the operation is completed. In order to determine if the operation has successfully been completed, use some other mechanism.

-> https://docs.microsoft.com/en-us/powershell/module/az.compute/stop-azvm?view=azps-3.8.0#parameters

Another example for optimizing the run duration is the -AsJob parameter. Using that parameter puts the cmdlet execution in the background as PowerShell job.

The execution of the Invoke-AzVMRunCommand cmdlet lets you run commands or scripts on an Azure VM without logging in via RDP or SSH. The run/execution itself can take a couple of minutes. When you need to run a lot of them, using -AsJob can help to parallelize the execution and optimize the overall run duration for the automation task.

But do not forget to implement a while loop to check the status of you background jobs. Otherwise the function exits before your background jobs have finished.

I hope you got some useful tips and tricks for optimizing your function run duration in the consumption plan.

When you are having long running operations exceeding the 10 minutes run duration, you better look into the premium or App Service plan for Azure Functions.

Nevertheless, keep in mind Azure Functions are made for short running tasks.

WordPress Cookie Notice by Real Cookie Banner