Skip to content
Tech Interview Prep
Technical interview guide

GitOps

Using a Git repository as the single source of truth for infrastructure and deployment state.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: OpenGitOps, Argo CD, Flux, Kubernetes, and Sigstore guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-9

Design repository structure for a large GitOps estate.

Answer

The 90-second answer

Assume one platform team, roughly 40 tenant teams, three environments, a few hundred clusters, and Argo CD as the reconciler. Flux changes the mechanics below, not the boundaries.

Split into three repo classes, each with one owner:

  • platform/: CRDs, controllers, cluster add-ons. Platform owns it, platform reviews it.
  • tenants/<team>/: that team's workloads, one directory per environment. The team owns it.
  • envs/<cluster>/: thin. It names which tenant directories and which platform revision this cluster runs. Whoever owns the cluster owns it.

Reusable bases live in a tagged repo or platform/modules; overlays are per-environment patches.

Why overlays stay small. Kustomize applies strategic-merge patches in order, so every field an overlay restates silently shadows the base. A base change then never reaches that environment, and nobody notices until an incident. Keep overlays to replicas, resource limits, hostnames and image tags: the things that genuinely differ per environment.

Why pinning matters. A remote base written as github.com/org/base//k8s?ref=v1.4.2 is fetched at render time. Drop the ?ref and an upstream force-push changes what your cluster runs with no commit in your repo: the audit trail is gone. Same story for Helm: Chart.lock pins the chart digest, and without it helm dependency update can move you.

Reconciliation scale. Argo CD's default resync is 180 seconds (timeout.reconciliation in argocd-cm). At 200 clusters × 40 tenants that is 8,000 Applications, and hand-writing them does not survive. Generate them with an ApplicationSet cluster generator. The repo-server keeps a local clone per repository and fetches on each refresh, so a repo with heavy binary history makes every refresh slower for every Application that points at it.

Failure modes and how you catch them.

  • Duplicate field ownership. Two Applications both set spec.replicas. Symptom: the Application flaps OutOfSync on every resync and the live object alternates between values. Detect it with argocd app history showing alternating revisions, or alert on sync count per Application per hour.
  • Unpinned base. Symptom is a diff with no corresponding commit. Detect it in CI: render kustomize build and fail the build if the output hash differs from the committed manifest.
  • Prune on the wrong path. syncPolicy.automated.prune: true on a namespace-scoped Application deletes anything not in Git. Run argocd app diff --local in CI before merge, and put argocd.argoproj.io/sync-options: Prune=false on shared CRDs.

What would change the decision. If tenants cannot be trusted with cluster-scoped resources, split by cluster rather than by team, and give each tenant an AppProject whose sourceRepos is restricted to their own directory. On Flux the boundaries hold, but tenancy is enforced differently: --no-cross-namespace-refs and --no-remote-bases on kustomize-controller, plus spec.serviceAccountName on each Kustomization so it reconciles as the tenant, not as the controller.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you validate Helm or Kustomize output before reconciliation?

Answer

Pin down what "the output" means before listing checks: the exact set of objects the controller will send to the API server, rendered by the controller's renderer at the controller's versions. Reading the chart in review is not that: most merge-time surprises are version or cluster drift, not YAML syntax.

Assumptions I'd state out loud: Git is the only writer; Argo CD or Flux applies; CI has a kubeconfig for a staging cluster on the same Kubernetes minor as production, with the same CRDs and admission webhooks installed. If the CRDs differ, every server-side result describes the wrong cluster. Also worth saying: controllers bundle their own renderer (Argo CD pins specific Helm and kustomize versions per release), so CI has to run those same versions or it is validating a different tool.

Four gates, cheapest first.

1. Pin the inputs and render. Chart version by digest, remote kustomize bases by commit SHA: a branch ref is mutable, and a render is only reproducible if its input is. helm template release chart -f values.yaml --kube-version 1.29.0 so .Capabilities.* branches resolve for the target, not for whatever cluster CI points at. Caveat that bites: with no cluster connection lookup returns empty, so a template guarded on cluster state renders its "not found" path. A different object graph from what helm upgrade will produce.

2. Static checks, no cluster. kubeconform -strict -kubernetes-version 1.29.0 -ignore-missing-schemas against a schema set for the target version (kubectl's built-in client schema is only as current as your kubectl binary, so pin that too). pluto detect-files -d . for kinds removed in the target version. conftest test -p policy/ rendered.yaml, or kyverno apply policy.yaml --resource rendered.yaml, for what schemas cannot express: hostPath mounts, privileged containers, a ClusterRoleBinding to cluster-admin, missing requests and limits, :latest tags. Plus the check people don't ship: a set difference of (apiVersion, kind, namespace, name) tuples between the previous render and this one. That is the only thing that catches "someone renamed the StatefulSet".

3. Server-side dry run. kubectl apply --dry-run=server -f rendered.yaml (or Helm 3.13+ --dry-run=server). This is the cheapest check that runs defaulting and both webhook phases. helm template --validate is weaker: it validates against the cluster's OpenAPI schemas but does not run admission.

4. Delta against live. kubectl diff -f rendered.yaml: exit 0 clean, 1 differences, above 1 means the tooling failed, which is a red build and never a pass. With Helm, the helm-diff plugin's helm diff upgrade shows the same with hook objects separated.

gatewhat it catcheswhat it misses
1 renderversion drift, values branchinganything cluster-dependent
2 staticremoved APIs, policy breaches, malformed schemadefaulting, webhooks
3 server dry runimmutable-field rejects, webhook denial, bad CRsdeletes: a dry run never prunes
4 deltadeletes, identity changes, rewritten fieldsintent

Client-side versus server-side is the real trade-off. Client-side is seconds, needs no cluster, and works on PRs from forks; server-side runs admission and defaulting but needs prod's CRDs and webhooks and costs one write attempt per object: for a 40-service repo rendering roughly 480 documents, that is 480 admission calls, so I run gates 1 and 2 on every push and 3 and 4 on the merge queue. Storing the rendered artifact buys forensics, but only if the render carries references rather than plaintext secret values, which is an argument for External Secrets or Sealed Secrets upstream of rendering.

Detection signals matter more than the category. A renamed StatefulSet with pruning enabled shows up as a minus-block in gate 4 and as an old tuple in the key-set diff; the cost is a fresh empty PVC and the old one gone unless something carries helm.sh/resource-policy: keep. An immutable-field change (Deployment spec.selector, StatefulSet spec.volumeClaimTemplates, Service clusterIP) comes back as a 422 from gate 3, and without gate 3 it halts the sync on the first object in the wave and stalls everything behind it. A CRD shipped in the same render as its CR fails server-side dry run with no matches for kind ... in version ..., because a dry run does not persist the CRD; that chart is either split or only ever checked client-side. Narrowing a CRD's structural schema is invisible in the diff: the apiserver prunes the dropped fields on the next write of every CR, so you have to dry-run one representative CR and read back the result.

What would change my answer: if prod's CRDs and webhooks cannot be reproduced in CI, I stop treating CI as authoritative, keep gates 1 and 2 plus the tuple diff, and make the controller's dry run the gate against a staging overlay. If the controller does not prune, the whole deletion class mostly disappears and gate 4 drops to cheap insurance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Define observability for a GitOps control loop.

Answer

Core answer

Observability for a GitOps control loop means telemetry that lets you answer, without reading controller logs, three questions: did the desired state get fetched and verified, did it render to the exact bytes that were applied, and does live state still match, and who changed it. "Synced" and "Healthy" are the controller's own scoped judgment, so you instrument the stages around them rather than trusting the summary.

The loop and where it breaks

Every GitOps controller runs the same stages: fetch source → verify → render → diff → apply → prune → assess health. Each stage fails differently, so each needs its own signal.

StageSignal (Flux / Argo CD)Failure it catches
Fetchgotk_reconcile_condition{type="Ready"} on GitRepository; argocd_git_request_total{request_type="fetch"}Repo unreachable, auth expired
Verifysource-controller checksum / spec.verify (cosign)Tampered or unsigned artifact
Renderkustomize/helm build errors; argocd_app_reconcile durationBad overlay, missing value
Diffargocd_app_info{sync_status}; Flux gotk_resource_infoDrift between desired and live
Applycontroller_runtime_reconcile_total{result} and ..._errors_totalApply rejected, webhook denied
Prunedeletion count per reconcileBlast radius from a bad commit
Healthargocd_app_info{health_status}; Flux Ready conditionWorkload not converging

Artefacts

Flux exposes gotk_reconcile_condition{kind,name,namespace,type,status} and gotk_suspend_status, plus the controller-runtime set (controller_runtime_reconcile_total, _errors_total, _time_seconds) on every controller. Argo CD exposes argocd_app_info with sync_status/health_status labels, argocd_app_sync_total{phase}, and argocd_app_reconcile as a duration histogram.

Staleness arithmetic: Argo CD's default resync is 180 s (--app-resync). If you page on "not synced for 15 min," that is five missed cycles: long enough to survive a repo-server restart, short enough to catch a dead webhook. Alert on time() - argocd_app_info{...} exceeding 900 s, not on a single failed reconcile.

PROMQL
# stale target: no successful sync in 15m
time() - max by (name,namespace) (
  argocd_app_info{sync_status="Synced"}
) > 900

Trade-offs and when not to

Per-resource metrics give precise drift detection but explode cardinality: a 5,000-resource app is 5,000 series per label set; aggregate at the app level and keep per-resource only for namespaces you actually page on. Flux's per-CRD model gives you a Ready condition per GitRepository/Kustomization, which is finer-grained than Argo CD's app-level status but means you must join conditions yourself. Push-based events (Flux notification-controller, Argo CD notifications) are cheap and carry the commit SHA, but they are lossy: never make them the only source of truth.

Failure modes

  • Stale target: controller can't reach the repo; every app shows the last good revision. Detect via source Ready=False plus revision age, not app health.
  • Repeated failure: same error every cycle. Alert on increase(controller_runtime_reconcile_errors_total[10m]) > 3, grouped by controller, so one broken repo doesn't page per app.
  • Controller saturation: workqueue depth and reconcile duration climbing; controller_runtime_reconcile_time_seconds p99 rising means the loop is falling behind its interval.
  • Unknown writers: drift with no corresponding commit. Compare the live object's managedFields manager against the controller's field manager.
  • Large deletion sets: alert when a single reconcile prunes more than N resources; that is the signature of a bad commit or a wrong path.

Finally, sample effective state independently (a periodic read of live objects, not the controller's cache) and ship audit logs to append-only storage: the controller's own view is exactly what you are trying to verify.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Model CRD, controller, and custom-resource ordering.

Answer

Core answer

Order: CRD → wait Established → controller → wait ready → CRs. Teardown is the reverse, CRD last. Each step's API surface only exists after the previous one, and getting it wrong doesn't produce a slow deploy: it produces a stuck object.

#ApplyWait on
1CustomResourceDefinition (apiextensions.k8s.io/v1)kubectl wait --for=condition=Established --timeout=60s crd/widgets.shop.example.com
2controller Deployment + RBACkubectl rollout status deploy/widget-controller, with a readiness probe that does not depend on the Widget informer
3Widget CRs—

Why those waits

Established is set by the apiextensions controller inside kube-apiserver, not by your tooling. It flips True with reason InitialNamesAccepted once the group/version is served and the structural schema is accepted. Before that, applying a Widget fails with no matches for kind "Widget" in version "shop.example.com/v1". Waiting on the condition is a real API read; sleep 30 is a guess that is too short on a cold control plane and wasted on a warm one.

The controller goes second because its informer LISTs the Widget resource. Before the CRD exists that LIST 404s, the reflector logs the server could not find the requested resource and retries with backoff. It self-heals once the CRD appears, unless readiness is gated on informer cache sync, in which case the pod never goes Ready and a health-gated wave deadlocks. Gate the CRD→controller edge on the CRD's condition, not the controller's readiness.

CRs go last because the controller's finalizer is what lets deletion terminate. Creating a CR before the controller runs is harmless; deleting one in that window leaves it in Terminating forever.

Trace: deleting the CRD before the controller

Three Widgets exist, each with metadata.finalizers: [shop.example.com/cleanup]. The controller has already been uninstalled. kubectl delete crd widgets.shop.example.com:

  1. CRD gets metadata.deletionTimestamp.
  2. apiserver deletes all Widget instances. Each gets deletionTimestamp but is not removed: the finalizer is still there.
  3. CRD status.conditions gains type: Terminating, status: "True", reason: InstanceDeletionFailed.
  4. kubectl get crd widgets.shop.example.com shows a deletionTimestamp; kubectl get widgets -A shows three objects stuck in Terminating.

Recovery is reinstalling the controller so it drains the finalizers, or patching each CR to strip the finalizer, which skips whatever cleanup it was for. Alert on the Terminating condition.

Conversion webhooks

If the CRD serves v1alpha1 and v1 with storage: true on v1, a GET of a v1alpha1 Widget reads v1 from etcd and calls the conversion webhook. With no endpoints behind that Service you get failed calling webhook "convert.widgets.shop.example.com": service "widget-webhook" not found, but only for v1alpha1. Requests to v1 still succeed, so a suite that only exercises the storage version never notices. Watch apiserver 5xx per version, and refresh spec.conversion.webhook.clientConfig.caBundle when the serving cert rotates, or every non-storage-version request fails with x509. Changing which version is storage: true does not rewrite existing objects; they convert on read and rewrite on next write. StorageVersionMigration (storagemigration.k8s.io/v1alpha1, 1.30+) forces the rewrite.

Tooling

Helm's crds/ directory installs before templates and is never upgraded or deleted by helm upgrade/helm uninstall: safe for step 1, useless for schema changes, which need a separate chart or job. Argo CD orders with sync waves:

YAML
metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "-10"   # CRD; controller "0"; CRs "10"
    # CRs in the same sync as their CRD also need:
    argocd.argoproj.io/sync-options: SkipDryRunOnMissingResource=true

Failure modes

SymptomCauseDetection
no matches for kind "Widget"CR applied before CRDapply error, CI fails
reflector logs could not find the requested resourcecontroller before CRDcontroller logs; recovers on retry
CRs stuck Terminating, CRD condition Terminating/InstanceDeletionFailedCRD deleted with finalizers and no controllerkubectl get crd deletionTimestamp
500s on v1alpha1 onlyconversion webhook down or stale caBundleapiserver logs, per-version error rate

When the simple thing is fine

If the controller creates its own CRs and nothing else does, you only need CRD → controller; the CR step disappears. One Helm chart with crds/ plus templates is fine while the CRD schema never changes. The moment it does, helm upgrade silently skips it and you find out when a CR is rejected or a field is pruned on write.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Build a test strategy for a GitOps application definition.

Answer

I'd start by pinning down the shape: I'll assume Argo CD managing a Helm chart or Kustomize overlay, the Application CR itself in Git, and CI running on every PR. The strategy is three tiers, each gated on what it costs to run and what only it can catch: static checks in seconds on every commit, a full reconcile lifecycle in a disposable cluster on every PR, and a canary of the exact rendered artifact before production sees it.

Tier 1: static, seconds, every commit. Render with helm template or kustomize build, then validate the output with kubeconform -strict -summary, pointing -schema-location at your CRD schemas so custom resources aren't silently skipped. Run conftest test with Rego for policy: no :latest tags, resource limits present, no cluster-admin bindings. For determinism, render twice and diff: that catches map-ordering and injected timestamps that would make every sync look dirty. This tier catches typos, schema drift and policy violations. It cannot catch anything that needs a live API server, which is the whole reason tier 2 exists.

Tier 2: disposable cluster, minutes, every PR. Spin up kind or k3d, install Argo CD, point it at the branch. Then walk the lifecycle, and each test earns its place:

testwhat it catches
fresh installapp never reaches Synced/Healthy
no-op re-syncnon-idempotent hooks, generated fields
upgrade from previous releaseimmutable field changes (Deployment selector)
manual drift + self-healreconcile actually reverts, within the sync interval
source outageapp holds last-known-good, reports Unknown not OutOfSync
invalid rendersync fails cleanly, no half-apply
prune on renameold resource deleted, not orphaned
empty outputprune doesn't wipe the namespace

Tier 3: canary. Promote the exact digest that passed tier 2 into a representative environment, ideally via Argo Rollouts with an analysis step. Assert service outcomes (error rate, p99 latency), security (image signature, no new egress), and data (migration ran, no loss). Correlate the sync revision to the Git SHA so the audit trail is real.

The trade-off is explicit: if the app is a single ConfigMap with no hooks, tier 2 is overkill. Tier 1 plus a canary is enough. If it has CRDs, finalizers or migrations, tier 2 is mandatory, because those only fail against a live API server.

One failure mode worth naming: prune with a stuck finalizer. The resource hangs in Terminating and sync reports Progressing forever. Detect it by asserting the app reaches Synced within a timeout, not by trusting that the command exited 0.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How should GitOps handle secrets?

Answer

The first two minutes

Plaintext secrets never go in Git, and the manifest that reaches the cluster should carry a reference, not a value. Three patterns, in the order I'd reach for them.

  1. External store plus a reconciler. Vault or AWS Secrets Manager holds the value; External Secrets Operator (ESO) or the Secrets Store CSI driver runs in the cluster and materialises it as a Kubernetes Secret or a mounted file. The repo holds nothing secret at all.
  2. Encrypted declaration in the repo. SOPS (age or a cloud KMS key) or Sealed Secrets: ciphertext in Git, decryption key held by the controller.
  3. Hand-injected plaintext. Not GitOps: no audit trail, no review, and it drifts the moment someone edits the Secret.

Why option 1 is the default

ESO is a controller, and the mechanism is what makes it work: it watches ExternalSecret objects, resolves the referenced store, calls the provider's API, and upserts a Kubernetes Secret. From that point RBAC applies to the Secret like any other object, and the Git commit contains only key and property names. Adding a new application secret is a reviewed pull request that changes a reference: the value never touches the repo, the PR diff, or CI logs.

The problem is that whatever authenticates to Vault is itself a credential. On EKS you delete it with IRSA: annotate the service account eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/payments-eso, the kubelet injects a projected token (AWS_ROLE_ARN, AWS_WEB_IDENTITY_TOKEN_FILE), and the SDK exchanges it through STS AssumeRoleWithWebIdentity. There is no static key to leak or rotate. GKE and AKS Workload Identity are the same shape.

Worked example

YAML
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata: {name: payments-db, namespace: payments}
spec:
  refreshInterval: 1h            # default is 1h; set it explicitly anyway
  secretStoreRef: {name: vault-backend, kind: ClusterSecretStore}
  target:
    name: payments-db
    creationPolicy: Owner        # default
    deletionPolicy: Retain       # default: keep the Secret if the store disappears
  data:
    - secretKey: password
      remoteRef: {key: payments/db, property: password}

Trace: ESO reads the object, resolves vault-backend, which holds the Vault address, KV mount and auth method, authenticated by IRSA, not a token in the cluster. Reads payments/db, and upserts Secret payments/payments-db with key password. Every refreshInterval it re-reads; if the value changed, pods mounting that Secret as a volume pick up the new bytes within roughly a minute (kubelet sync period, default 60s). Pods reading it as an environment variable do not: those need a restart, which is the argument for mounting files.

Trade-offs, and when encrypted-in-repo wins

patternwhere plaintext existsrotationwhat breaks
ESO / CSI + VaultVault, then pod memory (the CSI driver only creates a Secret if you opt in via secretObjects)write to Vault; next refreshstore unreachable: Retain keeps stale credentials running
SOPS + Flux / Argo CDcontroller memory at decryptre-encrypt and committhe cluster's decryption key is the blast radius
Sealed Secretscontroller memoryre-seal each secretcluster sealing key compromised means every SealedSecret
plaintext in GitGit history, permanentlyrotate, then rewrite historyalways

Flux decrypts SOPS natively (spec.decryption.provider: sops); Argo CD needs a plugin such as argocd-vault-plugin or KSOPS. Pick encrypted-in-repo when the cluster is air-gapped, there is no Vault, and you accept that the repo alone can rebuild the cluster. Sealed Secrets binds each ciphertext to one name and namespace (strict scope by default), so a SealedSecret leaked from one team's repo cannot be decrypted into another namespace; a leaked SOPS age key decrypts everything it was ever used for. If the store supports dynamic credentials, Vault's database engine, prefer a lease with a configured TTL over a static password you have to rotate by hand.

Failure modes worth naming

  • Store outage. With the default deletionPolicy: Retain the last good Secret survives, so pods keep serving on possibly-expired credentials instead of crash-looping. Alert on externalsecret_status_condition{condition="Ready",status="False"} and sync error counters, and rehearse a rotation while the store is reachable.
  • Rendered-secret leakage. argocd-vault-plugin substitutes placeholders server-side, so plaintext can surface in argocd app diff and the UI for anyone who can read the Application. Tighten that RBAC, or keep values out of the renderer entirely.
  • Namespace read access. A materialised Secret is readable by anyone with get secrets in that namespace. The CSI driver with no secretObjects avoids creating it.
  • Disaster recovery. Restoring only from Git gives you references, not values. Back up the store, and note that losing the cluster's sealing key makes every SealedSecret unrecoverable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you safely manage and sequence stateful database schema migrations in a GitOps reconciliation pipeline?

Answer

To safely execute schema migrations in GitOps, reconcile the operational impedance mismatch: GitOps reconcilers treat resources as declarative, idempotent, and infinitely retryable, whereas database schema changes are imperative, sequential, and state-mutating.

1. Decouple Schema Changes from Code via Expand/Contract

Never couple a breaking schema migration to an application rollout within a single Git commit. An atomic cutover across external state and stateless pods is impossible during rolling updates. Every change follows a two-phase release cycle:

  1. Expand: Apply additive, non-breaking schema changes (e.g., adding nullable columns, views, or new tables). Both $V_n$ and $V_{n+1}$ of the application run concurrently without errors.
  2. Contract: After the application deployment reaches healthy status and all legacy instances are terminated, run a secondary migration to enforce constraints (e.g., NOT NULL), drop deprecated columns, or remove temporary triggers.

2. Reconciliation Sequencing via Sync Phases and Waves

Using Argo CD sync phases (or equivalent pre-rollout job hooks), isolate the migration into an ephemeral batch/v1 Job orchestrated strictly prior to mutating the application Deployment.

YAML
apiVersion: batch/v1
kind: Job
metadata:
  name: orders-db-migrate-v102
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded
    argocd.argoproj.io/sync-wave: "0"
spec:
  backoffLimit: 1
  activeDeadlineSeconds: 300
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrator
          image: registry.internal/orders-migrator:v1.0.2
          command: ["flyway", "migrate"]
YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  annotations:
    argocd.argoproj.io/sync-wave: "1"
spec:
  # Evaluated and applied ONLY after wave 0 Job succeeds
  replicas: 10

3. Execution Mechanics and Failure Modes

Mechanism / PropertyConfigurationFailure Mode & Remediation
Hook ExecutionPreSync hook at wave 0If the migration fails, Argo CD halts the sync pipeline immediately. Wave 1 (Deployment) is never applied, preventing crashes on running pods.
Job RetriesbackoffLimit: 1, restartPolicy: NeverPrevents the reconciler from repeatedly executing a failed, non-transactional migration against a locked database engine.
Concurrency & LocksDDL transaction lock timeout (e.g., lock_timeout = '5s')DDL acquisition waiting behind long-running queries blocks downstream reads. A strict timeout aborts the Job rather than starving traffic.
Hook CleanupBeforeHookCreation,HookSucceededBeforeHookCreation ensures stale, failed migration Jobs from aborted syncs are pruned before the next attempt runs; HookSucceeded cleans sensitive logs.
Automated RollbackDo not invoke automatic down-migrationsAuto-rollback hooks attempting down-migrations on failed deployments risk dropping data. Revert by pushing a forward Git commit that safely adapts the state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design artifact promotion from staging to production.

Answer

The 90-second answer

Build the artifact once, in CI, and never again. The build produces an OCI image plus an SBOM and a signed provenance attestation: SLSA level 3, via docker buildx build --provenance=true or GitHub's actions/attest-build-provenance. Sign it with cosign; the signature binds the digest to the build identity. From then on every environment refers to the image by digest, registry.example.com/api@sha256:..., never by tag, because tags are mutable pointers and :v1.2.3 can be repointed after staging passed.

Staging deploys that digest and records evidence: test results, the SBOM, the attestation, the observed outcome. Production promotion is a reviewed change that selects the same digest and adds environment policy: replica counts, resource limits, feature flags. It is not a rebuild and not a tag move.

How the promotion works

GitOps makes this concrete. Each environment has an overlay holding the digest. Promotion is a pull request that changes one line in the production overlay from the old digest to the new one; Argo CD or Flux reconciles it. The PR carries the evidence links and a required reviewer approves. The admission controller, Kyverno or OPA Gatekeeper, verifies at apply time that the image is signed by the expected identity and referenced by digest. Anything else is rejected.

GateCheckTool
BuildProvenance + SBOM attachedbuildx / actions/attest
SignDigest signed by CI identitycosign
StagingTests pass, evidence recordedCI
AdmitSigned and digest-pinnedKyverno / Gatekeeper
RolloutError rate < 1%, p99 < 500 msArgo Rollouts + Prometheus

Rollout

Use Argo Rollouts canary: 5% for 5 minutes, 25% for 10 minutes, then 100%. An AnalysisTemplate queries Prometheus at each step; if the 5xx rate exceeds 1% or p99 latency exceeds 500 ms over the window, the rollout aborts and reverts to the previous ReplicaSet. Those thresholds come from your SLO, not from a blog: the point is that they are numbers you can defend.

Serialization

Only one promotion per service at a time. Two PRs touching the same digest field race, and the second merge silently reverts the first. Guard it with a GitHub environment that requires a reviewer, or a lock in the promotion controller keyed by service name. Detect a race by diffing the live digest against the merged PR.

Rollback vs roll-forward

The deciding question is whether the change is backward compatible with the previous version's data. If the release only added a nullable column, rollback is safe: revert the digest and the old code ignores the column. If it dropped or renamed a column, rollback breaks the old code and you must roll forward with a fix. That is why migrations use expand/contract: ship the expand migration in release N, the code that uses it in N+1, the contract (drop) in N+2. Then every single release is rollback-safe.

Failure modes

  • Tag drift: someone deploys :latest. Detect with an admission policy that rejects non-digest references; the cost is a blocked deploy, not an outage.
  • Registry garbage collection deletes the digest. Enable immutable tags and a retention policy; detect it when a rollback fails to pull.
  • External state drift: a migration ran, the app rolled back, the schema no longer matches. Detect via canary error rate; the cost is a manual forward-fix under incident pressure.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Retire a GitOps-managed application safely.

Answer

Core answer

First question back: is this a decommission or a migration? If a successor is taking over the same DNS name, database, or IAM role, you are cutting over, not retiring, and the plan is different. Assume full retirement: no successor, data carries a retention obligation, and the app owns a LoadBalancer, an IRSA role, and a StatefulSet with PVCs.

The safe retirement runs in three phases, and the reason is that a GitOps controller is a reconciliation loop that will undo you if you delete in the wrong order.

Phase 1: stop the loop. Do not delete the directory first. In Argo CD, add argocd.argoproj.io/sync-options: Prune=false to the Application (or switch the sync policy to manual) so removing manifests from Git does not trigger a prune mid-flight. In Flux, set spec.suspend: true on the Kustomization or HelmRelease. Now Git and the cluster can disagree without the controller acting on it.

Phase 2: drain, then delete in dependency order. Stop producers (CronJobs, queue consumers, webhooks) before consumers. Remove the Service and Ingress so traffic stops, then confirm the cloud load balancer is actually gone. Revoke external identities: the IRSA role, the Vault role, the OIDC client. Then delete the workload.

Phase 3: delete the controller object, then verify.

Two deletion paths, different blast radius:

  • Delete the Application/Kustomization object: its finalizer (resources-finalizer.argocd.argoproj.io, finalizers.fluxcd.io) makes the controller delete every resource it tracks. argocd app delete --cascade=false skips that and orphans everything.
  • Delete the manifests from Git: the controller prunes only resources it still tracks, and only if prune is on. Anything annotated Prune=false survives.
actioncontroller deletessurvives
argocd app delete (finalizer present)all tracked resourcesStatefulSet PVCs, IAM role, Vault secrets, DNS if ExternalDNS already stopped
argocd app delete --cascade=falsenothingeverything, now untracked
remove manifests from Git, prune onresources still trackedanything with Prune=false
kubectl delete nsnamespaced resourcescluster-scoped: CRDs, ClusterRole/Binding, PVs per reclaim policy

Failure modes and how to detect them

  • StatefulSet PVCs are not deleted with the StatefulSet. kubectl get pvc -n <ns> and check the cloud volume bill; a 100 GiB gp3 volume is roughly $8/month each and they accumulate silently.
  • Namespace stuck in Terminating: kubectl get ns <ns> -o jsonpath='{.status.conditions}' shows the finalizer holding it. kubernetes.io/pvc-protection keeps a PVC alive while any pod still mounts it.
  • ExternalDNS records orphan when the Service is deleted out-of-band. Check the TXT registry record for the hostname before assuming the record is gone.
  • External Secrets Operator deletionPolicy defaults to Retain: deleting the ExternalSecret leaves the secret in Vault or Secrets Manager. Set Delete only if policy permits.
  • IAM roles and security groups outlive the Service. They surface in cost and access reviews, not in kubectl get all.

Trade-offs. A bare argocd app delete --cascade with no plan is fine for an ephemeral preview environment: no persistent data, no external identity, no retention obligation, and a mistake costs one re-sync. It is wrong the moment any of those three exist. The deciding criteria are whether anything outside the cluster references this app (DNS, IAM, a consumer's config) and whether any data carries a retention or erasure obligation.

What would change this. If a successor is taking over, keep the identity and DNS and cut over instead. If data is under legal hold, this is a data-migration task before it is a deletion task.

Restoration window. Keep the last backup and leave the namespace suspended rather than deleted for 30 days; after that, deletion is irreversible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Set a safe drift and self-heal policy.

Answer

Assume GitOps on Kubernetes, Argo CD or Flux reconciling, and Git as the only sanctioned writer. A safe policy answers three questions in order: who owns each field, what the reconciler may do when it disagrees, and what a human does when the reconciler is wrong.

Ownership first. Read metadata.managedFields before writing any ignore rule: kubectl get deploy web -o yaml --show-managed-fields shows which manager owns which field. Fields owned by API-server defaulting or by another controller are not drift. Ignore them explicitly rather than letting the reconciler fight:

  • /spec/replicas on any Deployment with an HPA: the HPA owns it.
  • Service spec.clusterIP, spec.healthCheckNodePort: allocated by the API server.
  • metadata.creationTimestamp inside pod templates: defaulted.

In Argo CD:

YAML
ignoreDifferences:
  - group: apps
    kind: Deployment
    managedFieldsManagers: [horizontal-pod-autoscaler, cluster-autoscaler]
  - group: ""
    kind: Service
    jsonPointers: [/spec/clusterIP, /spec/healthCheckNodePort]

Flux applies server-side, so field ownership is already respected; the same conflict shows up as a field two managers both claim.

Enforcement tiers. Match the action to the consequence, not to the diff size.

DivergenceAction
Trusted, reversible, unauthorized (someone hand-edited a ConfigMap)auto-heal
Controller-owned or defaulted fieldignore
Externally owned (HPA, cert-manager, external-dns)detect-only
Destructive (PVC, StatefulSet volume, finalizer)detect-only, alert
Forensic (during an incident)pause

Bounds. Argo CD re-reads Git every 180 s by default (timeout.reconciliation); set syncPolicy.retry explicitly so a broken manifest doesn't loop forever: e.g. limit: 5, backoff: {duration: 5s, factor: 2, maxDuration: 3m}. Keep allowEmpty: false (the default) so a render that produces zero manifests can't prune the namespace. Flux: interval: 10m, retryInterval: 1m (defaults to interval if unset).

Failure modes and how you see them.

  1. Competing writer. HPA and Git both write spec.replicas. Signal: argocd_app_info{sync_status="OutOfSync"} flips every reconcile; managedFields shows horizontal-pod-autoscaler. Cost: an API-server write every 3 minutes per app, and replicas that flap. Fix: ignore the field, or remove the HPA.
  2. Self-heal erases a mitigation. An engineer scales a Deployment to 20 during an incident; self-heal reverts it within 180 s. Signal: the audit log shows argocd-application-controller updating the object seconds after a human patch. Fix: pause enforcement (argocd app set <app> --sync-policy none, or flux suspend kustomization <name>), record why, resume after.
  3. Prune deletes load-bearing state. A Secret or PVC created out-of-band is removed because it isn't in Git. Signal: prune events in argocd app history; PVC deletion is unrecoverable. Fix: PruneLast=true, and never enable prune on namespaces holding stateful resources without a backup.

Emergency changes. Either commit the hotfix to Git and let the reconciler apply it, or apply it by hand and pause enforcement until it's in Git. A change that lives only in the cluster is drift by definition; recurring drift means the competing writer or the ownership rule is wrong, not that the reconciler needs a longer ignore list.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Your platform runs Argo CD with automated sync on but self-heal and prune off. Given stateless services, a stateful database, and a cluster-scoped controller, which workloads would you enable self-heal and prune for, which would you leave off, and what evidence would change your mind?

Answer

Clarify first: which controller, and whether automated sync is already on. I'll assume Argo CD v2.x with syncPolicy.automated enabled for most Applications, allowEmpty at its default of false, and AppProjects in use. The decision is per workload class, not global, because a wrong prune costs data or a cluster-wide outage while no prune costs drift and toil.

My default: self-heal and prune on for stateless services, self-heal on but prune off for the stateful database, both off for the cluster-scoped controller.

classselfHealprunewhy
Stateless Deployment + Service + ConfigMapononEvery object is reconstructible from Git in seconds, no data. Prune clears renamed and retired objects that otherwise linger and block name reuse.
Stateful database (StatefulSet or operator + PVC)on for the spec, off for the data pathoffPruning the StatefulSet deletes pods; PVCs survive under the default Retain retention policy, but the database is down and the operator may not re-adopt cleanly. A bad commit that drops the StatefulSet is an outage, not a rollback.
Cluster-scoped controller (CRD, ClusterRole, webhook)off, or on only inside a narrow AppProjectoffDeleting a CRD cascades to every custom resource of that type. A webhook misconfiguration can block the API server for the whole cluster. Blast radius is the cluster, not the namespace.

Worked trace of the failure prune introduces. A refactor moves a shared ClusterRole from apps/foo to apps/bar. App foo still has prune on and no longer renders the ClusterRole, so on its next sync it deletes it. App bar has not synced yet, so nothing recreates it. Every pod using that role's token loses API access at the next token refresh. Detection: the AppProject's orphanedResources warning, or a sync failure if FailOnSharedResource is set, which fails the sync instead of deleting a resource another Application manages. Recovery is re-applying from bar, but the outage window is real. Guardrails that make prune survivable are allowEmpty: false (a path typo that renders zero objects fails the sync rather than pruning everything), PruneLast, PrunePropagationPolicy=foreground, and an AppProject that whitelists cluster-scoped kinds explicitly. They reduce the blast radius; they do not change whether you should enable prune at all.

Leaving it off has its own failure modes. Someone kubectl edits a Deployment image or a Service selector during an incident and never reverts it; the next Git deploy silently reverts it or conflicts, and nobody knows which version served traffic. Manual changes never make it back into Git, so the repository stops being the source of truth. Retired objects become orphans that block name reuse and confuse cost attribution, and every rename needs a human kubectl delete.

Decision criteria for a new workload: (1) can every object be recreated from Git alone with no data loss; (2) is each object exclusively owned by one Application; (3) is the blast radius namespace-scoped; (4) is there a tested restore path with a measured RTO. Enable prune only when all four hold. Enable self-heal when (1) and (2) hold and the workload has no legitimate out-of-band mutation path: no hotfix, no operator writing back.

Revisit when: self-heal reverted a deliberate change during an incident; a prune event deleted something a human created; orphaned-resource count trends up; a workload gains a CRD or a PVC; or the AppProject's cluster-scoped whitelist changes. Flux reaches the same trade-off differently: spec.prune on a Kustomization defaults to false and reconciliation is continuous, so drift is corrected without a separate self-heal flag, but the cascade risk of deleting a CRD is identical.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design safeguards for automatic pruning.

Answer

Core answer (first 90 seconds)

Clarify first: "automatic pruning" here means a GitOps controller deleting live resources that are no longer in Git. I'll assume Argo CD 2.x reconciling one Application per service into Kubernetes 1.27+, with automated sync. The real question is what stops a bad commit or a bad render from deleting production.

Three layers, in order: bound the blast radius, preview the delete set, make deletion reversible.

  1. Bound it. Argo CD only prunes resources it tracks: those carrying app.kubernetes.io/instance=<app> or the argocd.argoproj.io/tracking-id label. Anything untracked is never deleted. So the first safeguard is the tracking boundary itself: if a resource loses its label it becomes an orphan and leaks forever rather than being pruned. That's a silent cost, not a safety win.

  2. Preview. argocd app diff shows the prune set; argocd app sync --prune --dry-run prints exactly what would be deleted without deleting it. In CI, fail the pipeline when the prune set is non-empty for a prod Application unless a human approves.

  3. Fail closed. A failed kustomize build or helm template marks the sync failed and Argo CD does not prune. The dangerous case is the opposite: a render that succeeds and returns an empty or truncated manifest set. That prunes everything. Guard it with a manifest-count check in CI (fail if the rendered count drops more than, say, 20% versus the last good commit) and an alert on prune count above a threshold.

Protecting specific resources

Prune=false on a resource means Argo CD will never prune it even when it leaves Git; Delete=false blocks manual deletion too. Put both on namespaces, PersistentVolumes, CRDs and shared infrastructure. The trade-off: those resources now need manual cleanup, and a CRD left behind keeps its CRs alive.

YAML
metadata:
  annotations:
    argocd.argoproj.io/sync-options: Prune=false,Delete=false

Ordering and propagation

PruneLast=true runs prunes after the new resources are synced and healthy, so a failed rollout doesn't also delete the old one. PrunePropagationPolicy=foreground makes the API server wait for dependents before removing the owner; background is faster but can briefly orphan dependents. Finalizers block deletion until their controller removes them: a stuck deletion is a finalizer whose controller is gone. Detect it with kubectl get <res> -o jsonpath='{.metadata.finalizers}' plus a non-zero deletionTimestamp older than a few minutes.

Failure modes and how you see them

FailureWhat happensDetection
Empty renderevery tracked resource prunedCI manifest-count delta; prune-count alert
Path moveold path's resources all look removeddiff shows 100% of resources as pruned
Permission losscontroller can't delete, sync stuckargocd app get stuck Progressing; RBAC errors in controller log
Partial prunesome deleted, some failedsync result lists failed prune resources
Orphantracking label removed, never prunedlive -l app.kubernetes.io/instance=<app> set larger than Argo CD's

When not to prune

Don't enable prune: true on Applications that own stateful resources (PVCs, StatefulSets) or that share a namespace with another team's resources. Renaming a resource in Git is a delete plus a create, if the old name holds data, mark it Prune=false and migrate explicitly. Canary the change: run the new render against a canary Application first, so a mass prune hits 5% of traffic, not 100%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Resolve two GitOps applications managing the same resource fields.

Answer

Core answer (say this first)

Assume both apps are Argo CD Applications (Flux Kustomizations behave the same) and both render the same object, say Deployment/prod/api, including the same field, e.g. spec.replicas. This is not a sync-order problem. It is two controllers each believing they own the field. Fix it by giving every field exactly one owner, then removing the field from the other app's manifest. Pausing one app or sequencing syncs only hides the loop.

Why it happens

Each controller reconciles on its own interval (Argo CD's default timeout.reconciliation is 180s; a Flux Kustomization's spec.interval is whatever you set, commonly 10m). It renders desired state and applies it. With server-side apply (Flux's default, and Argo CD when you set syncOptions: [ServerSideApply=true]) the API server records per-field ownership in metadata.managedFields. App A's apply sets spec.replicas=3 and takes ownership; app B's apply sets spec.replicas=5 and takes it back. Every apply bumps resourceVersion, so the other controller sees drift and re-applies. That is a hot loop.

With client-side apply (Argo CD's default) it is a whole-object patch, so you get last-writer-wins flip-flop rather than per-field ownership.

Confirm it

kubectl -n prod get deploy api -o yaml --show-managed-fields

You will see two managers claiming the same field:

- manager: argocd-controller
  operation: Apply
  fieldsV1:
    f:spec:
      f:replicas: {}
- manager: kustomize-controller
  operation: Apply
  fieldsV1:
    f:spec:
      f:replicas: {}

Also watch resourceVersion climb every reconcile interval.

Options

OptionHowCost / when wrong
One canonical appDelete the object from the other app's source (path, Helm values, or spec.source.directory.exclude)Losing app loses visibility; with a shared chart you must exclude the resource, not just ignore it
Split fieldsBoth use SSA, manifests disjoint, each manager owns its fieldsFragile: any field added to both reintroduces the loop; wrong when fields are coupled (replicas + HPA minReplicas)
ignoreDifferencesArgo CD spec.ignoreDifferences with managedFieldsManagers: [kustomize-controller]Stops the OutOfSync flapping, but Argo CD still applies the full manifest: a band-aid, not a fix

Migrate safely

  1. Annotate the losing app's object with argocd.argoproj.io/sync-options: Prune=false so removing it does not delete the live object.
  2. Remove the field or object from the losing app's source and merge through review.
  3. Sync the losing app; confirm it no longer reports the object.
  4. Canary the canonical app on one namespace and watch resourceVersion stabilize.

Failure modes

  • Delete/recreate loop: removing the object with prune enabled deletes it, the other app recreates it, repeat. Detect: the object's UID changes repeatedly in events.
  • HPA vs GitOps: the HPA writes spec.replicas, the app reverts it. Detect: replicas oscillate under kubectl get deploy -w. Fix: drop replicas from the manifest or ignore /spec/replicas.
  • Silent drift: ignoreDifferences hides the conflict, so nobody notices the field is unmanaged.

Alert when two managers own the same field (scan managedFields), and document which app is authoritative for emergency changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Investigate a target that is Synced but serving the wrong version.

Answer

"Synced" is a claim about the manifest, not about the bytes running. Argo CD's Sync status is a diff between the live object's spec and the manifest it rendered from Git; Flux's Ready on a Kustomization says the same kind of thing. So split the question into three gaps and find which one you're in. Assume Argo CD below, with Flux equivalents noted.

Gap 1: the desired manifest isn't what you think. argocd app get <app> prints Status.Sync.Revision: the commit Argo CD actually resolved. If spec.source.targetRevision is main or HEAD, that commit moves under you. Then argocd app manifests <app> gives the rendered output after Kustomize or Helm: that rendered text is what gets compared, not the file you edited. Grep it for the image string. If it reads myapp:latest or myapp:main, the manifest is stable while the artifact is not: the tag resolves to a new digest at pull time and the diff stays clean forever. (Flux: flux get kustomizations shows the applied revision, flux get images all shows what the ImagePolicy resolved the tag to.)

Gap 2: live spec matches, running pods don't. Compare the spec string against what is actually running:

kubectl get deploy myapp -o jsonpath='{.spec.template.spec.containers[*].image}'
kubectl get pods -l app=myapp -o jsonpath='{.items[*].status.containerStatuses[*].imageID}'

imageID is the digest the kubelet pulled. If it differs from the registry's digest for that tag, the spec is right and the node is wrong. The usual cause is imagePullPolicy: IfNotPresent, the default for any tag other than :latest, on a node that already cached that tag. No pull event, no error, old code. kubectl describe pod showing no Pulling event is the tell.

The other cause is a rollout that never finished. kubectl get rs -l app=myapp showing two ReplicaSets with nonzero DESIRED means the old one is still serving, and kubectl rollout status deploy/myapp will hang. With maxUnavailable: 0 and a new pod failing readiness, the old ReplicaSet keeps all traffic while Argo CD still reports Synced and Healthy.

Gap 3: pods are right, traffic isn't. kubectl get endpointslices -l kubernetes.io/service-name=myapp -o wide. If the IPs are the old pods, the Service selector doesn't match the new pod labels. Same class of bug in an Ingress backend or a mesh VirtualService.

Two things mask all three: ignoreDifferences in the Application spec (say, on /spec/template/spec/containers/0/image), and a mutating admission webhook rewriting the image to a mirror registry. Detect the first by reading the Application; detect the second by diffing argocd app manifests against kubectl get deploy -o yaml.

Remediation, and when not to.

optionwhencost
Pin targetRevision to a SHA and the image to a digest, roll forwarddefaultneeds a PR and CI
argocd app rollback <app> <history-id>bad commit, source is a tag or SHAre-syncs to branch head if targetRevision is a branch, so it can undo itself
kubectl rollout undostop the bleeding nowcreates drift; the next sync reverts it

Rollback is the trap. It reverts the app's tracked revision, not the image, so with a mutable tag it changes nothing. The durable fix is identity: commit SHA in targetRevision, digest in the image field, plus an alert when imageID digest diverges from the registry digest for the deployed tag.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Handle a legitimate emergency kubectl change under GitOps.

Answer

Assumptions I'd state first: Argo CD owns the workload (Flux noted where it differs), the Application has syncPolicy.automated.selfHeal: true, I hold a break-glass cluster role, and the change is genuinely urgent. Prod is down and a commit-plus-sync round-trip is too slow or the fix isn't yet expressible in the repo. If any of those is false, break-glass is the wrong tool and I say so.

The answer, in the order I'd deliver it:

  1. Freeze the narrowest reconciler. Argo CD: argocd app set api --self-heal=false, or set syncPolicy.automated.selfHeal: false on the Application. Flux: flux suspend kustomization api. Scope to the one Application/Kustomization, never the whole cluster. This buys a window: Argo CD's default resync is 180s, so a manual edit is normally reverted within about three minutes.
  2. Apply the kubectl change and capture before/after: kubectl -n prod get deploy api -o yaml > after.yaml, keeping the pre-change copy.
  3. Land it in Git. Commit the same manifest, or an explicit supersede commit. The repo is the source of truth; the kubectl edit is a stopgap, not the record.
  4. Resume and verify. argocd app set api --self-heal=true, then argocd app get api: expect Synced/Healthy. Flux: flux resume kustomization api.
  5. Revoke. Delete the break-glass token and role binding.

Mechanism. Argo CD's controller compares desired (Git) to live every 180s. A manual edit makes the app OutOfSync; with selfHeal on, the controller re-applies desired state and reverts you. Disabling selfHeal stops that reversion while keeping the app tracked: prefer it over --sync-policy none, which also drops auto-sync. Flux's Kustomization re-applies on its required spec.interval (commonly 1m–5m); suspend: true halts that loop.

Trade-offs. If the fix is a one-line manifest change, commit-and-sync is faster and safer than break-glass: don't reach for kubectl. Pausing self-heal on a monolithic Application also stops drift correction for unrelated resources inside it; that's a real cost, so scope matters. ignoreDifferences (e.g. jsonPointers: [/spec/replicas]) is for genuinely controller-owned fields, not for silencing a drift you caused.

Failure modes, with detection.

  • Edit reverted before you pause (race with the 180s loop): your change vanishes; check argocd app history api.
  • Forgot to resume: silent drift, next sync surprises you. Detect by alerting on Applications with selfHeal: false older than N minutes.
  • ignoreDifferences left in: permanent drift with no signal.
  • Token not revoked: standing privilege. Detect via audit events on kubectl create token.

Artefact: timeline trace (Argo CD, selfHeal on, resync 180s):

tactionstate
0sprod down, decide break-glassOutOfSync risk
20sargocd app set api --self-heal=falsecontroller stops reverting
45skubectl -n prod set image deploy/api api=api:2.3.1live updated
60scapture after.yamlevidence
5mcommit manifest to Git, pushdesired updated
6margocd app set api --self-heal=true; argocd app get apiSynced/Healthy
7mrevoke tokenaccess closed

Without the t=20s step, the t=45s edit is reverted by roughly t=180s.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design GitOps change windows without losing drift response.

Answer

Core answer. A change window should gate desired-state promotion, not reconciliation. Block the pipeline that writes a new image tag or manifest into Git; leave the controller that makes live match Git running. Drift is then still detected and still corrected during the freeze, and the only thing frozen is the decision about what "correct" means.

Assumptions: Argo CD 2.x with an AppProject per team, one Git repo per environment, and a promotion pipeline (CI or Argo CD Image Updater) that commits image tags. If your drift instead comes from humans running kubectl edit, windows buy you nothing: you want admission control (Kyverno, OPA Gatekeeper), not a sync window.

Argo CD. Sync windows live on the AppProject, not the Application, so scope them to the project that owns the promotion path.

YAML
spec:
  syncWindows:
    - kind: deny
      schedule: "0 22 * * *"   # 22:00 UTC
      duration: 8h
      timeZone: "UTC"
      applications: ["payments-*"]
      manualSync: false        # block manual syncs too, not just auto-sync
    - kind: allow
      schedule: "0 6 * * 1-5"
      duration: 2h
      applications: ["payments-*"]
settingdefaultwhat it decides
manualSynctruewhether a human can sync during a deny window
timeZoneUTCwhich hours the window actually covers
andOperatorfalseOR vs AND across applications/namespaces/clusters
--app-resync180show often drift is re-detected
--operation-processors10concurrent syncs at window open

Three details decide whether this works. manualSync defaults to true, so a deny window with the default still lets an engineer click Sync: set it to false if the freeze is real. Filters are OR'd by default: applications: ["*"] plus namespaces: ["kube-system"] matches everything, not just kube-system; andOperator: true flips that to AND. And timeZone defaults to UTC, so "22:00" is 22:00 UTC. The most common way a window silently covers the wrong hours. When an allow and a deny window overlap, deny wins.

Critically, a deny window does not stop Argo CD from marking an app OutOfSync. The application controller still re-checks Git against live every --app-resync (default 180s) and on webhook, so your drift signal stays live; only the sync operation is refused.

Flux. There is no window primitive. Gate promotion by suspending the ImageUpdateAutomation (spec.suspend: true) and leave the Kustomization reconciling on its interval. Suspending the Kustomization instead is the mistake: it stops drift correction, which is the thing you were trying to keep.

The failure mode nobody plans for: the thundering herd. With 400 Applications frozen for 8h, all 400 are OutOfSync at 06:00. The application controller runs --operation-processors (default 10) concurrent syncs, so 400 syncs at ~20s each (hypothetical) serialize to 400 × 20 / 10 = 800s, about 13 minutes, while the repo-server generates 400 manifest sets at once. Stagger the allow windows by shard (06:00, 06:15, 06:30) or keep the freeze short. Also revalidate: the sync applies current Git HEAD, so a commit that landed during the freeze goes out unreviewed. Require a fresh CI pass or a PreSync hook that checks it.

Emergency override. Argo CD has no per-sync bypass flag. The auditable override is a break-glass AppProject with no windows; move the app into it by PR, and the git log plus argocd app history is your audit trail. Time-bound it by reverting the PR.

What would change this. If the freeze is regulatory and must cover every write including self-heal, accept the backlog and stagger. If drift is human-driven, drop windows and add admission control.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design multi-cluster GitOps rollout and promotion.

Answer

Core answer (first 90 seconds)

Assume Argo CD 2.11 as the reconciler, one Git repo holding rendered manifests, ~40 clusters across 3 regions, images pinned by digest, and Kubernetes 1.28–1.30 in the fleet. I'd classify clusters with labels on the Argo CD cluster Secrets (region, env, tenant, k8s-minor, failure-domain) and let an ApplicationSet clusterGenerator select them by label selector, so a cluster joins a wave by being labelled, not by being listed.

Promotion is a Git commit that moves a pointer, never a retag. Each environment directory pins image: repo@sha256:... and a chart version; promoting means merging the same digest into the next directory. The rendered revision is the commit SHA, and Argo CD records it as status.sync.revision per Application, so "which clusters are on which revision" is a query, not a spreadsheet.

Waves: canary = 1 cluster per region (3), then 25% (10), then the rest. Argo CD's ApplicationSet strategy: RollingSync with maxUpdate: 1 per step enforces this: the controller will not start the next Application until the previous is Healthy. That's the mechanism that bounds blast radius: wave size is a hard concurrency limit, not a hope.

waveclustersmaxUpdatebakegate
canary3 (1/region)130 min5xx < 0.5%, p99 < 300 ms, all Synced/Healthy
wave 210130 minsame + no burn-rate alert firing
wave 3remainder215 minsame

Guardrails are Prometheus queries, not vibes: rate(http_requests_total{code=~"5.."}[5m]) / rate(http_requests_total[5m]) < 0.005, p99 < 300 ms, no KubeJobFailed, plus an Argo Rollouts AnalysisTemplate for the app-level canary inside the canary cluster. Fail any → the RollingSync step halts and the pointer stays where it is.

Trade-offs

  • Pointer-in-Git vs. retagging: retagging is faster but makes "what ran" unanswerable and breaks rollback; pointer-in-Git costs a commit per promotion.
  • ApplicationSet RollingSync vs. Argo Rollouts for the whole fleet: RollingSync is cluster-granular and cheap; Rollouts is pod-granular and needs the workload to be a Rollout. Use both: RollingSync for fleet waves, Rollouts inside the canary cluster.
  • One repo with per-cluster dirs vs. repo-per-env: one repo gives atomic cross-env diffs but a bad merge touches everything; repo-per-env isolates blast radius at the cost of cross-repo promotion PRs. At 40 clusters I'd take one repo plus CODEOWNERS on the prod dir.
  • Pull-based Argo CD vs. push-based CI kubectl apply: pull survives a CI outage and gives drift detection; push is simpler but has no reconciliation loop.

Failure modes and detection

  • Source: digest missing or registry auth expired → Application ComparisonError, sync status Unknown. Detect with argocd app list -o json | jq '.[] | select(.status.sync.status=="Unknown")'.
  • Reconciliation: ApplicationSet can't render (bad generator, duplicate name) → ApplicationSet condition ErrorOccurred. Alert on it.
  • Cluster unreachable: cluster Secret connectionState not Successful; the cluster silently stops converging. This is the one that bites: a cluster that looks green because nobody is talking to it. Alert on the cluster connection metric.
  • Data: migration applied but app rolled back → schema ahead of binary. Compare schema_migrations version to the app's expected version before promoting the next wave.
  • Outcome: SLO burn with no hard error. 5xx flat but p99 climbing. Detect with a burn-rate alert, not a fixed threshold.

Recovery from partial state

Don't re-run the whole wave. Revert the pointer for the failing cluster only (per-cluster override in the ApplicationSet), let Argo CD converge it back, then re-promote. Migrations are the thing that doesn't roll back, so gate them behind a separate sync wave (argocd.argoproj.io/sync-wave: "-1") and keep them backward-compatible for one release.

Skew

Kubelet may be up to three minors behind the apiserver, so a manifest valid on 1.30 can be rejected on 1.28. Run pluto detect-files and kubeconform -kubernetes-version against the oldest minor in each wave in CI; a wave never mixes minors more than one apart.

What would change the decision

Homogeneous, single-tenant clusters: drop the canary wave and go straight to RollingSync with maxUpdate: 5. A 500-cluster fleet: shard ApplicationSets per region so one controller isn't the bottleneck.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a production GitOps platform for multiple teams.

Answer

Assumptions: Kubernetes 1.29+, Argo CD 2.11+ or Flux v2.3+, one Git host, the platform team owns the controllers, each product team owns its namespaces. Nobody runs kubectl apply against prod.

The 90-second answer. Git holds desired state; an in-cluster controller pulls it and reconciles on a loop. I'd pick Argo CD when teams want a UI, per-app RBAC and a first-class tenancy object (AppProject); Flux when the platform should be plain CRDs with no extra API server and tenants already write Kustomize and Helm. Everything else (repo layout, promotion, guardrails) is the same either way.

Layout. One config repo, clusters/<cluster>/<team>/<app>/, plus a separate source repo per app. CI builds an image, signs it with cosign, and writes the digest into the dev overlay. Promotion to staging and prod is a PR that changes only that digest: never a rebuild. The promoted artefact is then byte-identical to what was tested.

Tenancy. Argo CD: one AppProject per team, sourceRepos limited to that team's config repo, destinations limited to payments-*, clusterResourceWhitelist: [], and a role whose policy is p, proj:team-payments:deployer, applications, sync, team-payments/*, allow. Flux: one Kustomization per team with spec.serviceAccountName: team-payments and spec.targetNamespace: payments, while the controller's own SA holds nothing but read on the CRDs.

YAML
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata: {name: team-payments, namespace: argocd}
spec:
  sourceRepos: ["https://github.com/acme/payments-config"]
  destinations:
    - {server: https://kubernetes.default.svc, namespace: "payments-*"}
  namespaceResourceWhitelist:
    - {group: apps, kind: Deployment}
    - {group: "", kind: ConfigMap}
  clusterResourceWhitelist: []
  roles:
    - name: deployer
      policies:
        - p, proj:team-payments:deployer, applications, sync, team-payments/*, allow

Progressive reconciliation. Order with sync waves (argocd.argoproj.io/sync-wave, default 0, applied ascending): -1 Namespace and CRDs, 0 ConfigMap, 1 Deployment, 2 migration Job. Gate on health with argocd app wait payments --health --timeout 300. Leave prune: false (the default) until you also have PruneLast=true and argocd.argoproj.io/sync-options: Prune=false on PVCs and anything stateful.

Failure modes.

  • Controller SA is cluster-admin. Any AppProject mistake becomes cluster takeover. Detect with kubectl auth can-i --list --as=system:serviceaccount:argocd:argocd-application-controller. Fix with per-team destination service accounts (Argo CD 2.8+) or Flux serviceAccountName.
  • Prune deletes a PVC. Turning on prune without PruneLast and without the annotation above. Detect: argocd app history shows the revision that pruned, and argocd_app_sync_total{phase="Failed"} spikes.
  • Manual hotfix reverted. selfHeal: true reverts a kubectl edit within the poll interval: 180s by default (timeout.reconciliation). Detect: argocd app get flips OutOfSync back to Synced with no new commit.
  • Repo-server saturation. A monorepo with thousands of Helm apps re-templates on every poll. Detect: repo-server restarts and rising sync latency, with argocd_app_info{sync_status="Unknown"} climbing. Fix: split repos, raise --repo-cache-expiration.

Argo CD vs Flux, deciding criteria.

Argo CD 2.11+Flux v2.3+
tenancyAppProject + policy.csvserviceAccountName + namespace lockdown
UIbuilt innone (Weave GitOps, Grafana)
topologyone controller, many clusterstypically one controller per cluster
drift180s poll, webhook optionalspec.interval you set, e.g. 10m
prune defaultoffoff
extra API serveryesno

Pick Argo CD if you need the UI and per-app RBAC out of the box; pick Flux if you want no extra control plane and your teams already live in Kustomize. Don't run both against the same cluster.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Choose between one central and per-cluster reconcilers.

Answer

Core answer (say this first)

Assume Kubernetes clusters, desired state in git, and one team owning the fleet. Choose central (Argo CD hub-and-spoke, Karmada push mode) when the hub can reach every cluster's API server on 6443 and the fleet is small enough that one controller's queue is not the constraint. Choose per-cluster (Flux bootstrapped into each cluster, Rancher Fleet's per-cluster agent, Karmada pull mode) when clusters are edge or air-gapped, when credentials must not concentrate, or when the fleet is large enough that the hub becomes a shared failure domain. The deciding question is not "which is simpler" but "can the hub reach the cluster, and do I accept one credential store holding cluster-admin everywhere?"

Mechanism

Central: one controller process holds a credential per cluster (Argo CD keeps them as Secrets labelled argocd.argoproj.io/secret-type: cluster in its own namespace), watches git, renders, and writes to each cluster's API server. Every cluster's reconciliation shares one worker pool and one outbound path.

Per-cluster: an agent inside the cluster watches the source and applies locally. Flux's GitRepository requires spec.interval (commonly 1m); the agent needs only egress to git or the hub, never inbound.

centralper-cluster
failure radiushub down = whole fleet stopsone cluster drifts
networkhub to each API server on 6443cluster to git/hub egress only
credentialsN cluster-admin creds in one storeone scoped cred per cluster
costone control plane, shardableN agents to upgrade and observe

Sizing arithmetic (illustrative)

500 clusters, Argo CD's default timeout.reconciliation: 180s, roughly 1.5s of controller work per reconcile: 500 x 1.5s = 750s of work per 180s window, so at least 5 application-controller replicas, sharded with ARGOCD_CONTROLLER_REPLICAS and ARGOCD_CONTROLLER_SHARDING_ALGORITHM=consistent-hashing. The same 500 clusters with per-cluster agents spread that work over 500 processes and 500 API servers, with no shared queue but 500 upgrade targets.

Failure modes and how you see them

  • Hub partition: Argo CD marks the cluster unreachable and the Application's status.reconciledAt stops advancing while the cluster keeps running its last applied state. Alert on reconciledAt older than 2x the resync interval.
  • Agent crashloop: the cluster drifts silently. Flux's notification-controller emits Ready=False events; otherwise run an external audit diffing live objects against git.
  • Credential compromise: one hub Secret is cluster-admin on N clusters. Detection is the member clusters' API server audit logs showing writes from the hub's identity.
  • Two reconcilers on one object: they fight, and metadata.managedFields shows two managers. kubectl get deploy x -o jsonpath='{.metadata.managedFields[*].manager}'.

What changes the decision

Air-gapped or intermittently connected clusters, a compliance rule that credentials stay in-region, or a fleet where one hub's outage is unacceptable: any of those forces per-cluster. A hybrid is common and defensible, with the hub owning fleet policy (namespaces, RBAC, quotas, CRDs) and per-cluster agents owning tenant workloads.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Prevent image automation from bypassing production governance.

Answer

Core answer (first 90 seconds)

Assume the setup: Renovate opens PRs against a GitOps repo, and Argo CD syncs production from a protected branch. The bypass isn't one hole: it's three seams: the automation's credential, the merge gate, and the cluster's admission path. Close all three and the bot can propose but never promote.

Concretely: run the bot as a GitHub App, not a PAT, so its installation token is minted per run and expires in 60 minutes, scoped to contents: write on one repo. Let it open PRs; give it no merge rights. Pin every image by digest in the manifest. Then make the cluster refuse anything that isn't digest-pinned and signed with provenance from your release workflow, so even a merged-but-wrong manifest can't run.

Mechanism

  • Credential. A GitHub App installation token is short-lived and repo-scoped; a classic PAT with repo scope is a permanent key to every repo the human can reach. Renovate reads its token from hostRules/RENOVATE_TOKEN. Grant contents: write only: never workflow, which lets the bot rewrite CI to exfiltrate secrets.
  • Merge gate. Branch protection plus CODEOWNERS means the bot's PR still needs a human. platformAutomerge: true routes automerge through GitHub's native auto-merge, which still waits for required checks; Renovate's own merge path can skip them.
  • Admission. Kyverno verifyImages with mutateDigest: true rewrites :1.2.3 to @sha256:… at admission and rejects unsigned images. OPA/Gatekeeper does the same via a constraint template. This is the backstop: it holds even when the Git path is bypassed.
JSON
{
  "extends": ["config:recommended"],
  "pinDigests": true,
  "automerge": false,
  "platformAutomerge": true,
  "packageRules": [
    { "matchUpdateTypes": ["digest", "patch"], "automerge": true },
    { "matchUpdateTypes": ["major", "minor"], "automerge": false, "addLabels": ["needs-review"] }
  ]
}
YAML
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: verify-prod-images
spec:
  validationFailureAction: Enforce
  rules:
    - name: verify-signature-and-digest
      match:
        any:
          - resources:
              kinds: [Pod]
              namespaces: [prod]
      verifyImages:
        - imageReferences: ["registry.example.com/*"]
          mutateDigest: true
          verifyDigest: true
          attestors:
            - entries:
                - keyless:
                    issuer: "https://token.actions.githubusercontent.com"
                    subject: "https://github.com/acme/app/.github/workflows/release.yaml@refs/heads/main"
          attestations:
            - predicateType: "https://slsa.dev/provenance/v1"
              attestors:
                - entries:
                    - keyless:
                        issuer: "https://token.actions.githubusercontent.com"

Trade-offs

Gating every bump costs review latency and reviewer fatigue. The deciding criterion is blast radius and whether the change is digest-only. A digest-only update (same tag, new bytes) is a supply-chain event, so it deserves the same scrutiny as a version bump, not less. Patch bumps on a non-0.x dependency with green tests are the automerge case; major/minor and anything 0.x go to a human. On a dev cluster, skip the admission policy: a bad image there costs a redeploy, not an incident.

Failure modes

FailureHow it happensDetectionCost
Stale PATBot uses a classic PAT with repo scope, no expirySecret scanning; org token auditWrite to every repo the human owns
Direct manifest editkubectl apply on prod, bypassing GitArgo CD OutOfSync alert; Kyverno denies non-digest imageUntracked prod change, no rollback point
Over-scoped CI SAPipeline SA bound to cluster-adminkubectl auth can-i --list; RBAC reviewCompromised pipeline = cluster takeover
Automerge major bumpautomerge: true with no matchUpdateTypesPR label audit; policy gateBreaking change merged unreviewed

What would change the decision

If the release workflow doesn't sign yet, keyless verifyImages rejects everything. Start with mutateDigest plus digest pinning, then add the attestation once provenance exists.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design policy for source and artifact verification.

Answer

What I'd say first

Assumptions: Kubernetes deploys, images built in CI, Helm charts and remote Kustomize bases pulled at deploy time, one registry. If you're on VMs with no admission controller, the same policy moves into the deploy pipeline and the trade-offs shift.

The policy has one objective: every byte that reaches production traces to a reviewed commit and an authenticated builder. That means four things, in order: pin by digest, verify a signature identity and its claims, verify again where the artifact crosses a system boundary, and fail closed.

Why digest pinning, not tags

A tag is a mutable pointer. ghcr.io/acme/api:1.4.2 can be repointed to a different manifest with one registry API call and nothing downstream notices. A digest is the sha256 of the manifest, so the reference is the content. Kyverno's verifyImages defaults mutateDigest: true, rewriting the tag to the verified digest in the admitted Pod spec, so the kubelet pulls exactly what was verified, closing the gap between admission and pull.

What a signature actually attests

A valid signature proves some key signed some bytes. It does not prove who, or what was built. So the policy checks identity and claims, not presence. With keyless signing, Fulcio issues a ~10-minute certificate bound to a CI OIDC token, and the signature plus cert land in Rekor, an append-only Merkle log. Verification then has to name the identity:

Shell
cosign verify ghcr.io/acme/api@sha256:9f2c... \
  --certificate-identity-regexp 'https://github.com/acme/.*' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com

In cosign v2 those two flags are mandatory for keyless verification: omitting them fails, which is the point. A bare cosign verify that only checks "a signature exists" is the classic bypass.

Where to verify

BoundaryWhat it catchesTool
CI buildwrong source, unsigned outputcosign sign, SLSA provenance
Chart/base pullmutable remote baseHelm --verify, Kustomize ?ref=<sha>
Admissiontag repointed after CIKyverno verifyImages, failurePolicy: Fail
Deploy to second clusterartifact swapped in transitre-verify at the boundary

Trade-offs

Fail-closed (failurePolicy: Fail) means a Rekor or Fulcio outage blocks deploys. Advisory mode (Audit) never blocks but never enforces: right only while rolling out and measuring, with a dated exit. Keyless removes long-lived signing keys but adds a dependency on Fulcio/Rekor availability; long-lived keys with TUF-distributed roots trade that dependency for key custody. Verify-at-admission is cheap and catches post-CI mutation; verify-at-deploy catches cross-system swaps admission can't see.

Failure modes

  • Tag repointed after CI: caught by digest mismatch at admission.
  • Signature present, wrong identity: caught only if you assert identity. Log the verified identity, not just "verified".
  • Transparency log unavailable: with fail-closed, deploys stop; that's the intended signal, with a governed break-glass that logs who used it.
  • Root key compromise: TUF root rotation requires the new root signed by a threshold of old keys; rehearse it.

What would change the decision

If artifacts never cross a trust boundary and the pipeline is the only writer, verify-once at build with signed provenance is enough. If you can't run an admission controller, move enforcement into the deploy step and accept a wider TOCTOU window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Threat-model an in-cluster GitOps reconciler.

Answer

Scope and assumptions. I'm threat-modelling a reconciler that runs inside the cluster it deploys to, Argo CD or Flux, with write access to the target cluster and read access to a Git repo or OCI registry. Assume multi-tenant: several teams share one reconciler. Assume the reconciler's service account can create most namespaced kinds. If any of those is false, the model changes, so say which one you're working from before you start listing threats.

The core answer: the reconciler is a privileged automation identity whose input is attacker-reachable. Anyone who can land a commit, tag, or OCI artifact in a watched source can ask it to apply arbitrary manifests with its own credentials. So the model is three questions: what can reach the input, what can the reconciler's identity do, and what does a bad sync destroy before anyone notices. Everything else is a control on one of those three.

Assets and the trust boundary. Repo credentials, the signing trust root, the target-cluster credential, the desired-state repo, rendered artifacts, and the audit trail. The boundary that matters is between "can write to a source" and "can cause a sync": that's the line an attacker crosses.

Threats, exploit path, control, detection.

ThreatExploit pathControlDetection signal
Malicious commitAttacker with repo write pushes a manifestGPG commit verification (Argo CD signatureKeys in argocd-cm; Flux GitRepository.spec.verify)Sync rejected on unsigned commit; alert on verification failures
Source substitutionRepo URL or tag repointed to attacker's forkPin sourceRepos to exact URLs; digest-pin OCI artifactsDiff between configured and resolved source
Confused deputyTenant's ApplicationSet generator emits an Application targeting another namespaceAppProject destinations pinned to explicit namespaces, not *Application created with a destination outside the allowlist
Destructive pruneBad commit removes a Deployment; prune deletes itsyncPolicy prune off for platform apps; sync windowsPrune events in sync history
Extension executionConfig-management plugin or Helm chart runs in the repo-serverSandbox plugins; no cluster credentials in repo-serverUnexpected process or egress from repo-server

Worked trace: confused deputy. A tenant commits an Application manifest into their repo path. The ApplicationSet git generator picks it up and creates the Application. If the project allows destinations: namespace: "*", the generated Application syncs a DaemonSet into kube-system. The fix is one line: enumerate namespaces:

YAML
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: team-a
  namespace: argocd
spec:
  sourceRepos:
    - https://github.com/acme/team-a
  destinations:
    - namespace: team-a
      server: https://kubernetes.default.svc
  clusterResourceWhitelist: []

With clusterResourceWhitelist: [] and a single destination, the same commit fails at admission with a destination-not-permitted error instead of writing to kube-system.

Trade-offs. Pinning destinations and disabling prune costs you the ability to let teams self-serve new namespaces: you trade autonomy for a smaller blast radius, and it's worth it when the reconciler holds cluster-scoped rights. Flux has no AppProject equivalent; you get the same boundary by setting Kustomization.spec.serviceAccountName and scoping that SA's RBAC, which is more work per tenant but composes with existing RBAC tooling. Commit-signature verification blocks a compromised repo account but not a compromised CI token that signs legitimately, if your CI signs, verification buys you less than you think.

Failure modes and detection. Credential theft shows up as syncs from an unexpected IP or at an unexpected hour. Controller compromise shows up as API calls the reconciler never made before. Prune damage shows up as resource deletions with no matching commit. Set alerts on sync failures, prune events, and destination mismatches; treat any of them as a page, not a dashboard. Rehearse revocation: rotate the repo credential and the cluster token, then rebuild from a known-good commit, and time it, if it takes more than an hour, that's the finding.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Plan a GitOps controller upgrade.

Answer

A GitOps controller upgrade changes the component that reconciles everything else, and often manages itself, so I split it into two changes with different undo stories: the CRD/API surface, which is close to one-way, and controller behaviour, which is a redeploy away from undo. I pin both ends (Argo CD 2.11 to 2.13, or Flux v2.4 to v2.6), apply CRDs first with server-side apply, rehearse against an imported copy of production Applications, then canary one cluster. The rule that keeps a mistake from being an outage: at any moment exactly one controller holds credentials for a given cluster.

  1. Pin versions and read what moved. argocd version for server, repo-server, controller and CLI; for Flux, flux version --client and flux check, which reports drift between the CLI and the cluster's controllers. Inventory the four things that break across a minor jump: CRD schema, keys removed from argocd-cm/argocd-rbac-cm, repo-server plugins and their tool versions, and whether the controller manages itself. Self-management matters because the old controller applies the new one and cannot roll it back if it will not start: do that step by hand with kubectl apply.

  2. CRDs first, server-side. kubectl apply --server-side --force-conflicts -k https://github.com/argoproj/argo-cd/manifests/crds?ref=v2.13.0. Client-side apply fails here: "metadata.annotations: Too long: must have at most 262144 bytes". Order matters because a structural CRD has unknown fields pruned at the API server: a new controller against an old CRD drops a new syncPolicy field before it reaches etcd, so the feature is on in the release notes and off in your cluster.

  3. Keep a return path that does not need the new controller. argocd admin export -n argocd > argocd-$(date +%F).yaml gives every Application and AppProject in importable form; keep the previous install manifests pinned to a tag beside it. For Flux, Git holds the state, plus kubectl get -n flux-system -o yaml for generated secrets.

  4. Rehearse where failure is free: a kind cluster with the export imported, or flux install --export with Kustomizations suspended. Three checks that versions actually change: rendering is identical (argocd app manifests, or flux diff kustomization <name> --path=./clusters/prod expecting no differences), PreSync hooks still run once in the same waves, and prune still removes a deliberately orphaned ConfigMap.

  5. Canary a cluster, not a pod. A rolling upgrade has no partial ownership, the controller is one StatefulSet image, so a real canary is a second install (namespace argocd-next) holding the Cluster secret for one cluster and an AppProject whose destinations are limited to it. A second control plane is the cost; the failure it protects against is two controllers double-pruning one cluster. Detect that as the same app in both controllers' logs, or two hook Jobs for one sync.

  6. Bound concurrency, watch one signal. timeout.reconciliation: 180s (default in argocd-cm), controller --status-processors=20 and --operation-processors=10; in HA, ARGOCD_CONTROLLER_REPLICAS must equal the StatefulSet replica count or an app is reconciled twice or never. Baseline argocd_app_reconcile p99 and argocd_app_sync_total (Flux: gotk_reconcile_duration_seconds, gotk_reconcile_condition) before starting. Re-diffing every Application is what saturates Redis and the repo-server. If p99 is not back to baseline within one resync interval, roll back rather than wait.

  7. Roll back in Git, not in the UI. argocd app rollback restores a previously synced manifest set from the deploy history but does not touch Git, so auto-sync reverts it within 180 s. The durable rollback is git revert of the controller manifests plus the previous CRD, and treat the CRD step as one-way, since a schema downgrade can prune fields already written into existing Applications.

strategywhat it isblast radiuschoose it when
in-place rollingapply new manifests; controller rolls replica by replicafleetno CRD or config removals in the release notes, tight window
side-by-side canarysecond install owns exactly one cluster1 clusterCRD or controller behaviour changed
blue/green handovernew install takes the Cluster secrets, old one loses themfleet, reversible in a commitrollback must not depend on the new controller working

Rehearsal, hypothetical: 300 Applications, 6 clusters. 09:00 CRDs applied server-side, Application count still 300; 09:10 export yields 300 Applications and 14 AppProjects; 09:30 kind import plus canary cluster, diffs clean, hook Job ran once; 10:15 production controller rolls one replica at a time; 10:40 p99 back to baseline, 300 Synced and Healthy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Recover from an accidental GitOps namespace deletion.

Answer

What I'd say first

Two facts decide the whole recovery: is the namespace object gone or stuck in Terminating, and is Argo CD still auto-syncing with prune enabled?

I freeze first. argocd app set <app> --sync-policy none (or patch spec.syncPolicy.automated off) stops further reconciliation. The reason is the empty-set prune: Argo CD with automated.prune: true deletes every tracked resource absent from the rendered manifests. If the render is broken (a bad kustomize build, a wrong spec.source.path, a Helm template that fails) the desired set is empty and the next sync prunes the entire Application. That is how a one-line mistake becomes a namespace-wide deletion, and it is the failure I most want to rule out before touching anything.

Then I check the namespace: kubectl get ns <name> -o json for deletionTimestamp and finalizers. A namespace stuck in Terminating almost always means a resource with a finalizer: most often kubernetes.io/pvc-protection on a PVC still mounted by a running pod, or a custom operator finalizer. kubectl get ns <name> -o jsonpath='{.status.conditions}' shows NamespaceContentRemaining or NamespaceFinalizersRemaining. I don't strip finalizers until I know what they protect.

With the reconciler frozen and Git HEAD confirmed at a known-good SHA, I re-enable sync or run argocd app sync <app> --revision <sha>. That recreates the declarative objects: Deployments, Services, ConfigMaps, ServiceAccounts, RBAC.

What Git does not restore

Git restores objects, not bytes. PVCs are namespaced, so deleting the namespace deletes the PVC object. Whether the data survives depends on the PV reclaim policy: Delete (the default for dynamically provisioned volumes on EKS, GKE and AKS) destroys the backing disk; Retain keeps it. So for stateful workloads I restore from Velero: velero restore create --from-backup <backup> --include-namespaces <ns>. The RPO is whatever the backup schedule gives; a nightly schedule means up to 24 hours of loss, and that is the number I state to the incident channel rather than "some data may be lost."

ResourceRecreated by Git syncNeeds separate action
Deployments, Services, ConfigMapsYes—
PVC objectYes (empty)Velero restore for data
IRSA / IAM role bindingsAnnotation onlyRe-verify role trust
cert-manager CertificatesYesRe-issuance takes minutes
external-dns records, cloud LBsNoController reconciles

Failure modes and how I detect them

  • Empty-set prune: argocd app diff shows mass deletion, or the sync result reports 0 resources.
  • Namespace stuck Terminating: the conditions above; the cost is that nothing in the namespace can be recreated until it clears.
  • PVC bound to a fresh empty volume: kubectl get pvc shows Bound but the app's readiness probe fails. The object looks healthy while the data is gone.
  • Partial Velero restore: velero restore describe <restore> lists warnings and errors; a partial restore is worse than a clean one because it looks successful.

Trade-offs

Letting Argo CD self-heal is fast and keeps Git as the single source of truth, but it is only safe once you've confirmed Git is good and you understand prune. Restoring the whole namespace from Velero is a point-in-time snapshot that can reintroduce stale config; the cleaner split is Git for configuration, Velero for data. Force-deleting finalizers unblocks a stuck namespace in seconds but can orphan cloud load balancers and disks, so I only do it after inventorying what the finalizer holds.

Before resuming automation

I verify authorization (RBAC and IRSA re-bound), data integrity (row counts or checksums against the last backup), and critical user journeys, then re-enable sync with prune still off, and turn prune back on only after a clean diff.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Recover the GitOps platform after total cluster loss.

Answer

What I'd say in the first two minutes

Assumptions: one production cluster, the GitOps controller is Argo CD or Flux, and the Git remote, container registry and identity provider are still reachable. If Git itself is gone, this is a different problem: you are restoring a repo from backup, not a cluster.

The core point: in GitOps the cluster is disposable and Git is the source of truth, so most of recovery is re-bootstrapping the controller and letting it reconcile. What you cannot regenerate is the trust material: the key that decrypts secrets, the credentials the controller uses to reach Git and the cluster, and the persistent data. So the recovery kit is small and lives outside the cluster: a pinned controller version, the bootstrap manifest, the secret-decryption key, and the data backups.

Ordering, and why it is that order

Reconcile in dependency order, not alphabetical. CRDs before CRs (the Application CRD must exist before any Application object). Namespaces and RBAC before namespaced resources. Admission controllers (Kyverno, Gatekeeper) before workloads, if pods are admitted before policies load, they run unvalidated, which is worse than a failed sync. Secret decryption (the Sealed Secrets controller key, or External Secrets Operator reaching Vault) before anything that mounts a secret. Platform add-ons (cert-manager, ingress, CSI driver, CoreDNS) before applications, because apps depend on them.

Implement the gating with the controller's own primitives: Argo CD sync waves (argocd.argoproj.io/sync-wave) plus health checks, or Flux dependsOn. A wave only advances when the previous wave is Healthy, so a stuck cert-manager blocks the apps instead of racing them.

Trade-offs

Rebuild-from-Git vs restore-from-Velero. Rebuild is fast (minutes) and needs no backup of cluster objects, but only works if Git, the registry and the IdP are all up and the image tags still exist. Velero restores PVs and cluster objects, but restoring stale cluster objects fights the controller: it will revert them on the next sync. The deciding rule: restore data with Velero, let Git rebuild config.

In-cluster vs external secret state. Sealed Secrets keeps the sealing key in-cluster, so you must back that key up out of band. External Secrets + Vault means nothing to back up, but Vault becomes a hard dependency of every pod start.

Failure modes and detection

  • Sealing key lost → every SealedSecret is undecryptable; the controller logs no key could decrypt secret. Back the key up separately from the cluster.
  • Images garbage-collected from the registry → ImagePullBackOff; pin digests and mirror critical images.
  • IdP down → OIDC login fails, but existing client-cert kubeconfigs still work; watch apiserver OIDC errors.
WaveContentsWhy first
0CRDs, namespaces, RBACCRs and namespaced objects need them
1Admission policies, cert-managerpods must be validated and have TLS
2Secret decryption, CSI, ingress, DNSpods mount secrets and need storage/network
3Applicationsdepend on all of the above

Finally: rotate any credential that was in the lost cluster, and rehearse the case where the registry or IdP is also down. That is the scenario the kit exists for.

Curated: · Written: · Reviewed:

Difficulty: Hard