How to Auto Shut Down Azure Kubernetes Cluster (AKS)

If you’re running Azure Kubernetes Services (AKS), there may come a time when you want to automatically shut down your cluster.

Perhaps you’re going on vacation and don’t want your resources being used, or maybe you’ve completed the tasks you set out to do with AKS and don’t need it running anymore. No matter the reason, this blog post will show you how to auto shutdown your Azure Kubernetes Cluster!

Azure Automation

By default, Azure does not offer a built-in option to automatically shut down a running AKS cluster at a specific time; however, Azure does allow us to use Azure Automation and run a PowerShell to shut down the cluster.

Before we start, make sure you have an Azure automation account configured.

Create an Azure Automation Account

Azure Automation is a service that allows you to run PowerShell scripts in Azure. Azure automation can be used to manage your Azure resources, including your AKS cluster.

To create an Azure automation account, open the Azure portal and select Automation Accounts from the menu on the left. Click the Add button to create a new Azure Automation account.

In the Create Azure Automation Account blade, enter a name for your account, select your Azure subscription, and choose or create a resource group.

Once your Azure Automation account has been created, select it from the list of Automation Accounts and click the Runbooks button in the menu on the left.

In the Runbooks blade, click the Add a runbook button.

In the Add, a runbook blade, select PowerShell from the list of available runbook types and click the Create button.

In the Runbook blade, enter a name for your PowerShell runbook and click the Edit button.

PowerShell Code

The following PowerShell code will shut down an AKS cluster.

Note: Replace Resource Group and AKS Cluster name in the code.

Disable-AzContextAutosave –Scope Process
$connection = Get-AutomationConnection -Name AzureRunAsConnection
$logonAttempt = 0
while(!($connectionResult) -And ($logonAttempt -le 10))
{
    $LogonAttempt++
    # Logging in to Azure...
    $connectionResult =    Connect-AzAccount `
                               -ServicePrincipal `
                               -Tenant $connection.TenantID `
                               -ApplicationId $connection.ApplicationID `
                               -CertificateThumbprint $connection.CertificateThumbprint

    Start-Sleep -Seconds 1
}
Set-AzContext -SubscriptionId "AZURE SUB ID"
Stop-AzAksCluster -ResourceGroupName aks -Name akscluster01

After saving the code, publish it and set the schedule.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.