Columns › 6. Deploying the system › Part 31
GitOps with Argo CD: Let the Cluster Follow git on Its Own
用 Argo CD 做 GitOps:讓叢集自己跟著 git 走
Start from the four principles of GitOps, move the shop’s Kubernetes setup into its own config repository, install Argo CD, limit its reach with an AppProject, manage dev and prod with Applications and an ApplicationSet, turn migrations into a sync hook ordered by sync waves, switch secrets to External Secrets, leave CI only the image tag, then rollback, permissions and common pitfalls.
In this article
- What this article solves
- Step 1: What GitOps is: from push to pull
- Step 2: A config repository: deployment configuration apart from code
- Step 3: Install Argo CD, log in, add the repository
- Step 4: AppProject: limiting what Argo CD may do
- Step 5: An Application: deploying production
- Step 6: An ApplicationSet: dev and prod at once
- Step 7: Migrations as a sync hook, ordered with sync waves
- Step 8: Keeping secrets out of git
- Step 9: CI only builds and changes tags
- Step 10: Rollback, notifications and incidents
- Step 11: Permissions and security for Argo CD itself
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “A Kubernetes Configuration Reference: What to Write in Each Field, and Why”, made every service’s configuration complete and validated it in CI. But it’s still applied the way “Deploying a Microservice System on Kubernetes” did it: CI runs kubectl apply with cluster credentials. This article reverses the direction with GitOps and Argo CD: git is the single source of truth, and Argo CD inside the cluster pulls, compares and applies on its own.
What this article solves
Pushing deployments from CI runs into a few problems over time:
- CI holds cluster admin rights. The CI system, its plugins and anyone who can edit a pipeline can all touch production. Compromise CI and you’ve compromised the cluster.
- The cluster slowly drifts from git. Someone fixes an incident at night with
kubectl edit, changing replicas or an environment variable, and nobody writes it back to git; the next deploy overwrites it, or worse, doesn’t, and nobody knows what’s running. - “What version is in production?” is hard to answer. You dig through CI logs instead of looking in one place.
- Rollbacks rely on memory. The previous tag and configuration have to be pieced back together from scripts and logs.
This article works through:
- The four principles of GitOps, and push versus pull.
- Moving the Kubernetes configuration into its own config repository.
- Installing Argo CD, logging in, adding the config repository.
- Limiting what Argo CD may deploy, and where, with an AppProject.
- Deploying production with an Application: automated sync, self-heal and prune.
- Managing dev and prod at once with an ApplicationSet.
- Turning database migrations into a sync hook, ordered with sync waves.
- Keeping secrets out of git: External Secrets Operator or Sealed Secrets.
- Leaving CI only to build images and change tags.
- Rollback, notifications and incidents.
- Permissions and security for Argo CD itself.
Step 1: What GitOps is: from push to pull
GitOps comes down to four principles:
- Declarative: the desired state of the system is described as configuration (Kubernetes YAML already is), not as a sequence of commands.
- Versioned and immutable: that description lives in git; every change has a commit, an author, a review and history.
- Pulled automatically: an agent inside the cluster fetches the latest description from git, instead of an outside system pushing it in.
- Continuously reconciled: the agent keeps comparing what git wants with what the cluster has, and corrects any difference.
Figure: on top, push: CI holds cluster credentials and applies directly. Below, GitOps: CI only changes the config repository, and Argo CD inside the cluster pulls and keeps comparing.
The biggest difference is the direction of access: with push, an outside CI has to get into the cluster; with GitOps, Argo CD inside the cluster reads git outward, and CI needs no cluster access at all. The second is continuous reconciliation: change the cluster by hand, and Argo CD notices it no longer matches git and, depending on settings, warns or puts it back.
Step 2: A config repository: deployment configuration apart from code
So far in the series, the Kubernetes configuration lived in deploy/k8s/ in the code repository shop. With GitOps it’s common to move it into its own config repository, say shop-deploy:
shop-deploy/
├── apps/
│ ├── base/ # formerly deploy/k8s/base (four services, routes, NetworkPolicy)
│ └── overlays/
│ ├── dev/ # namespace: shop-dev
│ └── prod/ # namespace: shop, image tags, resources
└── argocd/
├── project.yaml # AppProject: what shop may deploy
└── applicationset.yaml # the dev and prod ApplicationsWhy separate them:
- Different permissions. Many people change code; few should change production configuration. The config repository can have its own review rules (say, two approvals for the prod directory).
- Clean history. Every commit in the config repository is a deployment change;
git log apps/overlays/prodis production’s change log. - No loops. When CI changes an image tag it has to commit somewhere; committing back to the code repository would trigger CI again.
Use directories for environments, not branches. dev and prod are two directories on one branch, so the differences are plain to see; with a branch per environment, merge directions and differences soon get tangled.
For a small team or a single service, staying in one repository works too, as long as CI’s commits carry something like [skip ci] to avoid the loop.
Step 3: Install Argo CD, log in, add the repository
Argo CD is itself a set of services running in the cluster. Install it as the official documentation describes, and pin a version rather than applying stable, so upgrades have a clear version difference to read:
kubectl create namespace argocd
# replace vX.Y.Z with the version you want; the manifest is large, so apply server-side
kubectl apply -n argocd --server-side \
-f https://raw.githubusercontent.com/argoproj/argo-cd/vX.Y.Z/manifests/install.yaml
# get the initial admin password, connect through a port-forward
argocd admin initial-password -n argocd
kubectl -n argocd port-forward svc/argocd-server 8080:443
argocd login localhost:8080
argocd account update-password
# once changed, the initial password's Secret can go
kubectl -n argocd delete secret argocd-initial-admin-secretThen let Argo CD read the config repository. Give it a read-only deploy key that can read only shop-deploy:
argocd repo add git@github.com:example/shop-deploy.git \
--ssh-private-key-path ~/.ssh/shop-deploy-readonlyIn real use, Argo CD’s interface should sign in through the company’s single sign-on (SSO), with the local admin account disabled once that works (step 11).
Step 4: AppProject: limiting what Argo CD may do
Argo CD comes with a default project that allows everything. Give the shop its own project and spell out where things come from, where they may go, and which cluster-level resources may be created:
# shop-deploy/argocd/project.yaml
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
name: shop
namespace: argocd
spec:
description: the shop's dev and prod
sourceRepos:
- git@github.com:example/shop-deploy.git
destinations:
- server: https://kubernetes.default.svc
namespace: shop
- server: https://kubernetes.default.svc
namespace: shop-dev
# the only cluster-level resource allowed is the Namespace (the overlays include namespace.yaml)
clusterResourceWhitelist:
- group: ''
kind: Namespace
# namespace level: permission objects aren't created by Argo CD; platform admins review them
namespaceResourceBlacklist:
- group: rbac.authorization.k8s.io
kind: RoleBindingNow even if someone adds a ClusterRoleBinding to the config repository, or points an Application at kube-system, Argo CD refuses to sync. Permission objects like RoleBindings are blacklisted and left for platform admins to review and apply; open them explicitly if your services really need them.
Step 5: An Application: deploying production
An Application says “deploy this directory of this repository to this namespace of this cluster”. When Argo CD finds a kustomization.yaml in the directory, it renders it with Kustomize automatically:
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: shop-prod
namespace: argocd
# deleting this Application also deletes the resources it created
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: shop
source:
repoURL: git@github.com:example/shop-deploy.git
targetRevision: main
path: apps/overlays/prod
destination:
server: https://kubernetes.default.svc
namespace: shop
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- PruneLast=true
- ServerSideApply=true
retry:
limit: 5
backoff:
duration: 10s
factor: 2
maxDuration: 3mWhat the settings mean:
automated: when git changes, Argo CD syncs; nobody presses a button. Production is guarded by review in the config repository (a PR must be approved to merge), not at the sync step.selfHeal: true: if someone changes the cluster by hand, Argo CD puts it back as git says. To change configuration during an incident, change git; if you really must act by hand for a while, turn off automated sync for this Application first, and remember to turn it back on.prune: true: resources deleted from git are deleted from the cluster. Without it, a removed Service or CronJob lingers in the cluster forever.PruneLast=true: prune only after everything else has synced and is healthy, so the old isn’t removed before the new is ready.ServerSideApply=true: apply server-side, so large resources (such as CRDs) and fields managed by several controllers conflict less.retry: retry transient failures (say, a webhook not ready yet) automatically.
Keep replica counts out of git. The previous articles’ Deployments deliberately leave out replicas and let HPA decide; if it were written, Argo CD would see every HPA adjustment as “out of sync” and change it back, and the two would fight.
Step 6: An ApplicationSet: dev and prod at once
dev and prod differ only in directory and namespace, so an ApplicationSet generates both Applications from one template:
# shop-deploy/argocd/applicationset.yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: shop
namespace: argocd
spec:
goTemplate: true
goTemplateOptions: ['missingkey=error']
generators:
- list:
elements:
- env: dev
namespace: shop-dev
- env: prod
namespace: shop
template:
metadata:
name: 'shop-{{.env}}'
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: shop
source:
repoURL: git@github.com:example/shop-deploy.git
targetRevision: main
path: 'apps/overlays/{{.env}}'
destination:
server: https://kubernetes.default.svc
namespace: '{{.namespace}}'
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- PruneLast=true
- ServerSideApply=trueAdding a staging environment later means one more overlay directory and one more line in the list. These two files (project.yaml, applicationset.yaml) can themselves be managed by Argo CD (the “app of apps” pattern), but the first time an admin applies them by hand with kubectl apply -n argocd -f argocd/.
Step 7: Migrations as a sync hook, ordered with sync waves
The release script in “Deploying a Microservice System on Kubernetes” had to delete the old Job, apply only configuration and migrations, wait for them, then apply everything, because “a Job’s template can’t be changed” and “migrations must finish before the new version goes live”. Argo CD says the same with annotations.
Sync waves set the order. Within one sync, Argo CD applies resources by their argocd.argoproj.io/sync-wave number, smallest first, default 0; it moves to the next wave only when every resource in the previous one is healthy. A Job is healthy when it has completed, so putting migrations before the services makes the services wait for a successful migration before they update. The shop uses three waves:
| Wave | Resources | Why |
|---|---|---|
| -2 | ConfigMaps, ExternalSecrets (step 8) | Both migrations and services read them |
| -1 | The migration Job | The schema must change before the new version goes live |
| 0 (default) | Deployments, Services, HPAs and so on | Roll out only after migrations succeed |
Figure: configuration first, services roll out only after the migration completes; if it fails, the sync stops at wave -1 and the old version keeps serving.
The migration Job gets the hook annotations:
# apps/base/order/migrate-job.yaml (metadata only)
apiVersion: batch/v1
kind: Job
metadata:
name: order-migrate
annotations:
argocd.argoproj.io/hook: Sync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
argocd.argoproj.io/sync-wave: '-1'hook: Sync: runs once on every sync, ordered by wave together with ordinary resources; if it fails, the sync stops and wave 0’s new version doesn’t go live.hook-delete-policy: BeforeHookCreation: delete the previous Job before creating the new one. That solves the unchangeable Job template.
Why not PreSync? PreSync runs before all ordinary resources, including the ConfigMaps the migration reads; on the first deploy, or whenever a ConfigMap’s content (and so its hashed name) changes, the Job can’t find it. Placing it in the same Sync phase, one wave after the configuration, gets the order right.
For ConfigMaps produced by configMapGenerator, add the annotation with Kustomize’s generatorOptions:
# apps/base/order/kustomization.yaml (added to what's there)
generatorOptions:
annotations:
argocd.argoproj.io/sync-wave: '-2'Schema changes must still be backward compatible (add the column, change the code, drop the old column later): old and new versions run side by side during a rolling update, and Argo CD doesn’t change that.
Step 8: Keeping secrets out of git
The dev environment in “Deploying a Microservice System on Kubernetes” used a secretGenerator reading local secrets/*.txt files kept out of version control. With Argo CD, which sees only what’s in git, the local files don’t exist and Kustomize fails outright. Secrets have to take a form that can live in git without revealing anything. Two common approaches:
External Secrets Operator (recommended). Secrets live in an external secret manager (a cloud Secret Manager, HashiCorp Vault and so on); git holds only a description of where to fetch them, and an operator in the cluster fetches them periodically and creates the Kubernetes Secret:
# apps/overlays/prod/order-secrets.yaml
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: order-secrets
spec:
refreshInterval: 1h
secretStoreRef:
kind: ClusterSecretStore
name: prod-secrets
target:
name: order-secrets
data:
- secretKey: db-password
remoteRef:
key: shop/prod/order
property: db_passwordThe resulting Secret has the same name and key as before (order-secrets, db-password), so the Deployment doesn’t change at all. To rotate a password, change it in the secret manager and the operator picks it up on the next refresh.
Sealed Secrets. A controller’s public key in the cluster encrypts a Secret into a SealedSecret; the encrypted file can be committed to git safely, and only that cluster can decrypt it. No external service is needed, which suits small teams; the cost is re-encrypting on rotation or when moving clusters, and managing the key’s backup separately.
Either way the rule is the same: no plaintext secret ever appears in git, base64 Secret YAML included. Add secret scanning (gitleaks, for example) to the config repository to block it at PR time.
Step 9: CI only builds and changes tags
CI’s job shrinks to two things: build and push images, and change the tag to the new SHA in the config repository. It needs no cluster access, only write access to the config repository (or permission to open PRs):
#!/usr/bin/env bash
# CI: runs after code is merged to main
set -euo pipefail
SHA="$(git rev-parse --short=12 HEAD)"
REG="registry.example.com/shop"
SERVICES=(api-gateway order payment inventory)
# 1. build and push the images (as before)
for svc in "${SERVICES[@]}"; do
docker buildx build --build-arg SERVICE="$svc" \
-f deploy/docker/Dockerfile -t "$REG/$svc:$SHA" --push .
done
# 2. change the dev tags in the config repository and push; prod goes through a PR
git clone --depth 1 git@github.com:example/shop-deploy.git /tmp/shop-deploy
cd /tmp/shop-deploy/apps/overlays/dev
for svc in "${SERVICES[@]}"; do
kustomize edit set image "$REG/$svc=$REG/$svc:$SHA"
done
git commit -am "dev: shop $SHA"
git push origin maindev is pushed directly and Argo CD deploys it; prod uses the same commands on apps/overlays/prod, but pushes to a branch and opens a PR, deploying only once it’s approved and merged. That way “who put which version into production, and when” is in the PRs and commits.
If you’d rather CI didn’t write to the config repository, Argo CD Image Updater can watch the registry for new tags and write the change back to git itself. Same idea; the one changing tags moves from CI to another component in the cluster.
Step 10: Rollback, notifications and incidents
Roll back with git revert first. When production breaks, revert the offending commit (usually the one that changed the tag) and Argo CD syncs the cluster back to the previous version. git stays the truth, and later you can see when and why it was rolled back.
Argo CD has its own rollback: argocd app history shop-prod lists the syncs, and argocd app rollback shop-prod <ID> returns to one. But it requires turning off automated sync first, and afterwards the cluster no longer matches git: remember to make the matching change in git and turn automated sync back on, or the next sync goes straight back to the broken version.
Look at Argo CD first during an incident. argocd app get shop-prod shows each resource’s sync status (Synced/OutOfSync) and health (Healthy/Progressing/Degraded), and argocd app diff shop-prod shows where the cluster differs from git. A Degraded resource leads to the Kubernetes events and Pod status; from there, debug as in step 9 of “Deploying a Microservice System on Kubernetes”.
Notifications. Use Argo CD Notifications to send “sync failed” and “health became Degraded” to the team’s chat channel.
Progressive delivery. Argo CD applies git’s state to the cluster; canary releases and automatic aborts based on metrics are Argo Rollouts’ job, and the two work together. “Automating Deployments and Troubleshooting with AI Workflows” has an Argo Rollouts setup.
Step 11: Permissions and security for Argo CD itself
Argo CD can change the whole cluster, so it’s a prime thing to protect:
- Sign-in: connect SSO and disable the local admin (
admin.enabled: "false"inargocd-cm). - Permissions: in
argocd-rbac-cm, decide who may view, who may sync and who may change settings. Default to read-only:
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-rbac-cm
namespace: argocd
data:
policy.default: role:readonly
policy.csv: |
p, role:shop-dev, applications, get, shop/*, allow
p, role:shop-dev, applications, sync, shop/shop-dev, allow
p, role:shop-ops, applications, *, shop/*, allow
g, shop-developers, role:shop-dev
g, shop-sre, role:shop-opsDevelopers can see all of shop’s Applications but may only sync dev by hand; only the operations team has full rights over prod.
- Repository keys are read-only, granted only for the repositories needed.
- The AppProject limits the reach (step 4): sources, destinations and cluster-level resources all listed explicitly.
- Upgrading Argo CD itself is an ordinary change: pin the version, read the release notes, try it on a dev cluster first.
Common pitfalls
prune on while moving resources to another Application. The old Application thinks they were deleted and removes them. When moving, turn off prune on the old Application first, or annotate the resources so Argo CD won’t delete them.
Fixing an incident with kubectl edit, then watching it revert. That’s exactly what selfHeal is for. Put the fix in git, or pause automated sync first and write it back afterwards.
replicas in the Deployment. It fights HPA, and the Application shows OutOfSync forever.
Using the latest tag. git doesn’t change, so Argo CD never learns of the new image; and there’s nothing to roll back to.
Bringing a local-file secretGenerator into Argo CD. The files aren’t in git and rendering fails; switch to External Secrets or Sealed Secrets.
A plaintext or base64 Secret committed to git. git history doesn’t forget; treat it as leaked the moment it’s committed and rotate it.
Migrations as a PreSync hook. It runs before every resource, so on the first deploy the ConfigMap it reads doesn’t exist yet; use a Sync hook with a sync wave.
Rolling back in Argo CD and forgetting git. The next sync goes straight back to the broken version.
Everything in the default project. Any Application can deploy to any namespace; create your own AppProject.
Key takeaways
- GitOps: declarative, kept in git, pulled automatically by an agent in the cluster, continuously reconciled; the big change is that CI no longer needs cluster access, and drift between cluster and git gets noticed.
- Configuration lives in its own config repository, with directories per environment; prod is guarded by PR review.
- Install Argo CD with a pinned version, delete the initial password once used, give it read-only repository keys.
- An AppProject limits sources, destinations and cluster-level resources; don’t use the
defaultproject. - Applications use automated sync,
selfHeal,prune(withPruneLast) and retries; replica counts belong to HPA, not git. - An ApplicationSet generates dev and prod from one template; a new environment is one directory and one line.
- Order with sync waves: configuration and secrets (-2), then the migration Job (-1, a
Synchook withBeforeHookCreation), then services (0); notPreSync, which runs before configuration exists; schema changes stay backward compatible. - Secrets come through External Secrets Operator or Sealed Secrets; git never holds a plaintext secret.
- CI only builds images and changes tags (dev pushed, prod via PR); roll back with git revert first.
- Argo CD itself uses SSO, has admin disabled, splits rights with RBAC, and is upgraded as an ordinary change.
References
- What is OpenGitOps? (OpenGitOps): the four principles (declarative, versioned, pulled, reconciled) described in step 1.
- Projects (official Argo CD documentation): the permissive
defaultproject and restricting sources, destinations and cluster resources, used in step 4. - Automated Sync Policy (official Argo CD documentation):
prune,selfHeal, and why rollback is blocked while auto-sync is on, used in steps 5 and 10. - Sync Options (official Argo CD documentation): sync options such as
PruneLastandServerSideApply, used in the Application in step 5. - Sync Phases and Waves (official Argo CD documentation): hook types, wave ordering and
BeforeHookCreation, used for the migration in step 7. - Generating Applications with ApplicationSet (official Argo CD documentation): generating several Applications from one template, used for dev and prod in step 6.
- RBAC Configuration (official Argo CD documentation): the built-in
role:readonlyand custom roles, used for access control in step 11. - External Secrets Operator (official External Secrets Operator documentation): ExternalSecret and SecretStore syncing secrets from an external store, used in step 8.
Next
The whole system now deploys declaratively, heals itself, and goes live and rolls back through PRs. But swapping in a new version all at once is still risky. The next article, “Blue-Green and Canary Releases: Doing Them Right and What to Watch For”, shows how to send a small share of traffic to the new version first, judge it automatically by metrics, and roll back on failure.