π€ The Push-to-Pull Paradigm Shift: Decoupling CI from In-Cluster CD
In legacy continuous delivery architectures, Jenkins operated as a heavyweight "Push-based" orchestrator: worker agents held highly privileged cluster-admin kubeconfig files, SSH keys, or cloud IAM roles, executing direct kubectl apply or helm upgrade commands against target Kubernetes clusters. This design violates least-privilege security principles, expands the blast radius of compromised CI agents, and fails to reconcile configuration drift when manual cluster mutations occur. GitOps inverts this relationship into a decoupled, pull-based reconciliation model. Jenkins fulfills its optimal mandate as a Continuous Integration Engine (validating code, testing, scanning, packaging OCI images, and cryptographically signing digests). To deploy, Jenkins executes an automated GitOps Handshake: writing updated image digests and manifests back to a dedicated Config/Manifest Git Repository. Downstream in-cluster reconciliation controllersβsuch as ArgoCD or Flux CDβdetect this commit, reconcile state against target Kubernetes clusters, and report health back via webhooks.
GITOPS CI/CD ORCHESTRATION TOPOGRAPHY:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β APP SOURCE CODE REPOSITORY (GitHub / GitLab) β
β Developer pushes commit β Jenkinsfile executes CI workflow β
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Step 1: Build, Test, Scan & Publish)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JENKINS CI ORCHESTRATION (COMPUTE ISOLATION) β
β β
β β’ Compiles source bytecode & executes unit/integration test suites β
β β’ Runs SonarQube quality gate & Trivy container vulnerability scan β
β β’ Builds OCI image & pushes to Registry: β
β registry.company.com/finance/ledger:142-7f8a9b0 (Immutable Digest: sha256:d8f3...) β
β β’ Cryptographically signs digest with Sigstore Cosign β
β β
β β
NOTICE: Jenkins holds ZERO credentials for target Kubernetes production clusters! β
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Step 2: Automated Git Write-Back / PR)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DEPLOYMENT MANIFEST REPOSITORY (GitOps Repo) β
β Repository: git@github.com:enterprise-org/k8s-fleet-manifests.git β
β β
β Automated Commit: β
β Author: Jenkins GitOps Bot <bot@company.com> β
β Message: "chore(release): update ledger to 142-7f8a9b0 [skip ci]" β
β β
β Target File: environments/staging/apps/ledger/kustomization.yaml β
β - newTag: 141-6e7d8a1 β
β + newTag: 142-7f8a9b0 β
ββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββ
β β
β (Step 3A: Optional Sync Webhook) β (Step 3B: Poll / Event)
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββ
β IN-CLUSTER CONTROLLER: ARGOCD β β IN-CLUSTER CONTROLLER: FLUX CD β
β (Namespace: argocd) β β (Namespace: flux-system) β
β β β β
β β’ Detects manifest update via Git webhookβ β β’ GitRepository CR & Kustomization CR β
β β’ Compares desired state (Git) against β β β’ Reconciles drift every 1m or via β
β live state (Kubernetes etcd) β β notification webhook receiver β
β β’ Executes rolling update / Canary sync β β β’ Applies server-side apply (SSA) β
β β’ Emits sync status to Slack / Datadog β β β’ Emits status to Kubernetes Events β
ββββββββββββββββββββ¬ββββββββββββββββββββββββ ββββββββββββββββββββ¬ββββββββββββββββββββββββ
β β
βΌ (Step 4: In-Cluster Workload Execution) βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TARGET KUBERNETES RUNTIME CLUSTER (EKS / GKE / AKS) β
β β’ Deployment / StatefulSet updated with zero external inbound network access β
β β’ Pods pull verified, signed image from private container registry β
β β’ Zero open inbound SSH or kubectl ports exposed to external CI systems β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../../../base/apps/ledger
namespace: finance-staging
# Container image override target patched by Jenkins
images:
- name: registry.company.com/finance/ledger
newTag: 141-6e7d8a1 # This exact field is mutated by CI upon successful build!
#!/usr/bin/env bash
# ==============================================================================
# Script: gitops_writeback.sh
# Purpose: Clones deployment repository, patches image tag via Kustomize,
# and commits change back to Git with conflict retry loops.
# ==============================================================================
set -euo pipefail
GITOPS_REPO="git@github.com:enterprise-org/k8s-fleet-manifests.git"
TARGET_ENV="${1:-staging}"
SERVICE_NAME="${2:-ledger}"
NEW_TAG="${3:-latest}"
WORK_DIR="/tmp/gitops-deploy-${BUILD_NUMBER}"
echo "[*] Step 1: Cloning GitOps manifest repository..."
rm -rf "${WORK_DIR}"
git clone --depth 1 --branch main "${GITOPS_REPO}" "${WORK_DIR}"
cd "${WORK_DIR}/environments/${TARGET_ENV}/apps/${SERVICE_NAME}"
echo "[*] Step 2: Mutating image tag via Kustomize CLI..."
# Cleanest mutation: Avoids regex/sed bugs and preserves YAML comments!
kustomize edit set image "registry.company.com/finance/${SERVICE_NAME}=registry.company.com/finance/${SERVICE_NAME}:${NEW_TAG}"
echo "[*] Step 3: Verifying rendered diff..."
git diff kustomization.yaml
echo "[*] Step 4: Committing and pushing with atomic retry loop..."
git config user.name "Jenkins GitOps Bot"
git config user.email "ci-bot@company.com"
git add kustomization.yaml
git commit -m "chore(${TARGET_ENV}): promote ${SERVICE_NAME} to tag ${NEW_TAG} [skip ci]"
# Rebase-retry loop to handle concurrent pipeline commits safely
MAX_RETRIES=5
COUNT=0
while [ "${COUNT}" -lt "${MAX_RETRIES}" ]; do
if git push origin main; then
echo "[β] Successfully pushed updated manifest to GitOps repository."
cd /tmp
rm -rf "${WORK_DIR}"
exit 0
fi
echo "[!] Push rejected due to concurrent commit. Pulling with rebase..."
git pull --rebase origin main
COUNT=$((COUNT + 1))
sleep 2
done
echo "[β] FATAL: Failed to push to GitOps repository after ${MAX_RETRIES} attempts!"
rm -rf "${WORK_DIR}"
exit 1
pipeline {
agent { label 'docker-capable-host' }
options {
timeout(time: 45, unit: 'MINUTES')
timestamps()
ansiColor('xterm')
disableConcurrentBuilds()
}
environment {
SERVICE_NAME = 'ledger-service'
REGISTRY_HOST = 'harbor.company.com'
IMAGE_NAME = "finance/${env.SERVICE_NAME}"
SHORT_SHA = "${env.GIT_COMMIT ? env.GIT_COMMIT.take(7) : 'manual'}"
IMAGE_TAG = "${env.BUILD_NUMBER}-${env.SHORT_SHA}"
FULL_IMAGE_URI = "${env.REGISTRY_HOST}/${env.IMAGE_NAME}:${env.IMAGE_TAG}"
GITOPS_DEPLOY_KEY_ID = 'gitops-repo-deploy-ssh-key'
}
stages {
stage('Compile & Test') {
steps {
echo "[*] Compiling application and executing unit test assertions..."
sh 'mvn clean test -B'
}
}
stage('Build & Publish OCI Container') {
steps {
echo "[*] Building container image: ${env.FULL_IMAGE_URI}"
sh "docker build -t ${env.FULL_IMAGE_URI} ."
echo "[*] Publishing image to enterprise registry..."
docker.withRegistry("https://${env.REGISTRY_HOST}", 'harbor-deploy-token') {
def img = docker.image(env.FULL_IMAGE_URI)
img.push()
}
}
}
stage('Security Vulnerability Gate') {
steps {
echo "[*] Auditing published container with Trivy..."
sh "trivy image --severity CRITICAL --exit-code 1 --ignore-unfixed ${env.FULL_IMAGE_URI}"
}
}
stage('GitOps Handshake: Promote to Staging') {
when {
branch 'main'
}
steps {
echo "[*] Initiating GitOps handshake: Updating staging manifest..."
// Inject dedicated SSH key that has write access ONLY to the k8s-fleet-manifests repository
withCredentials([sshUserPrivateKey(credentialsId: env.GITOPS_DEPLOY_KEY_ID,
keyFileVariable: 'GITOPS_SSH_KEY',
usernameVariable: 'GITOPS_SSH_USER')]) {
sh '''
export GIT_SSH_COMMAND="ssh -i ${GITOPS_SSH_KEY} -o StrictHostKeyChecking=no"
chmod +x ci/gitops_writeback.sh
./ci/gitops_writeback.sh staging ${SERVICE_NAME} ${IMAGE_TAG}
'''
}
echo "[β] GitOps repository updated. In-cluster reconciliation controllers will now deploy."
}
}
}
post {
always {
cleanWs notFailBuild: true
}
success {
slackSend(
channel: '#ci-deployments',
color: '#16834d',
message: ":white_check_mark: *GitOps Handshake Successful:* ${env.SERVICE_NAME} [${env.IMAGE_TAG}] committed to Staging manifest. ArgoCD/Flux syncing."
)
}
}
}
RECONCILIATION LATENCY ACCELERATION:
DEFAULT POLLING BEHAVIOR (UP TO 3 MINUTES LATENCY):
Jenkins pushes to GitOps Repo β ArgoCD repo-server polls every 180 seconds β Sync initiates.
Total Latency: 1 to 3 minutes of idle developer waiting.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ACCELERATED PIPELINE SYNCHRONIZATION:
Jenkins pushes to GitOps Repo
β
βββ OPTION A: REPOSITORY WEBHOOK (RECOMMENDED)
β GitHub automatically posts webhook to: https://argocd.company.com/api/webhook
β ArgoCD invalidates cache and triggers sync within 1 to 2 seconds!
β
βββ OPTION B: DIRECT ARGOCD REST API CALL FROM JENKINS
Jenkins invokes authenticated POST to ArgoCD server:
POST /api/v1/applications/ledger-staging/sync
ArgoCD forces instant synchronization and streams health metrics back to CI!
stage('ArgoCD Accelerated Sync & Health Wait') {
environment {
ARGOCD_SERVER = 'argocd.internal.company.com'
ARGOCD_APP_NAME = 'ledger-staging'
ARGOCD_AUTH_ID = 'argocd-ci-auth-token' // Stored as Secret Text
}
steps {
withCredentials([string(credentialsId: env.ARGOCD_AUTH_ID, variable: 'ARGOCD_TOKEN')]) {
echo "[*] Triggering instant sync on ArgoCD application: ${env.ARGOCD_APP_NAME}..."
sh '''
# 1. Trigger manual Application Sync
curl -s -f -k -X POST \
-H "Authorization: Bearer ${ARGOCD_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"revision": "main", "prune": true}' \
"https://${ARGOCD_SERVER}/api/v1/applications/${ARGOCD_APP_NAME}/sync"
echo "[*] Awaiting ArgoCD health status transition to 'Healthy'..."
# 2. Poll application status until Healthy (Timeout after 120s)
MAX_CHECKS=24
COUNT=0
while [ "${COUNT}" -lt "${MAX_CHECKS}" ]; do
STATUS_PAYLOAD=$(curl -s -f -k \
-H "Authorization: Bearer ${ARGOCD_TOKEN}" \
"https://${ARGOCD_SERVER}/api/v1/applications/${ARGOCD_APP_NAME}")
SYNC_STATUS=$(echo "${STATUS_PAYLOAD}" | jq -r .status.sync.status)
HEALTH_STATUS=$(echo "${STATUS_PAYLOAD}" | jq -r .status.health.status)
echo "[+] Status Check: Sync=${SYNC_STATUS} | Health=${HEALTH_STATUS}"
if [ "${SYNC_STATUS}" == "Synced" ] && [ "${HEALTH_STATUS}" == "Healthy" ]; then
echo "[β] ArgoCD reports application is fully Synced and Healthy!"
exit 0
elif [ "${HEALTH_STATUS}" == "Degraded" ]; then
echo "[β] FATAL: ArgoCD reports application entered DEGRADED state!"
exit 1
fi
COUNT=$((COUNT + 1))
sleep 5
done
echo "[β] Timeout waiting for ArgoCD application to become Healthy."
exit 1
'''
}
}
}
# flux-receiver.yaml (Committed to cluster infrastructure repo)
apiVersion: notification.toolkit.fluxcd.io/v1beta2
kind: Receiver
metadata:
name: jenkins-webhook-receiver
namespace: flux-system
spec:
type: generic
secretRef:
name: webhook-token # Secret containing pre-shared HMAC token
resources:
- kind: GitRepository
name: k8s-fleet-manifests
- kind: Kustomization
name: ledger-staging
stage('Notify Flux CD Receiver') {
environment {
FLUX_RECEIVER_URL = 'https://flux-receiver.internal.company.com/hook/7f8a9b0c1d2e...'
WEBHOOK_TOKEN_ID = 'flux-webhook-hmac-secret'
}
steps {
withCredentials([string(credentialsId: env.WEBHOOK_TOKEN_ID, variable: 'HMAC_TOKEN')]) {
echo "[*] Notifying Flux v2 notification-controller of new Git commit..."
sh '''
# Dispatch generic webhook payload authenticated via HMAC token
curl -s -i -X POST \
--data-binary '{"event": "jenkins_push", "revision": "'${IMAGE_TAG}'"}' \
"${FLUX_RECEIVER_URL}"
echo "[β] Flux receiver triggered. Reconciliation loop scheduled immediately."
'''
}
}
}
GITOPS REPOSITORY STRUCTURAL MODELS:
MODEL 1: DIRECTORY-PER-ENVIRONMENT (RECOMMENDED ENTERPRISE STANDARD)
Repository: git@github.com:enterprise-org/k8s-fleet-manifests.git (Single 'main' Branch)
βββ base/ <-- Shared foundational manifests
β βββ ledger/
β βββ deployment.yaml
β βββ service.yaml
βββ environments/
βββ dev/ <-- Direct commit from CI on feature PRs
β βββ apps/ledger/kustomization.yaml
βββ staging/ <-- Direct commit from CI on main branch merge
β βββ apps/ledger/kustomization.yaml
βββ production/ <-- MODIFIED STRICTLY VIA PULL REQUEST!
βββ apps/ledger/kustomization.yaml
PROMOTION WORKFLOW:
1. Dev / Staging: Automated commits by Jenkins bot directly to 'main' branch.
2. Production: Jenkins DOES NOT push directly to production!
Jenkins automatically opens a Pull Request:
"chore(production): promote ledger to version 142-7f8a9b0"
Lead SRE reviews PR, reviews automated test results, and clicks "Merge".
ArgoCD detects PR merge and syncs to production!
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MODEL 2: BRANCH-PER-ENVIRONMENT (ANTI-PATTERN FOR MANIFESTS)
Branches: 'dev', 'stage', 'prod'
β’ Problem: Git merge conflicts constantly occur when merging 'dev' into 'prod' because environment-
specific configurations (replicas: 10 vs replicas: 1) collide. Directory-per-environment eliminates this!
stage('Create Production Promotion Pull Request') {
when {
buildingTag() // Triggered exclusively when a semantic release tag is pushed
}
steps {
withCredentials([string(credentialsId: 'github-bot-token', variable: 'GH_TOKEN'),
sshUserPrivateKey(credentialsId: 'gitops-deploy-key', keyFileVariable: 'SSH_KEY')]) {
echo "[*] Creating production release branch and Pull Request..."
sh '''
export GIT_SSH_COMMAND="ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no"
# Clone deployment repo
git clone git@github.com:enterprise-org/k8s-fleet-manifests.git /tmp/gitops-prod
cd /tmp/gitops-prod
# Create dedicated promotion branch
BRANCH_NAME="promote-${SERVICE_NAME}-${TAG_NAME}"
git checkout -b "${BRANCH_NAME}"
# Patch production kustomization
cd environments/production/apps/${SERVICE_NAME}
kustomize edit set image "registry.company.com/finance/${SERVICE_NAME}=registry.company.com/finance/${SERVICE_NAME}:${TAG_NAME}"
git commit -am "chore(production): release ${SERVICE_NAME} ${TAG_NAME}"
git push origin "${BRANCH_NAME}"
# Use GitHub CLI to create formal pull request for SRE approval
gh pr create \
--repo enterprise-org/k8s-fleet-manifests \
--head "${BRANCH_NAME}" \
--base main \
--title "π Production Release: ${SERVICE_NAME} ${TAG_NAME}" \
--body "Automated promotion request generated by Jenkins Build #${BUILD_NUMBER}. Verified by Staging Smoke Tests." \
--reviewer "enterprise-org/sre-leads"
'''
}
}
}
THE INFINITE RECURSIVE CI LOOP DEFECT:
SCENARIO: Monorepo containing both source code AND manifests without proper filtering.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DEVELOPER COMMITS CODE β PUSH TO GIT β
ββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JENKINS BUILDS CONTAINER & PUSHES MANIFEST COMMIT β
β Commit: "update image tag to 142" β
ββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
β GitHub sees NEW commit on repo β Dispatches Webhook!
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JENKINS SEES NEW COMMIT β TRIGGERS NEW BUILD (#143)! β
β β’ Build #143 builds container... β
β β’ Build #143 pushes manifest commit "update to 143"... β
β β’ CATASTROPHE: Pipeline triggers Build #144 in an β
β INFINITE RECURSIVE LOOP, exhausting compute! β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
THE DUAL-REMEDIATION ARCHITECTURE:
1. THE COMMIT MESSAGE TAG:
Always append '[skip ci]' or '[ci skip]' to automated manifest commits:
git commit -m "chore(staging): promote ledger to 142 [skip ci]"
All major CI engines (Jenkins, GitHub Actions, GitLab) natively ignore commits
containing '[skip ci]'.
2. DEDICATED REPOSITORY SEPARATION:
Maintain a strict physical boundary:
β’ Repository A: 'payment-service' (Contains ONLY source code and Jenkinsfile)
β’ Repository B: 'k8s-fleet-manifests' (Contains ONLY Kubernetes YAML and Helm values)
Jenkins pushes commits to Repository B, which NEVER triggers a rebuild of Repository A!
COMMON GITOPS HANDSHAKE DEFECTS & REMEDIATIONS:
1. ERROR: "git push origin main: [remote rejected] (fetch first) error: failed to push some refs"
β’ Symptom: Jenkins fails during the Git write-back step with a concurrent modification rejection.
β’ Cause: Another pipeline (e.g. Order Service) committed a manifest change to the GitOps repo
at the exact same second, advancing the remote HEAD.
β’ Remediation: Implement the rebase-retry loop shown in Section 2:
git pull --rebase origin main && git push origin main
2. ERROR: "Host key verification failed / Permission denied (publickey)"
β’ Symptom: The pipeline cannot clone or push to the GitOps repository.
β’ Cause: The SSH deploy key registered in GitHub lacks "Write" access (GitHub defaults deploy keys to read-only!).
β’ Remediation: In GitHub: GitOps Repo β Settings β Deploy Keys β Check "Allow write access".
3. ARGOCD SYNC STATE HANGS IN 'OUTOFSYNC' / 'PROGRESSING':
β’ Symptom: Jenkins updates Git, but ArgoCD displays a yellow synchronization icon for 20 minutes.
β’ Causes:
- Case A: A Kubernetes manifest specifies a container image tag that was never pushed to the registry (ImagePullBackOff).
- Case B: An immutable field in a Kubernetes Service or StatefulSet was modified, which Kubernetes rejects.
β’ Remediation: Inspect ArgoCD live diff:
argocd app diff <app-name>
argocd app get <app-name> --show-operation-details
4. MERGE CONFLICTS IN KUSTOMIZATION.YAML:
β’ Cause: Manually editing the 'kustomization.yaml' file on the remote Git repository while
pipelines are running automated write-backs.
β’ Remediation: Treat the 'environments/staging' manifests as machine-owned files. Never edit
image tags manually on branches where CI bots push changes.
GITOPS HANDSHAKE TECHNICAL SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β ARCHITECTURAL COMPONENT β TECHNICAL TOOLCHAIN β PROTOCOL / API β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Manifest Mutation β Kustomize (set image) / yq β CLI Tooling β Updates container tag in YAML β
β Write-Back Target β Dedicated Manifest Repositoryβ Git over SSH/TLS β Immutable deployment log β
β In-Cluster Controller β ArgoCD / Flux CD β Pull-based K8s β Reconciles Git to live state β
β Sync Acceleration β ArgoCD REST API / Webhooks β HTTP POST (JSON) β Slashes 3-minute polling lag β
β Flux Event Receiver β Notification Controller β HMAC Webhook β Triggers instant Git fetch β
β Production Promotion β GitHub CLI (gh pr create) β SCM Pull Request β Enforces human SRE approval β
β Infinite Loop Guard β [skip ci] in commit message β SCM Header Match β Blocks recursive build storms β
β Credential Boundary β Zero cluster-admin in CI β Least Privilege β Hardens CI against K8s breach β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 GITOPS HANDSHAKE AXIOMS FOR DEVOPS SREs: β
β 1. Zero Direct Cluster Access: Jenkins must never execute 'kubectl apply' against production environments.β
β 2. Mutate via Kustomize: Use 'kustomize edit set image' rather than brittle sed/regex replacements. β
β 3. Atomic Rebase Loops: Implement retry loops on Git push to handle concurrent multi-service commits. β
β 4. Decouple Repositories: Maintain separate Git repos for source code vs. Kubernetes deployment manifests.β
β 5. Pull Requests for Production: Automate staging deployments; require approved Git PRs for production. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ