GitOps & Platform Engineering
Git is the source of truth. Declarative. Versioned. Automated. Reconciled. Learn ArgoCD, Flux, Crossplane, and how to build self-service Internal Developer Platforms.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: Building Real Internal Developer Platforms · Enterprise GitOps: FluxCD, ESO & Multi-Cluster · Alerting on Drift: argocd_app_info and an OutOfSync Rule
- Why it matters
- A required lesson for DevOps Engineer, Platform Engineer, Release / CI-CD Engineer, DevOps / Platform Architect. Recommended for DevSecOps Engineer, Container/Kubernetes Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 11 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 12.1
GitOps: desired state lives in Git. Operators continuously reconcile actual state to desired state. Everything is auditable, reviewable, and reversible.
Core Components 12.2
| Tool | Key Resources | Primary Strength |
|---|---|---|
| ArgoCD | Application, AppProject, ApplicationSet | Great UI, RBAC, sync waves |
| Flux | GitRepository, Kustomization, HelmRelease | Lightweight, native GitOps |
| Crossplane | XRD, Composition, Claim | Self-service infrastructure |
| Backstage | Software catalog + templates | Internal Developer Portal |
WSL Hands-On Lab 12.3
ArgoCD + ApplicationSet + Flux + Crossplane Composition on kind
$ kubectl create ns argocd $ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml $ flux bootstrap github --owner=$GITHUB_USER --repository=platform-gitops
- Install ArgoCD on kind cluster and access the UI
- Create an Application CR and successfully sync a sample app
- Create an ApplicationSet that generates apps for multiple environments
- Bootstrap Flux and reconcile a HelmRelease
- Define a simple Crossplane Composition and claim a database
- Complete Killercoda ArgoCD and Flux labs
Real-World Project 12.4
Single ArgoCD Application for one microservice
Multi-environment deployment with ApplicationSets and sync waves
Self-service IDP: Backstage + Crossplane + ArgoCD + team self-service namespaces
Troubleshooting 12.5
ArgoCD stuck in OutOfSync / Unknown
Inspect events and resource health. Use server-side apply. Check for webhook or CRD upgrade issues.
Flux reconciliation failures
Check GitRepository status, image policy, and secret access for private repos.
Crossplane claim stuck in Pending
Review Composition readiness, provider credentials, and XRD status conditions.
30-Day Roadmap 12.6
- Application CR
- Sync policies
- RBAC & projects
- GitRepository + Kustomize
- HelmRelease
- Image automation
- ApplicationSets
- Generators
- Progressive delivery
- Crossplane XRD/Composition
- Claims for self-service
- Backstage + templates
Deep Dive: Building Real Internal Developer Platforms 12.7
Platform Components
Backstage catalog + software templates. Crossplane for self-service claims. ArgoCD ApplicationSets for environments. Golden paths documented and enforced through templates.
Measuring Platform Success
Track cognitive load reduction, deployment frequency, MTTR, and developer satisfaction surveys. A good platform makes correct things easy and wrong things hard.
Real Incident: ArgoCD Self-Managed App Deleted Itself
What happened: The ArgoCD application CR that managed ArgoCD itself was stored in the cluster (App of Apps pattern). A developer ran kubectl delete application argocd-self -n argocd believing it was a test app. ArgoCD began deleting its own resources including the application controller.
# Prevention: use RBAC to restrict argocd namespace access $ kubectl create clusterrole argocd-readonly \ --verb=get,list,watch \ --resource=applications,appprojects \ -n argocd # App of Apps: manage ArgoCD app CRs in separate protected repo # Set finalizers to prevent accidental deletion $ kubectl patch application argocd-self -n argocd \ --type=merge \ -p '{"metadata":{"finalizers":["resources-finalizer.argocd.argoproj.io"]}}' Finalizer prevents kubectl delete from completing without --cascade=false
Recovery: Re-apply ArgoCD manifests from Git. Applications reconcile automatically once controller comes back. Self-healing GitOps means recovery is just kubectl apply -k away.
Enterprise GitOps: FluxCD, ESO & Multi-Cluster 12.8
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: payments-api
namespace: flux-system
spec:
interval: 5m0s # Reconcile every 5 minutes
path: ./kubernetes/apps/payments-api/overlays/prod
prune: true # Delete resources removed from Git
sourceRef:
kind: GitRepository
name: fleet-infra
healthChecks: # Wait for resources to be healthy
- apiVersion: apps/v1
kind: Deployment
name: payments-api
namespace: production
timeout: 5m0s
retryInterval: 2m0s
# Dependencies: ensure namespace exists before app
dependsOn:
- name: namespaces
postBuild:
substitute:
cluster_name: prod-eks-us-east-1
environment: production
substituteFrom:
- kind: ConfigMap
name: cluster-vars# FluxCD Image Automation: auto-update image tags in Git
# New image pushed to ECR -> Flux detects -> updates values.yaml -> commits -> reconciles
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageRepository
metadata:
name: payments-api
namespace: flux-system
spec:
image: 123456789.dkr.ecr.us-east-1.amazonaws.com/payments-api
interval: 1m
secretRef:
name: ecr-credentials
---
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
name: payments-api
namespace: flux-system
spec:
imageRepositoryRef:
name: payments-api
policy:
semver:
range: '>=1.0.0' # Only stable releases in prod
---
apiVersion: image.toolkit.fluxcd.io/v1beta1
kind: ImageUpdateAutomation
metadata:
name: flux-system
namespace: flux-system
spec:
interval: 30m
sourceRef:
kind: GitRepository
name: fleet-infra
git:
checkout:
ref:
branch: main
commit:
author:
email: fluxbot@acme.com
name: Flux Bot
messageTemplate: |
chore(image): update {{range .Updated.Images}}{{.}}{{end}}
push:
branch: main
update:
path: ./clusters/prod
strategy: Setters # Uses # {"$imagepolicy": "flux-system:payments-api"} markersapiVersion: external-secrets.io/v1beta1
kind: ClusterSecretStore
metadata:
name: aws-secrets-manager
spec:
provider:
aws:
service: SecretsManager
region: us-east-1
auth:
jwt:
serviceAccountRef:
name: external-secrets
namespace: external-secrets
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: payments-db-credentials
namespace: production
spec:
refreshInterval: 1h
secretStoreRef:
name: aws-secrets-manager
kind: ClusterSecretStore
target:
name: payments-db-creds # K8s Secret created here
creationPolicy: Owner
template:
type: Opaque
data:
DB_HOST: "{{ .host }}"
DB_PASSWORD: "{{ .password }}"
DB_USER: "{{ .username }}"
data:
- secretKey: host
remoteRef:
key: prod/payments/database
property: host
- secretKey: password
remoteRef:
key: prod/payments/database
property: passwordapiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: payments-api-all-clusters
namespace: argocd
spec:
generators:
# Cluster generator: creates one App per registered cluster
- clusters:
selector:
matchLabels:
env: production
values:
revision: main
template:
metadata:
name: 'payments-api-{{name}}'
spec:
project: default
source:
repoURL: https://github.com/acme-corp/fleet-infra
targetRevision: '{{values.revision}}'
path: 'apps/payments-api/overlays/{{metadata.labels.region}}'
destination:
server: '{{server}}'
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
- ServerSideApply=true- Bootstrap FluxCD with flux CLI, create GitRepository and Kustomization for a sample app
- Configure FluxCD Image Automation — push a new image tag, watch Flux auto-commit to Git
- Install External Secrets Operator, create ExternalSecret that syncs from AWS Secrets Manager
- Create ArgoCD ApplicationSet with cluster generator — deploy to 2 kind clusters simultaneously
- Add finalizer to ArgoCD app, verify kubectl delete is blocked without --cascade=false flag
Alerting on Drift: argocd_app_info and an OutOfSync Rule 12.9
Self-heal fixes drift silently, and without self-heal drift stays until someone looks at the UI. Either way, someone should know. The Argo CD application controller exports argocd_app_info, one series per Application with sync_status and health_status labels, on the argocd-metrics service (port 8082). Alert on it.
Recorded from a real run of scripts/recordings/gitops-alert.sh; every output below is pasted from scripts/recordings/gitops-alert.out. Cover the output, predict it, then compare.
Environment: minikube v1.34.0 (Kubernetes v1.31.0), Argo CD v2.13.3, and a minimal prom/prometheus:v2.55.1 in the monitoring namespace. The guestbook Application (argoproj/argocd-example-apps, kustomize-guestbook) has automated sync but no selfHeal, so a hand edit stays as drift.
groups:
- name: argocd
rules:
- alert: ArgoCDAppOutOfSync
# argocd_app_info is exported by the application controller (argocd-metrics:8082), one series per app.
expr: argocd_app_info{sync_status="OutOfSync"} == 1
# 1m so the recording fires quickly; size this to how long drift may last before someone is paged.
for: 1m
labels:
severity: warning
annotations:
summary: "Argo CD app {{ $labels.name }} is OutOfSync with Git"global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/argocd-alert-rules.yaml
scrape_configs:
- job_name: argocd-application-controller
static_configs:
- targets: ["argocd-metrics.argocd.svc:8082"]# What Prometheus sees for the app $ kubectl -n monitoring exec deploy/prometheus -- wget -qO- 'http://localhost:9090/api/v1/query?query=argocd_app_info' | jq -r '.data.result[].metric | "\(.name) sync=\(.sync_status) health=\(.health_status)"' guestbook sync=Synced health=Healthy # Alerts before any drift $ kubectl -n monitoring exec deploy/prometheus -- wget -qO- http://localhost:9090/api/v1/alerts | jq -r '.data.alerts | length' 0 # Someone scales the Deployment by hand $ kubectl scale deployment kustomize-guestbook-ui --replicas=3 # Sync status 40 seconds later $ kubectl -n argocd get application guestbook -o jsonpath='{.status.sync.status}'; echo OutOfSync # The alert right after $ kubectl -n monitoring exec deploy/prometheus -- wget -qO- http://localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | "\(.labels.alertname) \(.labels.name) \(.state)"' ArgoCDAppOutOfSync guestbook pending # About a minute later $ kubectl -n monitoring exec deploy/prometheus -- wget -qO- http://localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | "\(.labels.alertname) \(.labels.name) \(.state)"' ArgoCDAppOutOfSync guestbook firing # What the page says $ kubectl -n monitoring exec deploy/prometheus -- wget -qO- http://localhost:9090/api/v1/alerts | jq -r '.data.alerts[0].annotations.summary' Argo CD app guestbook is OutOfSync with Git
An alert goes pending while its expression is true for less than for, then firing. The 1m here keeps the run short. Choose it from how long drift may last before someone must act, and route it to the team that owns the Application. Pair it with argocd_app_info{health_status="Degraded"} for apps that sync but do not become healthy. With the Prometheus Operator the same rule group goes in a PrometheusRule; Argo CD Notifications can also message a channel on on-sync-status-unknown or on-sync-failed triggers.
Argo CD Notifications: Declarative Subscriptions, Templates & Secret References
Prometheus metric alerts require external alertmanager infrastructure. For direct ChatOps and webhook dispatch, Argo CD Notifications runs as a dedicated controller watching Application CR lifecycle changes. According to Argo CD Notifications Documentation and Notifications Services Guide (Argo CD v2.10+):
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-notifications-cm
namespace: argocd
data:
# Decoupled secret reference: token value pulled from argocd-notifications-secret
service.slack: |
token: $slack-token
template.app-sync-failed: |
message: |
Application {{.app.metadata.name}} sync failed: {{.app.status.operationState.message}}
slack:
attachments: |
[{
"title": "{{.app.metadata.name}}",
"title_link": "{{.context.argocdUrl}}/applications/{{.app.metadata.name}}",
"color": "#e53e3e",
"fields": [
{ "title": "Sync Status", "value": "{{.app.status.sync.status}}", "short": true },
{ "title": "Repository", "value": "{{.app.spec.source.repoURL}}", "short": true }
]
}]
trigger.on-sync-failed: |
- description: Application sync execution failed or encountered errors
send: [app-sync-failed]
when: app.status.operationState != nil and app.status.operationState.phase in ['Error', 'Failed']
---
apiVersion: v1
kind: Secret
metadata:
name: argocd-notifications-secret
namespace: argocd
type: Opaque
stringData:
# Secret reference mapped into $slack-token in argocd-notifications-cm
slack-token: xoxb-synthetic-test-token-reference
---
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: guestbook
namespace: argocd
annotations:
# Declarative subscription: subscribe Slack channel to on-sync-failed trigger
notifications.argoproj.io/subscribe.on-sync-failed.slack: devops-alerts
spec:
project: default
source:
repoURL: https://github.com/argoproj/argocd-example-apps
targetRevision: HEAD
path: kustomize-guestbook
destination:
server: https://kubernetes.default.svc
namespace: defaultVerification & Troubleshooting Commands:
# 1. Verify notifications secret is properly mounted and unmasked
kubectl -n argocd get secret argocd-notifications-secret -o jsonpath='{.data.slack-token}' | base64 -d; echo
# 2. Confirm application has the subscription annotation attached
kubectl -n argocd get application guestbook -o jsonpath='{.metadata.annotations}' | jq .
# 3. Stream notifications controller logs to troubleshoot failed deliveries or webhook 401/403 errors
kubectl -n argocd logs -l app.kubernetes.io/name=argocd-notifications-controller --tail=100 -f
Troubleshooting Checklist: If alerts fail to dispatch, check: (1) Secret reference syntax $slack-token matches key in argocd-notifications-secret; (2) The when expression condition correctly catches app.status.operationState.phase; (3) Controller service account has read RBAC permissions across watched application namespaces.
Flux Image Automation via Protected Branch & Reviewed Pull Request Path
Pushing automated image tag updates directly to the default branch bypasses branch protection rules, code reviews, and pre-deployment automated checks. A resilient enterprise GitOps workflow qualifies image updates by committing to a dedicated bot branch and opening a pull request. According to Flux Image Update Automation Guide and Flux Git Updates Guide (Flux v2.3+):
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageUpdateAutomation
metadata:
name: payments-api-automation
namespace: flux-system
spec:
interval: 15m
sourceRef:
kind: GitRepository
name: fleet-infra
git:
checkout:
ref:
branch: main # Base automated commits on reviewed main branch
commit:
author:
email: fluxbot@acme.corp
name: Flux Bot
messageTemplate: |
chore(release): bump payments-api to {{range .Updated.Images}}{{.}}{{end}}
push:
branch: bot/image-updates # Push restricted to staging branch
update:
path: ./clusters/prod
strategy: SettersGit Automation Permissions & Branch Protection Rules:
- Least-Privilege Automation Credentials: The Git deploy key or fine-grained GitHub App token used by Flux must be scoped exclusively to
contents: write(restricted to branch filterrefs/heads/bot/*) andpull-requests: write. It must be explicitly denied direct write access tomainorrelease/*branches. - Branch Protection Policy: The target
mainbranch enforces required pull request reviews (at least 1 peer approval), dismissal of stale approvals on new commits, mandatory linear Git history, and passing status checks (container image vulnerability scans, unit tests, and policy evaluations). - PR Automation Workflow: An accompanying CI workflow (e.g. GitHub Actions) detects pushes to
bot/image-updatesand generates a pull request with changelog context:gh pr create --base main --head bot/image-updates --title "chore: automated payments-api image bump" --body "Triggered by Flux ImageUpdateAutomation. Pending automated CI and peer review."
Minimal Crossplane Composition, XRD & Claim (Zero Cloud Provisioning)
Crossplane turns Kubernetes into a universal control plane, letting platform teams compose cloud infrastructure into self-service custom resources called Claims. According to Crossplane Composition Concepts and Crossplane XRD Reference (Crossplane v1.16+, Provider-AWS Upbound v1.4+):
# 1. CompositeResourceDefinition (XRD): defines custom API contract
apiVersion: apiextensions.crossplane.io/v1
kind: CompositeResourceDefinition
metadata:
name: xpostgresqlinstances.database.example.org
spec:
group: database.example.org
names:
kind: XPostgreSQLInstance
plural: xpostgresqlinstances
claimNames:
kind: PostgreSQLInstance
plural: postgresqlinstances
versions:
- name: v1alpha1
served: true
referenceable: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: [storageGB]
properties:
storageGB:
type: integer
description: Allocated database disk capacity in GB
---
# 2. Composition: maps abstract Claim to concrete Managed Resources
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
name: postgresql-aws-standard
labels:
provider: aws
db: postgresql
spec:
compositeTypeRef:
apiVersion: database.example.org/v1alpha1
kind: XPostgreSQLInstance
resources:
- name: rds-instance
base:
apiVersion: rds.aws.upbound.io/v1beta1
kind: Instance
spec:
forProvider:
region: "us-east-1"
engine: postgres
engineVersion: "16.2"
instanceClass: db.t4g.micro
allocatedStorage: 20
skipFinalSnapshot: true
deletionPolicy: Delete
patches:
- type: FromCompositeFieldPath
fromFieldPath: spec.storageGB
toFieldPath: spec.forProvider.allocatedStorage
---
# 3. Developer Claim: self-service request consumed by application teams
apiVersion: database.example.org/v1alpha1
kind: PostgreSQLInstance
metadata:
name: dev-database-claim
namespace: team-payments
spec:
storageGB: 50Validation, Lifecycle & Cleanup Runbook: (Simulated offline architecture; no live cloud credentials or paid cloud resources are provisioned; simulated results are labeled and live-run limitations remain in curriculum gaps).
# 1. Offline schema validation using Crossplane CLI
crossplane beta validate --schema=xrd-schema.yaml crossplane-database-composition.yaml
# 2. Dry-run client verification against cluster API
kubectl apply --dry-run=client -f crossplane-database-composition.yaml
# 3. Inspect composite readiness and condition events
kubectl get postgresqlinstances.database.example.org -n team-payments
kubectl describe xpostgresqlinstance -l crossplane.io/claim-name=dev-database-claim
# 4. Deterministic cleanup: deleting Claim cascades deletion to managed cloud resources
# deletionPolicy: Delete ensures cloud provider resources are deleted rather than orphaned
kubectl delete postgresqlinstance dev-database-claim -n team-payments// Deterministic Crossplane Composition & Claim Validator
export function validateCrossplaneClaim(claim, composition) {
if (!claim || !claim.spec || typeof claim.spec.storageGB !== 'number' || claim.spec.storageGB < 10) {
return { valid: false, error: 'StorageGB must be a positive number >= 10 GB' };
}
const baseResource = composition?.spec?.resources?.[0]?.base;
if (!baseResource || baseResource.spec?.deletionPolicy !== 'Delete') {
return { valid: false, error: 'Composition must enforce deletionPolicy: Delete to prevent orphaned resources' };
}
const patchedStorage = claim.spec.storageGB;
return {
valid: true,
allocatedStorage: patchedStorage,
engine: baseResource.spec.forProvider.engine,
instanceClass: baseResource.spec.forProvider.instanceClass,
deletionPolicy: baseResource.spec.deletionPolicy
};
}
// Deterministic Argo CD Notifications Trigger Evaluator
export function evaluateNotificationTrigger(appState) {
if (!appState || !appState.operationState) return { sendNotification: false, reason: 'No active operationState' };
const phase = appState.operationState.phase;
if (['Error', 'Failed'].includes(phase)) {
return { sendNotification: true, template: 'app-sync-failed', phase };
}
return { sendNotification: false, phase };
}