GitOps promotion gates¶
Make Flux or Argo CD stop the next rollout step when a service breaks its
contract. For Kargo, see Kargo. A NonCompliant
Pacto turns the Kustomization unready or the Application Degraded.
The health snippets stop the next step: by the time the operator has a
verdict the pods are already serving. The Argo CD plugin
stops the render, before Argo CD applies anything. With Flux, catch a
breaking change in the pull request with pacto impact.
Flux and Argo CD read status.contractStatus only through an extension point,
which the two health snippets below configure.
Flux¶
Flux decides health with kstatus, its built-in status reader, which recognises
only the Ready, Reconciling and Stalled conditions. Pacto publishes ContractValid, RuntimeObserved and
ReadinessSatisfied, so kstatus discards all three and the object falls through
to Current: the gate looks configured and passes everything.
spec.healthCheckExprs (kustomize-controller v1.5.0, flux2 v2.5.0 and later)
replaces that fallback with a CEL expression:
# Flux promotion gate driven by the Pacto contract verdict.
#
# This file is published verbatim in integrations/kubernetes/docs/gitops.md and
# applied verbatim by tests/acceptance/kind/gitops-flux.sh. Edit it and you edit
# both; the documented snippet cannot drift from the tested one.
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: orders-staging
namespace: flux-system
spec:
interval: 1m
# Must exceed the operator's stabilization window (default 2m) plus one
# requeue interval, or a real violation arrives as an ambiguous timeout
# instead of a clean failure.
timeout: 5m
prune: true
wait: true
sourceRef:
kind: OCIRepository
name: orders
path: ./staging
healthCheckExprs:
- apiVersion: pacto.trianalab.io/v1alpha1
kind: Pacto
failed: status.contractStatus in ['NonCompliant', 'Invalid']
current: status.contractStatus in ['Compliant', 'Reference', 'Warning']
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: orders-production
namespace: flux-system
spec:
interval: 1m
timeout: 5m
prune: true
wait: true
# Production does not start until staging is healthy, and healthy now
# includes the contract verdict. This line is the promotion gate.
dependsOn:
- name: orders-staging
sourceRef:
kind: OCIRepository
name: orders
path: ./production
sourceRef is whatever you already use. Three things about that snippet, each
checked against fluxcd/pkg runtime/cel/status_evaluator.go:
- The snippet leaves out
inProgresson purpose. When no expression matches, Flux falls through to in-progress, so an unrecognised verdict holds the deploy until it times out. It fails closed. Warningsits in the passing set. Move that one word tofailedif you want contract warnings to block promotions. That is the whole knob.timeoutmust exceed the operator's stabilization window, or a real violation reaches you as an ambiguous timeout. See Timing.
A freshly created Pacto has no status and the expression errors while that is
true; Flux treats the error as not-yet-healthy and keeps polling.
tests/acceptance/kind/gitops-flux.sh applies that exact file to a kind cluster and asserts the dependent
Kustomization never reaches it while the contract is violated.
Argo CD¶
Argo picks a health check from a fixed list of built-in kinds and returns no
health for any other kind. The roll-up into Application health skips a resource
with no health, so Argo ignores a Pacto. A resource health customization in
argocd-cm supplies the missing check:
# Argo CD health customization that makes a violated Pacto contract turn its
# Application red.
#
# This file is published verbatim in integrations/kubernetes/docs/gitops.md.
# Apply it as a MERGE PATCH, never as a plain `kubectl apply` -- argocd-cm holds
# Argo's own keys and a full apply would drop them:
#
# kubectl -n argocd patch configmap argocd-cm --type merge \
# --patch-file argocd-cm-pacto-health.yaml
#
# The data key must be typed exactly. Argo silently ignores a key it does not
# recognise, which looks identical to having configured nothing at all.
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-cm
namespace: argocd
data:
resource.customizations.health.pacto.trianalab.io_Pacto: |
-- Argo runs this with the Lua string library disabled.
-- Only concatenation, comparison, ipairs and tostring() are available.
-- Set to "Degraded" to make contract warnings block a promotion.
local warningHealth = "Healthy"
local hs = {}
if obj.status == nil or obj.status.contractStatus == nil then
hs.status = "Progressing"
hs.message = "waiting for the first contract evaluation"
return hs
end
if obj.status.observedGeneration ~= obj.metadata.generation then
hs.status = "Progressing"
hs.message = "contract not yet evaluated at this generation"
return hs
end
local s = obj.status.contractStatus
if s == "Compliant" or s == "Reference" then
hs.status = "Healthy"
hs.message = "contract satisfied"
return hs
end
if s == "Warning" then
hs.status = warningHealth
hs.message = "contract satisfied with warnings"
return hs
end
if s == "NonCompliant" then
hs.status = "Degraded"
hs.message = "contract violated"
if obj.status.findings ~= nil then
for _, f in ipairs(obj.status.findings) do
if f.severity == "error" then
hs.message = "contract violated: " .. tostring(f.code) .. ": " .. tostring(f.message)
break
end
end
end
return hs
end
if s == "Invalid" then
hs.status = "Degraded"
hs.message = "contract is invalid and could not be evaluated"
return hs
end
-- Unknown, NotEvaluated, and anything added later.
hs.status = "Progressing"
hs.message = "contract verdict pending: " .. tostring(s)
return hs
Apply it as a merge patch, because argocd-cm holds Argo's own configuration
and a plain kubectl apply would drop it. Then restart the controller:
kubectl -n argocd patch configmap argocd-cm --type merge \
--patch-file argocd-cm-pacto-health.yaml
kubectl -n argocd rollout restart statefulset/argocd-application-controller
The restart is required. The application controller reads health
customizations into its resource cache at startup, and that cached verdict is
what it compares to decide whether a changed object needs re-examining. Until it
has the customization, every verdict the operator writes compares equal to the
last and the Application only catches up on the next periodic resync. On a core
install, without argocd-server, a restart is the only way in: hot reload of
argocd-cm needs server.secretkey, which only argocd-server creates.
In the Lua, anything unrecognised becomes Progressing. Argo's Unknown
ranks worse than Degraded and would mask broken workloads, so the script never
returns it. The string library is also disabled, so
string.format and s:gsub() fail at runtime, after the script loads.
tests/acceptance/kind/gitops-argocd.sh runs that exact file through the
Lua sandbox with no cluster, and then inside a kind cluster where an Application
must go Degraded naming the finding and back to Healthy once corrected.
Check that it took¶
Argo ignores a data key it does not recognise, and an ignored key looks
exactly like having configured nothing:
# The key must read back exactly, group and kind included.
kubectl -n argocd get cm argocd-cm \
-o jsonpath='{.data.resource\.customizations\.health\.pacto\.trianalab\.io_Pacto}'
Then ask Argo what it makes of a real object. argocd admin settings evaluates
the customization against files on disk, in the same Lua sandbox the controller
uses, so it answers without waiting for a sync:
kubectl -n argocd get cm argocd-cm -o yaml > /tmp/argocd-cm.yaml
kubectl -n <namespace> get pacto <name> -o yaml > /tmp/pacto.yaml
argocd admin settings resource-overrides health /tmp/pacto.yaml \
--argocd-cm-path /tmp/argocd-cm.yaml
A Compliant Pacto prints STATUS: Healthy and MESSAGE: contract satisfied.
A key that did not take prints Health script is not configured while
exiting 0, so read the output and ignore the exit code. Both checks read the
ConfigMap, so they also pass on a controller that started before the patch.
Gate every Argo CD sync¶
A Config Management Plugin sidecar on argocd-repo-server gates every
auto-detected Application whose folder holds a contract pacto.yaml. It
renders the folder with helm template or kustomize build, then runs
pacto impact --running on the rendered Pacto object's contractRef, or on
pacto.yaml when the render holds none. That judges the contract against the
revisions that run on known targets, read from the signed
target snapshots.
Argo CD receives the manifests only after a pass.
An Application that sets spec.source.helm, kustomize or directory skips
plugin discovery, so its editors can opt out: restrict who edits Applications
with AppProjects and Argo CD RBAC.
apiVersion: v1
kind: ConfigMap
metadata:
name: pacto-cmp-plugin
namespace: argocd
data:
plugin.yaml: |
apiVersion: argoproj.io/v1alpha1
kind: ConfigManagementPlugin
metadata:
name: pacto
spec:
discover:
# A contract has neither top-level key; a Pacto object saved as
# pacto.yaml has both, and is left to Argo CD's own detection.
find:
command:
- sh
- -c
- 'test -f pacto.yaml && ! grep -qE "^(apiVersion|kind):" pacto.yaml && echo pacto.yaml'
generate:
command: [sh, /home/argocd/cmp-server/config/generate.sh]
generate.sh: |
# Pacto sync gate: render, judge the contract the render applies against
# what runs, and print the manifests only after a pass. Stdout is the
# manifest stream, so nothing else writes to it.
set -u
fail() { echo "pacto plugin: $*" >&2; exit 1; }
# Unpinned (no word, or a word without :cluster-) reads only the clusters
# that published a tag right now, so a missing one reads as no consumers.
pinned=false
for ref in ${PACTO_TARGET_SNAPSHOT:-}; do
case "$ref" in
*:cluster-*) pinned=true ;;
*) pinned=false; break ;;
esac
done
if [ "$pinned" != true ] && [ "${PACTO_ALLOW_CLUSTER_DISCOVERY:-false}" != true ]; then
fail "pin each destination cluster (oci://<registry>/pacto-targets:cluster-<uid>)"
fi
work=$(mktemp -d /tmp/pacto-cmp.XXXXXX) || fail "cannot create a temp folder under /tmp"
trap 'rm -rf "$work"' EXIT
render="$work/render.yaml"
# Render with the folder's own tool. Registry credentials meant for Pacto
# never reach helm or kustomize.
if [ -f Chart.yaml ]; then
(
unset PACTO_REGISTRY_USERNAME PACTO_REGISTRY_PASSWORD PACTO_REGISTRY_TOKEN
if [ -f Chart.lock ] && [ ! -d charts ]; then
helm dependency build . >&2 || exit 1
fi
set -- template "${ARGOCD_APP_NAME:-}" . --namespace "${ARGOCD_APP_NAMESPACE:-}" --include-crds
if [ -n "${KUBE_VERSION:-}" ]; then set -- "$@" --kube-version "$KUBE_VERSION"; fi
IFS=,
for v in ${KUBE_API_VERSIONS:-}; do set -- "$@" --api-versions "$v"; done
unset IFS
exec helm "$@"
) > "$render" || fail "helm template failed"
elif [ -f kustomization.yaml ] || [ -f kustomization.yml ] || [ -f Kustomization ]; then
(
unset PACTO_REGISTRY_USERNAME PACTO_REGISTRY_PASSWORD PACTO_REGISTRY_TOKEN
# shellcheck disable=SC2086 # build options are a word list
exec kustomize build ${PACTO_KUSTOMIZE_BUILD_OPTIONS:-} .
) > "$render" || fail "kustomize build failed"
else
fail "${ARGOCD_APP_SOURCE_PATH:-$PWD} has no Chart.yaml or kustomization.yaml; add one, or exclude the folder from the plugin"
fi
# The contract the render applies: the contractRef.oci of its Pacto objects.
refs=$(awk '
function flush() { if (pacto) for (i = 1; i <= n; i++) print r[i]; pacto = 0; n = 0 }
/^---/ { flush(); next }
/^kind:[ \t]*Pacto[ \t]*$/ { pacto = 1 }
/^[ \t]+oci:[ \t]*[^ \t]/ { v = $0; sub(/^[ \t]+oci:[ \t]*/, "", v); gsub(/["'\'' \t]/, "", v); r[++n] = v }
END { flush() }' "$render" | sed 's|^oci://||; s|^|oci://|' | sort -u)
contract=.
if [ -n "$refs" ]; then
if [ "$(echo "$refs" | wc -l)" -ne 1 ]; then
fail "ERROR rendered contractRef values disagree: $(echo "$refs" | tr '\n' ' ')"
fi
contract=$refs
# service.version of the folder contract, block or flow style.
want=$(awk '
function out(v) { sub(/^[ \t]*version:[ \t]*/, "", v); gsub(/["'\'' \t]/, "", v); print v; exit }
/^service:/ { if (match($0, /version:[ \t]*[^,} \t]+/)) out(substr($0, RSTART, RLENGTH)); svc = 1; ind = ""; next }
/^[^ \t#]/ { svc = 0 }
svc && /^[ \t]+[^ \t#]/ { match($0, /^[ \t]+/); i = substr($0, 1, RLENGTH); if (ind == "") ind = i; if (i == ind && $0 ~ /^[ \t]+version:/) out($0) }' pacto.yaml 2> /dev/null)
path=${refs##*/}
case "$path" in
*@*) ;;
*:*) if [ -n "$want" ] && [ "${path##*:}" != "$want" ]; then
fail "ERROR rendered contractRef $refs does not match pacto.yaml $want"
fi ;;
esac
fi
# The installation's config only: the folder's pacto.yaml is the
# contract, and would otherwise be read as Pacto's config.
set -- impact --running --local "" --config /etc/pacto/config.yaml
for ref in ${PACTO_TARGET_SNAPSHOT:-}; do set -- "$@" --target-snapshot "$ref"; done
pacto "$@" "$contract" > "$work/out" 2> "$work/err"
rc=$?
# The full text goes to the sidecar log. Argo CD shows the render error
# to every Application reader, and a repository writer picks the service
# judged, so the reason (consumers, clusters, refs) stays in the log
# unless the installation sets PACTO_SHOW_REASON=true.
{ cat "$work/err" > "${PACTO_PLUGIN_LOG:-/proc/1/fd/2}"; } 2> /dev/null || true
reason="(the reason is in the pacto container log of argocd-repo-server)"
if [ "${PACTO_SHOW_REASON:-false}" = true ]; then
reason=$(head -n 1 "$work/err" | sed 's/^unverified: //' | cut -c1-512)
fi
allow=false
case "${PACTO_ALLOW_UNVERIFIED:-false}" in
true) allow=true ;;
per-application) [ "${ARGOCD_ENV_PACTO_ALLOW_UNVERIFIED:-false}" = true ] && allow=true ;;
esac
case "$rc" in
0) ;;
2) if [ "$allow" != true ]; then
echo "pacto impact: UNVERIFIED $reason, exit 2" >&2
exit 2
fi ;;
1) if [ -s "$work/out" ]; then
echo "pacto impact: BLOCKED $reason, exit 1" >&2
else
echo "pacto impact: ERROR $reason, exit 1" >&2
fi
exit 1 ;;
*) echo "pacto impact: ERROR $reason, exit $rc" >&2
exit 1 ;;
esac
cat "$render"
The patch adds no ServiceAccount, Role or binding:
# Strategic merge patch for argocd-repo-server: a Pacto Config Management
# Plugin sidecar. Apply it once; no Application changes.
# kubectl -n argocd patch deployment argocd-repo-server --patch-file argocd-repo-server-pacto-patch.yaml
# Change PACTO_TARGET_SNAPSHOT: one pinned tag per Argo CD destination cluster.
# Registry credentials: mount a host-keyed docker config and set DOCKER_CONFIG;
# PACTO_REGISTRY_* would send its credentials to every host Pacto pulls from.
apiVersion: apps/v1
kind: Deployment
metadata:
name: argocd-repo-server
namespace: argocd
spec:
template:
spec:
initContainers:
- name: pacto-install
image: ghcr.io/trianalab/pacto/dashboard:4.6.1
command: [cp, /usr/local/bin/pacto, /pacto/bin/pacto]
securityContext:
runAsNonRoot: true
runAsUser: 65532
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop: [ALL]
volumeMounts:
- name: pacto-bin
mountPath: /pacto/bin
containers:
- name: pacto
image: quay.io/argoproj/argocd:v3.5.2
command: [/var/run/argocd/argocd-cmp-server]
env:
- name: PATH
value: /pacto/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
- name: HOME
value: /tmp
- name: PACTO_NO_UPDATE_CHECK
value: "1"
- name: PACTO_TARGET_SNAPSHOT
value: oci://ghcr.io/acme/pacto-targets:cluster-<uid-a> oci://ghcr.io/acme/pacto-targets:cluster-<uid-b>
- name: PACTO_DELIVERY_TRUST
value: /etc/pacto/trust.yaml
- name: PACTO_ALLOW_UNVERIFIED
value: "false"
- name: PACTO_SHOW_REASON
value: "false"
- name: PACTO_KUSTOMIZE_BUILD_OPTIONS
value: ""
securityContext:
runAsNonRoot: true
runAsUser: 999
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop: [ALL]
seccompProfile:
type: RuntimeDefault
volumeMounts:
- name: var-files
mountPath: /var/run/argocd
- name: plugins
mountPath: /home/argocd/cmp-server/plugins
- name: pacto-cmp-plugin
mountPath: /home/argocd/cmp-server/config
- name: pacto-bin
mountPath: /pacto/bin
- name: pacto-tmp
mountPath: /tmp
- name: pacto-trust
mountPath: /etc/pacto
volumes:
- name: pacto-bin
emptyDir: {}
- name: pacto-tmp
emptyDir: {}
- name: pacto-cmp-plugin
configMap:
name: pacto-cmp-plugin
- name: pacto-trust
configMap:
name: pacto-trust
kubectl apply -f argocd-cmp-pacto.yaml
kubectl -n argocd create configmap pacto-trust --from-file=trust.yaml
kubectl -n argocd patch deployment argocd-repo-server \
--patch-file argocd-repo-server-pacto-patch.yaml
tests/acceptance/gitopsplugin and tests/acceptance/kind/gitops-argocd-sync.sh
run that exact script.
Point it at your clusters¶
Change one line: PACTO_TARGET_SNAPSHOT holds one
oci://<registry>/pacto-targets:cluster-<uid> word per destination cluster,
published by each cluster's operator (see
Target snapshot). A missing tag reads
partial. An empty value, or a word without :cluster-, is refused unless
PACTO_ALLOW_CLUSTER_DISCOVERY=true.
trust.yaml holds one entry per cluster, from its installation key and scoped
to its UID: see Target snapshot consumers
and the registry value.
For registry reads, mount a host-keyed Docker config and set DOCKER_CONFIG,
or use workload identity. PACTO_REGISTRY_* sends its credentials to every
host Pacto pulls from; the plugin unsets it before Helm or Kustomize. Running
revisions are pulled only from the snapshot hosts and an oci://
contractRef's host, plus the comma-separated PACTO_RUNNING_REGISTRIES;
any other host makes the answer unverified. The plugin reads Pacto settings
from /etc/pacto/config.yaml in the trust ConfigMap, if present, and never
from the folder's pacto.yaml, which is the contract.
Exit codes¶
pacto impact |
The render | Message |
|---|---|---|
0 clear |
Passes | |
1 blocked |
Fails | pacto impact: BLOCKED |
1, could not run |
Fails | pacto impact: ERROR |
2 unverified |
Fails unless allowed | pacto impact: UNVERIFIED |
A rendered contractRef whose tag disagrees with service.version fails
with pacto plugin: ERROR; a digest contractRef has no tag to compare and is
judged as rendered. PACTO_ALLOW_UNVERIFIED decides exit 2: false
(default, also any unknown value) fails, true renders, per-application
renders only for an Application with
spec.source.plugin.env: [{name: PACTO_ALLOW_UNVERIFIED, value: "true"}].
What the message shows¶
$ argocd app get payments
CONDITION MESSAGE
ComparisonError ... plugin pacto: pacto impact: BLOCKED (the reason is in the pacto container log of argocd-repo-server), exit 1
Core installs read the Application's ComparisonError condition. The full
reason is in the pacto container log (PACTO_PLUGIN_LOG names another
file). The plugin judges whatever service the folder or its rendered Pacto
object names, so anyone who can write to a repository the plugin renders
could otherwise read consumer names, clusters and refs of any service in the
snapshot through their own Application. With PACTO_SHOW_REASON=true the
message carries the first line of the reason, cut at 512 bytes: set it only
when every writer of those repositories may read the snapshot. Either way,
Application readers see the verdict.
Before you install¶
spec.source.helmvalues and parameters skip the plugin; keep values in the chart folder.- Copy
argocd-cmkustomize.buildOptionsintoPACTO_KUSTOMIZE_BUILD_OPTIONS. - A folder with no
Chart.yamlor Kustomization fails the render.
Fallback: a PreSync Job per Application¶
An Application with an explicit source type can run this hook on its published bundle, one Job each; exit 1 or 2 fails the sync:
# Per-Application fallback: a PreSync hook that runs pacto impact on the
# published bundle before Argo CD applies anything. Exit 1 or 2 fails the sync.
# To let an unverified answer pass, replace args with:
# command: [sh, -c]
# args: ['pacto impact --running oci://ghcr.io/acme/payments:2.0.0 --local "" --target-snapshot oci://ghcr.io/acme/pacto-targets:cluster-<uid> || [ $? -eq 2 ]']
apiVersion: batch/v1
kind: Job
metadata:
name: pacto-impact
annotations:
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
automountServiceAccountToken: false
containers:
- name: pacto-impact
image: ghcr.io/trianalab/pacto/dashboard:4.6.1
args:
- impact
- --running
- oci://ghcr.io/acme/payments:2.0.0
- --local
- ""
- --target-snapshot
- oci://ghcr.io/acme/pacto-targets:cluster-<uid>
env:
- name: HOME
value: /tmp
- name: PACTO_NO_UPDATE_CHECK
value: "1"
- name: PACTO_DELIVERY_TRUST
value: /etc/pacto/trust.yaml
securityContext:
runAsNonRoot: true
runAsUser: 65532
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop: [ALL]
volumeMounts:
- name: pacto-tmp
mountPath: /tmp
- name: pacto-trust
mountPath: /etc/pacto
volumes:
- name: pacto-tmp
emptyDir: {}
- name: pacto-trust
configMap:
name: pacto-trust
Kargo¶
Kargo verifies Freight after each promotion. One shared
ClusterAnalysisTemplate runs pacto impact --running on the Freight's
contract bundle in every Stage: see Kargo.
Timing¶
The gate is as fresh as the verdict behind it, and verdicts land at different speeds.
| Change | When it becomes NonCompliant |
|---|---|
| A mismatch: workload, persistence or configuration conformance | The first reconcile after the workload is observed |
| An absence: a missing interface, capability, dependency, Secret or ConfigMap | After the stabilization window (default two minutes) plus one requeue interval |
That split is why timeout has a floor: five minutes against the default
two-minute window leaves room for the window, one requeue and the apply.
Argo re-examines a Pacto when its health status changes, so Healthy to
Degraded shows up in about a second. But one NonCompliant reason replaced by
another keeps the stale message until the next periodic resync. The status
changes at once and the message catches up later.
Limits¶
- Argo health customizations are instance-global. One Argo serving several
teams cannot give one a blocking
Warningand another a passing one. - Flux cannot refuse an artifact for what is inside it. There, "reject this because it breaks three consumers" is a pull-request check.
- The plugin gates discovered Applications only, and judges at render time: a consumer deployed later counts at the next render or hard refresh.
ARGOCD_EXEC_TIMEOUT(default 90 seconds) bounds the render andpacto impacttogether; each snapshot read stops at 20 seconds.- Each destination cluster is pinned by hand in
PACTO_TARGET_SNAPSHOT. - The verdict is about the contract.
Compliantsays the workload matches its contract. It says nothing about request errors or saturation. status.lastReconciledAtcannot gate on freshness. Neither tool hands the expression a clock.