Kubernetes · FinOps

One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling

A shared workflow registers clusters and applies autoscaling policy, parameterised by environment, HA role and state suffix: spot in lower, on-demand in upper.

  • CAST AI
  • Terraform
  • GitHub Actions
  • Helm
  • Vault
  • TFLint
  • Checkov

// Why this matters

A reusable GitHub Actions Terraform plan/apply workflow is the cheapest way to make cluster cost policy consistent. Node scaling and cost tuning has to be identical across many clusters and two environments, yet each cluster differs in small ways: lower runs on spot capacity, upper on on-demand; some clusters are the secondary half of an HA pair; some have local accounts disabled so authentication differs.

If each of those variants gets its own copy of the workflow, the copies drift. One gets the new lint step, another keeps the old backend template, a third forgets the exit-code gate and applies on no changes. Over a year, the cost policy you thought you had everywhere exists in some of the places.

This post shows the single-workflow pattern used for the autoscaling stage of From Form to Running Cluster: Self-Service Team Onboarding. It generalises to any Terraform root that has to be applied to many similar targets.

// The problem

Cost optimisation for Kubernetes is only real if it is applied to every cluster the same way and kept applied. A cluster that skipped the autoscaler registration runs fixed-size on-demand nodes indefinitely. A cluster whose policy was edited by hand drifts from the rest. Both are invisible until the cloud bill arrives.

The pipeline-side problem is duplication. Teams and customers, lower and upper, HA primary and secondary give you at least eight combinations. Each needs federated auth, a templated backend, lint, security scan, a plan, a review gate, and an apply of exactly the reviewed plan. Writing that eight times is how an apply ends up re-planning (and applying something nobody reviewed).

Finally the stage must be re-runnable on its own and chain onward. It is dispatched by the previous stage, may be dispatched by hand, and on a real apply must dispatch the next stage (see Who Deploys the Deployer? Terraform-Bootstrapped FluxCD) without doing so on a no-op.

// The solution

The design is one reusable workflow and thin wrappers. The reusable workflow declares workflow_call inputs for everything that varies (work directory, environment, runner, action, state suffix, secondary flag, auth method, scan toggle) and two jobs. The wrappers, one per estate (team, customer, lower, upper, HA), contain no logic beyond resolving which environments to run, checking the stage's required flag in Vault, and fanning out a matrix of jobs with paired skip jobs.

The plan job does all the hygiene in a fixed order: federated auth, templated backend (substituting customer name, bucket and state suffix with sed), terraform fmt, init, validate, TFLint, Checkov, then plan -detailed-exitcode -out=plan. The exit code becomes skip_apply: 0 means skip, 2 means apply, 1 fails. It writes a markdown summary to the job summary and uploads both the summary and the raw plan file.

The apply job is gated three ways: the plan said there were changes, the requested action includes apply, and the protected environment reviewer approves. It downloads the raw plan artifact and runs terraform apply on it, so there is no second plan. State separation for HA is a suffix appended to the backend prefix; an IS_SECONDARY_REGION flag adjusts behaviour such as keeping the evictor off on the standby.

Policy lives in Vault, not in the workflow. The Terraform root reads the team or customer's values and builds the autoscaler configuration: spot or on-demand by environment, a floor of two CPU cores with a Vault-configurable ceiling, per-node minimums that exclude tiny SKUs, evictor and rotation schedule keys with documented defaults. I rejected copying the workflow per estate (drift) and a composite action (it cannot own jobs, environments or approval), and accepted that the reusable workflow needs a long input list.

How it flows flow1. Wrapper prepare → 2. Matrix of jobs → 3. Plan job → 4. Plan artifact → 5. Gate: changes only → 6. Apply or destroy → 7. Chain onward01Wrapper prepare02Matrix of jobs03Plan job04Plan artifact05 · GATEGate: changes only06Apply or destroy07Chain onward
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Wrapper preparedetermine environments and subscriptions; check the required flag
  2. Matrix of jobslower, upper, lower-secondary, upper-secondary, with paired skip jobs
  3. Plan jobfederated auth, templated backend with state suffix, fmt, init, validate, lint, scan
  4. Plan artifactmarkdown summary and raw plan uploaded; optional chat notification
  5. Gate: changes only gateapply runs only if the plan has changes and the action allows
  6. Apply or destroythe exact saved plan is applied
  7. Chain onwardTerraform dispatches the GitOps bootstrap
WrappersTeam lower/upperCustomer lower/upperHA primary/secondaryReusable workflowPlan jobGated apply jobSkip-flag outputsTerraform rootReads Vault keysBuilds policyDispatches next stagePolicy dataSpot vs on-demandLimits and evictorRotation schedule
Wrappers over one reusable workflow. Variation is input data; behaviour lives in exactly one place.
Plan job to apply job flow1. Auth → 2. Template backend → 3. Lint and scan → 4. Plan → 5. Gate: changes only → 6. Review → 7. Apply → 8. Chain01Auth02Template backend03Lint and scan04Plan05 · GATEGate: changes only06Review07Apply08Chain
Plan job to apply job. The exit code becomes a skip flag; the saved plan is applied verbatim.
  1. AuthOIDC to cloud and state bucket
  2. Template backendcustomer, bucket, state suffix
  3. Lint and scanfmt, validate, TFLint, Checkov
  4. Plandetailed-exitcode, out=plan
  5. Gate: changes only gateexit 2 and action includes apply
  6. Reviewprotected environment approval
  7. Applyterraform apply of the saved plan
  8. Chaindispatch GitOps bootstrap on real apply

// Before you start

  • GitHub Actions with reusable workflows enabled, a protected environment per cluster environment, and runners with network line of sight to the cluster API.
  • Terraform 1.9+, TFLint and Checkov available in CI; a remote backend bucket with a per-stage state prefix.
  • A Vault with per-cluster configuration keys (see Vault as the Control Plane: A Five-Tier Key Model with Locking), and an autoscaler account with an API key stored as a repository secret.
  • Cloud OIDC federation for CI, plus kubelogin on the runner if clusters use RBAC-only authentication.
  • Familiarity with workflow_call inputs and secrets, and needs.<job>.outputs.

// Step-by-step implementation

  1. 01 Declare the reusable workflow interface

    Start with the contract. Every axis of variation becomes an input with a safe default so that wrappers only specify what differs. Secrets are declared explicitly (reusable workflows do not inherit unless the caller passes secrets: inherit), and the concurrency group includes the state suffix so a primary and a secondary run in parallel but two runs of the same cluster serialise.

    Booleans that gate behaviour (APPLY_ON_NO_CHANGES, TERRAFORM_DESTROY, ENABLE_SECURITY_SCAN) are typed booleans; the secondary flag is a string because it is also fed into the Terraform environment.

  2. 02 Template the backend so one root serves many clusters

    The Terraform root contains placeholders in backend.tf, and the workflow substitutes them. The state key is <customer>/<stage><suffix>, which is how the HA secondary gets its own state without a second copy of the root. A tfvars template rendered with envsubst passes runtime values (subscription, tokens) without committing them.

    Keep the substitution deterministic and cheap to audit: three sed lines and one envsubst. Print the rendered backend (never the tfvars, which can contain tokens) so a failed run shows which state it targeted.

  3. 03 Write the plan job: hygiene first, then the exit-code gate

    Order the plan job so cheap failures come first: format, init, validate, lint. Run Checkov with continue-on-error: true initially and upload the JSON; tighten later once you know the noise level. Then plan with -detailed-exitcode under set +e, capture the code, and translate it.

    Handle the destroy variant in the same step by switching on TERRAFORM_DESTROY: a plan -destroy still writes a plan file and the same exit code semantics apply, so the apply job stays identical for builds and teardowns (the offboarding workflow in Demolition in Dependency Order: Safe, Re-runnable Offboarding reuses this).

  4. 04 Write the apply job: gated, environment-bound, saved-plan only

    The apply job has one if that combines three facts: the plan reported changes, the requested action includes apply or destroy, and the plan job did not fail. It binds to the same protected environment, so for upper the reviewers approve here. It downloads the artifact and applies it. There is no terraform plan in this job on purpose.

    Re-run init in the apply job (state backend and providers are not in the artifact) but with the identical rendered backend. If the state changed between plan and apply, Terraform refuses the stale plan, which is exactly the safety you want.

  5. 05 Handle clusters with local accounts disabled and the HA secondary

    Clusters that disable local accounts cannot use the admin kubeconfig, so authentication is an input. When it is azure, the job installs kubelogin and converts the kubeconfig to use the federated identity; otherwise it pulls the admin credentials. Do this in one conditional step before plan so the Kubernetes and Helm providers have working credentials in both jobs.

    The HA secondary differs in two ways. Its state is separate (the suffix), and it runs a different Vault key suffix so the root reads the secondary cluster's id and subnet. The secondary also disables the evictor and other disruptive features by default, because disrupting the standby while the primary serves traffic is rarely what anyone intends.

  6. 06 Express cost policy as Vault-driven Terraform inputs

    The root builds the autoscaler configuration from keys with documented defaults. Lower environments set on_demand = false so nodes are spot; upper sets it true. A cluster-wide CPU floor of two cores and a ceiling from a Vault key bound total spend, and a per-node minimum excludes very small SKUs whose overhead (for example from a network add-on) leaves too little room for pods.

    Evictor and node rotation are optional and read with try(): the evictor repacks pods and removes underused nodes; a weekly rotation keeps nodes on current images. An absent key keeps the module default, so changing policy is a Vault edit plus a plan, not a code change. Dispatch the next stage only after the cluster-registration resource exists.

  7. 07 Write the thin wrappers with matrix legs and paired skip jobs

    A wrapper has a prepare job that works out which environments to run and whether the stage is required (read from Vault), then one job per cluster shape: lower, upper, lower-secondary, upper-secondary. Each calls the reusable workflow with its own suffix and flags. Add a paired skip job for each so the run graph says why a leg did not run.

    Keep wrappers dull. If you find yourself adding logic to one, ask whether it belongs in the reusable workflow as an input instead.

// How to verify it works

  • Dispatch the wrapper with Plan for a lower team: the plan job summary renders and no apply job starts.
  • Re-dispatch with Plan & Apply when nothing changed: the plan exits 0, skip_apply is true, and no downstream stage is dispatched.
  • On a real apply, the apply job logs Apply complete, and a new run of the GitOps bootstrap workflow appears in the Actions list.
  • The autoscaler dashboard shows the cluster registered with the expected policy (spot in lower), and kubectl get nodes -L <spot-label> shows spot nodes there.
  • Dispatch the secondary leg; confirm a different state prefix (...-secondary) was used in the rendered backend log.

// Design decisions and trade-offs

  • Applying the saved plan artifact guarantees that what was reviewed is what runs.
  • A state-suffix input separates HA secondary state; an is-secondary flag adjusts behaviour such as the evictor.
  • Auth method is an input (admin or RBAC) for clusters with local accounts disabled.
  • Evictor, rotation schedule and zones are all Vault-driven with documented defaults.
  • The earlier GCP generation did the same with a read-only mode and a GPU toggle.

// Pitfalls and lessons learned

  • Re-planning in the apply job. It can apply a different change set from the one reviewed; always download and apply the saved plan.
  • Treating exit code 2 as failure. With -detailed-exitcode 2 means changes present; only 1 is an error.
  • Long-lived plan artifacts. A plan is bound to the state it was created against; keep retention short and let Terraform reject stale plans.
  • Sharing state between primary and secondary. Always pass a state suffix; a shared state makes the second apply plan to destroy the first.
  • Forgetting secrets: inherit (or explicit secrets) when calling a reusable workflow; the job fails with an empty credential rather than a clear message.
  • Tiny node SKUs under spot. System add-ons can consume most of a 2-vCPU node; enforce a per-node minimum.
  • Dispatching the next stage from the secondary. It must be suppressed or GitOps bootstrap runs twice.

// Frequently asked questions

How do I create a reusable GitHub Actions workflow for Terraform plan and apply?

Define on: workflow_call with inputs and secrets, a plan job that uploads the plan file and exposes a skip_apply output, and an apply job that depends on it, downloads the artifact and applies it. Call it from thin wrapper workflows.

Why apply a saved plan file instead of running apply directly?

It guarantees the reviewed changes are exactly what runs, and Terraform rejects the plan if the state moved in between.

How do I give an HA secondary its own Terraform state without copying the root?

Template the backend prefix with a state suffix input such as -secondary, and pass an is-secondary flag so the module reads suffixed Vault keys.

Should lower environments use spot instances?

Usually yes: interruptions are tolerable and savings are largest. Keep upper on on-demand, and use an evictor and rotation schedule with documented defaults.

Why not use a composite action for this?

Composite actions cannot define jobs, environments or approval gates, so the protected-environment review step would have to live in every caller.

// The outcome

Documented limits such as 2 to 200 CPU cores autoscaling, with one workflow serving every cluster shape.

// Where to take it next

// Keep reading