The Steps GitOps Cannot Express Declaratively
Once you separate the vendor snapshot from the overlays, map one overlay to one Argo CD Application, and let an App-of-Apps parent order those Applications with sync waves, most of the platform deployment is expressed declaratively. And yet, every time you push a real deployment all the way through, a few steps are left over. These are the points where no amount of careful manifest writing makes the output of kustomize build alone enough to bring the cluster to its intended state.
Where the other articles in this series covered what was declared, this one covers what stayed outside the declaration, and how that residue gets pulled back into Git.
A classification of why steps stay imperative
Section titled “A classification of why steps stay imperative”If you call all of it “imperative steps” as one lump, the remedy becomes one lump too. In practice four distinct causes are mixed together, and Argo CD offers a different prescription for each.
| Class | Nature | Representative symptom |
|---|---|---|
| Ordering / readiness dependency | Resource B cannot be applied until resource A is Established on the API server | A CR applied before its CRD is registered fails with no matches for kind |
| Values known only at runtime | A field that does not exist when the manifest is written and is injected later by a controller | An empty webhook caBundle makes the admission call fail TLS |
| Controller convergence | The desired outcome is not a resource spec but a side effect produced by a controller | Creating a Profile does not yet produce the namespace, RBAC, and ServiceAccount |
| One-time migration | The transition from a past state to the current one is an event, not a state | Schema migrations, relabeling resources whose ownership changed |
The first three are problems of time. The declared end state is correct; the path to that state needs ordering and waiting. The last one is different in kind. A one-time migration is inherently imperative work that cannot be expressed as an end state.
This distinction matters because the first three are debt you can pay off, while the last one is a constant you cannot remove.
The three cases that actually remained
Section titled “The three cases that actually remained”trainer: webhook caBundle and jobset rollout
Section titled “trainer: webhook caBundle and jobset rollout”The trainer component registers CRDs and ships validating/mutating webhooks for those CRDs alongside them. The clientConfig.caBundle in the webhook manifest has no value in Git, because the controller that issues the certificate (cert-manager, or the component’s own injector) fills that field in after deployment.
The problem is that if another workload creates a resource in that API group before the injection completes, the API server calls the webhook, fails TLS verification, and rejects the whole request. On top of that, the jobset controller pod that was already running held a cached view of the webhook configuration from before the change, so it could not refresh itself even after the caBundle was filled in, and a restart was required.
In the early deployment script, both were papered over with a single sleep 30. Poll for caBundle injection instead. Keep the jobset controller restart needed in that environment out of the every-sync hook: run it as a separate operational action only when the stale-cache issue is confirmed, then check rollout status. Each rollout restart updates the pod template’s restartedAt, so it is not idempotent. Whether this wait belongs in PostSync depends on the environment: if the webhook blocks CR creation or Deployment readiness in an earlier wave, PostSync is never reached. In that case, arrange a readiness gate before applying the CR or change the controller/certificate injection order.
profile: controller convergence and PSS labels
Section titled “profile: controller convergence and PSS labels”Applying a Profile resource and the corresponding namespace actually existing are two different events. The Profile controller has to finish reconciling before the namespace, default RBAC, and ServiceAccount appear. This platform then has to apply Pod Security Standards labels to that namespace, but the target namespace does not exist as a manifest in Git, because it is a controller-created resource.
The workaround of writing the namespace manifest into Git directly should be avoided here. If Argo CD separately owns the same namespace while the Profile controller owns it, the two owners oscillate, each reverting the other’s labels and annotations. The correct remedy is to leave ownership with the controller and use a PostSync hook that waits for the namespace to appear and then patches only the labels.
knative / kserve: re-applying CRs after CRDs are established
Section titled “knative / kserve: re-applying CRs after CRDs are established”The knative and kserve overlays contain both CRDs and the CRs that use them in the same Application. Earlier installs sometimes treated CR creation failures as a reason to “just sync once more.” But when the CRD is in the same sync, Argo CD automatically skips dry-run for that CR. Do not attribute every such failure to dry-run; distinguish CRD establishment order, webhook readiness, and the actual apply error.
When a controller creates the CRD later in a different sync, SkipDryRunOnMissingResource=true can skip dry-run for the unknown type. It does not wait for CRD establishment or webhook readiness. In a single Application, check CRD/CR ordering and consider ServerSideApply=true only for a separate issue such as a large manifest exceeding the client-side apply limit. These conditions can reduce re-apply hooks, but combining the two options does not cure every first-install failure. Diagnose against Argo CD sync options first.
The mechanisms Argo CD offers and what each one covers
Section titled “The mechanisms Argo CD offers and what each one covers”Argo CD’s ordering and waiting features have similar names and are frequently confused. Here is which class of problem each mechanism actually solves.
| Mechanism | Problem it solves | Caveat |
|---|---|---|
argocd.argoproj.io/sync-wave | Ordering between resources inside one Application; ordering between Applications in App-of-Apps | Without health assessment it cannot wait for readiness. Health checks for Application CRs require separate configuration |
| PreSync hook | Preconditions that must hold before apply, such as a schema migration | A failure aborts the entire sync, so do not put irreversible destructive work here |
| Sync hook | Work that must run interleaved with ordinary resources in the same phase | The relative order against ordinary resources must be stated with waves |
| PostSync hook | Convergence waits and side-effect handling after everything is applied and Healthy | Wait for webhook injection here only when it does not block an earlier apply |
| SyncFail hook | Cleanup and notification on failure | It does not fix the cause of the failure |
hook-delete-policy | Lifetime management of hook resources | Choose among HookSucceeded, HookFailed, and BeforeHookCreation. Discussed below |
| Custom health check (Lua) | Teaching Argo CD what “this CR is ready” means | It makes wave waiting genuinely meaningful. The strongest tool for removing hooks entirely |
SkipDryRunOnMissingResource=true | Unknown-type dry-run failure when the CRD is not in the same sync | A CRD in the same sync already triggers automatic skipping; this does not fix apply/readiness failures |
ServerSideApply=true | Apply issues such as large manifests exceeding the client-side apply limit | Does not automatically resolve field ownership conflicts; inspect owners and policy |
Replace=true | Cases requiring replace/create instead of apply | Replaces existing resources; delete/create occurs when combined with Force=true. Check state impact before use |
The core judgment is simple. Ordering goes to waves, dry-run failures go to sync options, value injection and controller convergence waits go to hooks, and any hook that can be eliminated moves into a health check.
hook-delete-policy is especially prone to misunderstanding. Even when omitted, Argo CD assumes BeforeHookCreation. A fixed-name hook Job is deleted before its next creation, while the example’s ttlSecondsAfterFinished: 3600 can make the TTL controller clean up a completed or failed Job sooner. Do not assume the previous result is always retained; collect logs separately. HookSucceeded deletes successful Jobs promptly, shortening access to their Job/pod logs. See Argo CD hook lifecycle and Kubernetes Job TTL.
How sync waves and hooks run together
Section titled “How sync waves and hooks run together”The important part of the diagram is the wave 2 note: without an effective CR health check, Argo CD may not assess actual convergence. This flow reaches PostSync only if earlier resources apply successfully and become Healthy, and the webhook does not block CR application. If a custom health check can represent CR readiness, some of the wait can move into the wave.
Implementing the PostSync hook
Section titled “Implementing the PostSync hook”First, a ServiceAccount with scoped write access. This example only allows CRD reads for kubectl wait, reading the webhook configuration, and changing labels on a named namespace. Replace resourceNames with the actual deployment targets; if multiple namespaces are involved, design an explicit allowlist.
apiVersion: v1kind: ServiceAccountmetadata: name: platform-postsync namespace: <env>-platform annotations: argocd.argoproj.io/hook: PostSync argocd.argoproj.io/hook-delete-policy: BeforeHookCreation---apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata: name: platform-postsyncrules: - apiGroups: ["apiextensions.k8s.io"] resources: ["customresourcedefinitions"] verbs: ["get", "list", "watch"] - apiGroups: ["admissionregistration.k8s.io"] resources: ["validatingwebhookconfigurations"] resourceNames: ["trainer-validating-webhook"] verbs: ["get"] - apiGroups: [""] resources: ["namespaces"] resourceNames: ["<env>-tenant-a"] verbs: ["get", "patch"]---apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata: name: platform-postsyncroleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: platform-postsyncsubjects: - kind: ServiceAccount name: platform-postsync namespace: <env>-platformThere is no create, delete, or escalate, and the Job has no Deployment patch permission. Namespace patch is confined to a named target, not to PSS label fields: it can also modify other labels and annotations. Verify the name and controller ownership; add an admission policy if field restrictions are required.
Next, the hook Job itself.
apiVersion: batch/v1kind: Jobmetadata: name: trainer-postsync namespace: <env>-platform annotations: argocd.argoproj.io/hook: PostSync argocd.argoproj.io/hook-delete-policy: BeforeHookCreation argocd.argoproj.io/sync-wave: "20"spec: backoffLimit: 2 activeDeadlineSeconds: 900 ttlSecondsAfterFinished: 3600 template: spec: serviceAccountName: platform-postsync restartPolicy: Never containers: - name: converge image: <registry>/kubectl:<tag> command: ["/bin/sh", "-e", "/scripts/converge.sh"] volumeMounts: - name: scripts mountPath: /scripts resources: requests: cpu: 50m memory: 64Mi limits: memory: 128Mi volumes: - name: scripts configMap: name: trainer-postsync-scripts defaultMode: 0555sync-wave: "20" is set on the hook too. Hooks sometimes need ordering among themselves, and without a wave value all Jobs in the same hook phase start simultaneously.
The script is the heart of it. The one principle to hold here is that no fixed wait is used.
#!/bin/shset -eu
CRD="trainjobs.trainer.<cluster-domain>"WEBHOOK="trainer-validating-webhook"
# 1. Wait until the CRD is Established - returns as soon as the condition holdskubectl wait --for=condition=Established "crd/${CRD}" --timeout=180s
# 2. Poll until the controller injects the webhook caBundle.# While it is empty, admission calls fail TLS verification.deadline=$(( $(date +%s) + 300 ))while :; do bundle=$(kubectl get validatingwebhookconfiguration "${WEBHOOK}" \ -o jsonpath='{.webhooks[0].clientConfig.caBundle}' 2>/dev/null || true) [ -n "${bundle}" ] && break [ "$(date +%s)" -ge "${deadline}" ] && { echo "caBundle not injected within deadline" >&2 exit 1 } sleep 2 # a polling interval, not a guess at completiondoneecho "caBundle present (${#bundle} bytes)"
echo "trainer convergence complete"If the stale-cache problem recurs in the existing jobset controller, treat the restart as an operation separate from repeated syncs. First inspect the current context, target namespace, and Deployment read-only; assign the verified namespace to NS. Check permission to patch that Deployment and the affected workloads before running kubectl -n "$NS" rollout restart deployment/jobset-controller-manager, then confirm with kubectl -n "$NS" rollout status deployment/jobset-controller-manager --timeout=300s. This produces a new revision, so do not repeat it automatically. The caBundle polling above is valid in PostSync only if that webhook does not block application of earlier resources.
The profile-side script follows the same shape. It waits for the namespace, then applies both PSS labels conditionally. Pod Security Admission labels distinguish enforce from warn.
#!/bin/shset -eu
PROFILE_NS="<env>-tenant-a"
# Wait for the controller to create the namespace - the controller still owns itdeadline=$(( $(date +%s) + 300 ))until kubectl get namespace "${PROFILE_NS}" >/dev/null 2>&1; do [ "$(date +%s)" -ge "${deadline}" ] && { echo "profile namespace never appeared" >&2 exit 1 } sleep 2done
# Do nothing when both values are correct - re-running yields the same resultenforce=$(kubectl get namespace "${PROFILE_NS}" \ -o jsonpath='{.metadata.labels.pod-security\.kubernetes\.io/enforce}' 2>/dev/null || true)warn=$(kubectl get namespace "${PROFILE_NS}" \ -o jsonpath='{.metadata.labels.pod-security\.kubernetes\.io/warn}' 2>/dev/null || true)if [ "${enforce}" = "baseline" ] && [ "${warn}" = "baseline" ]; then echo "PSS labels already correct"else kubectl label namespace "${PROFILE_NS}" \ pod-security.kubernetes.io/enforce=baseline \ pod-security.kubernetes.io/warn=baseline \ --overwritefiWhy sleep is the anti-pattern
Section titled “Why sleep is the anti-pattern”sleep 30 gets two things wrong at once. When the cluster is slow it is too short and fails; when the cluster is fast it is too long and wastes deployment time. Worse, it tells you nothing about the cause when it fails. If the command after the sleep fails, the log shows only that command’s failure, and you cannot tell whether the wait was genuinely too short or the target was wrong all along.
The replacements sort into three layers.
- When the API server already knows the condition, use
kubectl wait --for=condition=.... Established CRDs, Available Deployments, and Complete Jobs belong here. - When it is a field value rather than a condition, use a polling loop with an explicit deadline. The
sleepinside that loop is a polling interval, not a guess at completion, so it is a different thing entirely. - When neither is possible, that is a signal to write a custom health check rather than to solve it with a hook.
All three layers share one property: on failure, the log records what it was waiting for when it gave up.
The rules that make hooks safe
Section titled “The rules that make hooks safe”Normal syncs may re-run hooks (selective syncs do not run them). With selfHeal enabled, drift can trigger another sync, so hooks must be idempotent and re-runnable. See Argo CD sync phases.
- Check the state and change it only when needed. That is why the PSS label script reads the current value first.
- Restrict verbs and targets. Even
label --overwriteshould run only if the current value needs changing.applyandpatchcan have side effects depending on input and target; they are not inherently idempotent. Everyrollout restartchangesrestartedAt. - Do not put destructive work in PreSync. If PreSync fails the whole sync stops, and at that moment the cluster is already half changed.
- Always set
activeDeadlineSecondsandbackoffLimit. A hook whose condition never holds pins the Application inProgressingforever. - Let the hook’s exit code tell the truth. If an unmet condition is swallowed as success, the hook becomes decoration that does nothing.
Shrinking the imperative surface
Section titled “Shrinking the imperative surface”Every hook is state that lives outside the declarative model, even when it sits in Git as a file. That script reads the cluster’s current state and branches on it, and the result never shows up in a manifest diff. The “Synced” you see in the Argo CD UI only means the hook succeeded; it says nothing about what the hook did.
So the number of hooks is not a value to maintain but a value to reduce. There are three real paths by which it goes down.
| Way it shrinks | Hook that disappears |
|---|---|
Considering ServerSideApply=true | A re-apply hook added for client-side apply size limits, when applicable |
| Writing a custom health check | Wait-only hooks that blocked on the previous wave becoming ready |
| Upstream fixing the controller | The rollout restart hook needed because of cached webhook configuration |
For knative/kserve, distinguish automatic dry-run skipping for a same-sync CRD from server-side apply when needed. The jobset restart stops being necessary if its underlying cause is fixed, but check the deployed upstream version before assuming that has happened. What remains is the case where controller-created resources must be adjusted afterwards, as with the Profile controller convergence wait, and one-time migrations.
One-time migrations alone cannot be eliminated. Instead they are handled differently: make them explicit one-shot work rather than a hook that runs on every repeated sync, and record the completion somewhere in the cluster so the next run skips itself. Done that way, the shape stays imperative but the re-run safety matches every other hook.
The goal is not to drive imperative steps to zero, but to know what is left and why it is left. That is the same reason this series started at the GitOps Architecture and ended here. Draw the boundary precisely, and what lies outside it becomes something you can manage too.