A cluster that is needed from 8 am to 7 pm, but stays on at night and over the weekend, pays for 168 hours a week to use sixty. On a client’s AKS cluster I automated the after-hours shutdown. It is a microservices platform with about twenty services, Istio, RabbitMQ, Keycloak, ArgoCD and a MinIO object store holding almost two million objects.

The result is −63% on compute: about €546 a month, over €6,500 a year. Here is how I did it and, above all, what I found by measuring instead of estimating.

The numbers, before writing any code

There are six nodes, 2 × D8as_v6 and 4 × D2as_v6, in Italy North. I read the prices from Azure’s public pricing API, not from memory. az aks stop only deallocates compute, so the first question is which part of the bill actually moves.

ItemAlways onOff after hours
Node VMs€802/monthscales with hours
Node OS disks€66/monthscales with hours (the VMSS go to zero)
Saving~€546/month, −63%
Data disks (14 PVCs)€141/monthunchanged
Managed databases~€35/monthunchanged
Public IPs€6/monthunchanged
Control plane€0 (Free tier)€0

The window is Monday to Friday, 07:30 to 19:30. Tell the client about the fixed items before promising figures: stopping the cluster does not mean stopping the bill.

Why Azure Automation and not a CronJob

The deciding requirement is daylight saving time. Azure Automation schedules handle it themselves and support weekly recurrence by weekday out of the box: 07:30 in Rome stays 07:30 in winter and in summer, with no application logic.

  • A CronJob inside the cluster is out from the start: it cannot switch on the cluster it runs in.
  • Container Apps Jobs: cron is UTC only, so you fix daylight saving by hand twice a year.
  • Logic Apps: cheaper, but state checks, retries and structured logs become a chain of actions that is hard to version.
  • Azure Functions: a storage account plus an app, which means more moving parts for the same result.

Permissions: three actions, not Contributor

The role usually granted for this job is Azure Kubernetes Service Contributor, but it includes managedClusters/delete. An automation that runs unattended at 19:30 must not be able to delete the cluster.

I defined a custom role with only the three actions the runbook calls, scoped to the single cluster and assigned to the Automation Account’s managed identity. There are no secrets and no service principal to rotate.

resource "azurerm_role_definition" "aks_power_operator" {
  name        = "AKS Power State Operator"
  scope       = azurerm_kubernetes_cluster.aks.id

  permissions {
    actions = [
      "Microsoft.ContainerService/managedClusters/read",
      "Microsoft.ContainerService/managedClusters/start/action",
      "Microsoft.ContainerService/managedClusters/stop/action",
    ]
  }
  assignable_scopes = [azurerm_kubernetes_cluster.aks.id]
}

resource "azurerm_role_assignment" "scheduler_power" {
  scope              = azurerm_kubernetes_cluster.aks.id
  role_definition_id = azurerm_role_definition.aks_power_operator.role_definition_resource_id
  principal_id       = azurerm_automation_account.scheduler.identity[0].principal_id
}

An idempotent runbook, with one dependency fewer

The runbook calls the ARM API with Invoke-AzRestMethod rather than Start-AzAksCluster. The reason: Az.Accounts is always present in an Automation Account, while Az.Aks has to be imported and kept up to date. One dependency fewer is one thing fewer to break at 7:30 am, when nobody is watching.

  • It reads the state before acting: if the cluster is already where it should be, it exits with no-op.
  • If ARM already has an operation running it does not queue another (skipped-busy); the next run will handle it.
  • It retries only on transient errors (409, 429, 5xx), with backoff. A 403 does not get better on retry.
  • It writes one JSON line per event: readable by eye, filterable with jq and ready for Log Analytics.
$before = Get-PowerState
if ($before.Power -eq $targetState) { return }            # no-op: already there
if ($before.Provisioning -notin 'Succeeded','Failed','Canceled') {
    return                                                 # skipped-busy: ARM is working
}
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
    $r = Invoke-AzRestMethod -Method POST -Path "$BaseUri/$verb?api-version=2024-09-01"
    if ($r.StatusCode -in 200, 202) { break }
    # 409 conflict, 429 throttling, 5xx: transient. Anything else: stop retrying.
    if ($r.StatusCode -notin 409, 429 -and $r.StatusCode -lt 500) { throw $r.Content }
    Start-Sleep -Seconds ($RetryDelaySeconds * $attempt)
}

Measure the start-up, do not estimate it

I had estimated 15-25 minutes. Then I ran a real stop/start and timed every phase.

PhaseTime
Full shutdown2 min 40 s
Azure reports the cluster Running4 min 44 s
Istio ingress answers (503 on the APIs)4 min 56 s
First application API alive9 min 1 s
MinIO ready (1.9 million objects)20 min 50 s
Starting state restored24 min 42 s

Azure reports the cluster running in under five minutes. Measure only that and you conclude “five minutes” and are wrong by a factor of five. The bottleneck is MinIO’s metadata initialisation: almost 21 minutes for 1.9 million objects and 3.9 million versions. A tenant with eight thousand objects was ready at once.

Start-up time therefore depends on the data, not the VMs, and grows with it, so it has to be measured again. That is why the cluster starts at 07:30 and the system is usable at around 07:55. It is a deliberate choice that favours the saving over availability at dawn.

The test did no damage. The 14 disks detached and reattached cleanly, and the before/after comparison on MinIO is identical: drives, buckets, objects and versions.

Three Terraform and Azure traps

  1. runbook_type = "PowerShell72" recreates the runbook on every apply and runs it on PowerShell 5.1. It is a known azurerm provider defect (issue #31841). The correct form is runbook_type = "PowerShell" plus runtime_environment_name = "PowerShell-7.2". I only caught it because the plan after the apply was not clean.
  2. Job schedule parameter keys must be lower case. The API normalises them, and in camelCase the job fails with “parameter not found” only on its first scheduled run.
  3. Write the time zone as an IANA name (Europe/Rome), not the Windows name the docs suggest, or the schedule falls back to UTC and loses daylight saving. Also, start_time only describes the first occurrence. ignore_changes avoids a perpetual diff but makes the time impossible to change, unless you tie the replacement to its value.
resource "terraform_data" "stop_time" {
  input = "${var.stop_first_date}|${var.stop_local_time}|${var.timezone}"
}

resource "azurerm_automation_schedule" "aks_stop" {
  frequency  = "Week"
  interval   = 1
  week_days  = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
  timezone   = "Europe/Rome"   # IANA name, not "W. Europe Standard Time"
  start_time = "${var.stop_first_date}T19:30:00+02:00"
  # ...
  lifecycle {
    ignore_changes       = [start_time]                  # Azure computes the next runs
    replace_triggered_by = [terraform_data.stop_time]    # but a new time still applies
  }
}

What a cluster that restarts every morning reveals

A cluster that never restarts hides its start-up defects. One that restarts every day lines them up.

  • Two services reached storage through the public hostname: traffic left the cluster and came back through DNS, load balancer, ingress and TLS, while the internal service sat right there. That is free fragility on a critical path.
  • One service, if storage was not ready, died instead of waiting. Kubernetes restarted it with exponential backoff, so the later storage was, the longer the wait. It settles in the end, but every morning the logs fill with errors that look like outages.
  • An alarm was needed: a CronJob checks storage and the public API and, if something does not answer, fails and turns the application Degraded in ArgoCD. The alarm shows up where people already look, with no extra service.

The interesting part was the alarm itself. A Job whose pod cannot start never fails: it stays active, and with concurrencyPolicy: Forbid it blocks every later check too. One configuration error would have silenced the alarm indefinitely. activeDeadlineSeconds turns that into a visible failure. An alarm must go off even when the fault is its own.

The risks that remain

  • Region capacity. Microsoft warns that a stopped cluster may fail to start if the region is short of capacity. There is no cheap mitigation: it is a risk to accept knowingly, and I wrote it down.
  • Disks. You go from zero to about 250 detach/reattach cycles a year. Stopping drains the nodes, so the shutdown is orderly, but a storage alarm becomes a prerequisite, not a nice-to-have.
  • Rollback. The automation adds resources and does not modify the cluster. It is switched off with one Terraform flag and an apply.

The checklist

  1. Separate variable and fixed costs before promising a figure.
  2. Pick a scheduler that handles daylight saving time.
  3. Least privilege and a managed identity: no credentials.
  4. An idempotent runbook that retries only transient errors.
  5. Time a real stop/start until the service is ready, not until Azure says Running.
  6. Arm the stop before the start: if the first stop fails the cluster simply stays on and nothing breaks. The worst case only comes after its rehearsal.
  7. Add an alarm that notices its own failures too.

Does your cluster stay on when nobody is using it? A Kubernetes Health Check tells you how much you can save and what you risk, with measured numbers.


Leave a Reply

Your email address will not be published. Required fields are marked *