Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

CAPA Cheatsheet

Weights: Workflows 36%, CD 34%, Rollouts 18%, Events 12%.

Argo CD

Architecture

  • API Server - gRPC/REST, UI, auth, RBAC, webhooks
  • Repo Server - clones Git, renders manifests (plain YAML, Helm, Kustomize, Jsonnet, plugins), caches
  • Application Controller - compares live vs desired, syncs, default reconcile every 3m (timeout.reconciliation: 180s in argocd-cm)
  • ApplicationSet Controller - generates Applications
  • Redis - cache only, rebuilt on start
  • Dex (optional) - SSO connector for OIDC/SAML/LDAP/GitHub
  • Webhooks from GitHub/GitLab/Bitbucket trigger an immediate refresh
  • GitOps: declarative, versioned, automated, continuously reconciled

ConfigMaps / Secrets

  • argocd-cm - main config (URL, SSO/Dex, accounts.<name>, resource customizations, timeouts)
  • argocd-rbac-cm - RBAC policy
  • argocd-cmd-params-cm - component flags
  • argocd-initial-admin-secret - initial admin password
  • Repos: Secret label argocd.argoproj.io/secret-type: repository
  • Repo creds template: repo-creds; clusters: cluster

Install and access

kubectl create ns argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
kubectl port-forward svc/argocd-server -n argocd 8080:443
argocd admin initial-password -n argocd
argocd login localhost:8080
  • install.yaml non-HA, ha/install.yaml HA (needs 3+ nodes), also Helm and Operator

Application

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: myapp
  namespace: argocd
  finalizers:
  - resources-finalizer.argocd.argoproj.io
spec:
  project: default
  source:
    repoURL: https://github.com/example/repo.git
    targetRevision: main
    path: kubernetes/production
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
      allowEmpty: false
    syncOptions:
    - CreateNamespace=true
    retry:
      limit: 5
      backoff: {duration: 5s, factor: 2, maxDuration: 3m}
  • Finalizer: deleting the Application also deletes its resources (cascade)
  • Destination: server or name; in-cluster is https://kubernetes.default.svc
  • Multiple sources, reference values from another repo:
    sources:
    - repoURL: https://github.com/example/app.git
      path: helm
      helm:
        valueFiles:
        - $values/values-prod.yaml
    - repoURL: https://github.com/example/config.git
      targetRevision: main
      ref: values
    
  • Kustomize overlay: point source.path at the overlay dir
  • Exclude files: source.directory.exclude

Status

  • Sync: Synced, OutOfSync, Unknown
  • Health: Healthy, Progressing, Degraded, Suspended, Missing, Unknown
  • Sync status and health are independent
  • ComparisonError when the repo can’t be read or manifests don’t render

Sync policy

  • Manual by default
  • automated.prune - delete resources removed from Git
  • automated.selfHeal - revert manual cluster changes
  • automated.allowEmpty - allow an empty source to delete everything (default false)
  • Drift is detected without self-heal, it just isn’t fixed
  • Disable auto-sync: argocd app set myapp --sync-policy none

Sync options

syncOptions:
- Validate=false                 # skip schema validation
- CreateNamespace=true
- PrunePropagationPolicy=foreground  # foreground (default), background, orphan
- PruneLast=true                 # prune after other resources are synced
- ApplyOutOfSyncOnly=true
- ServerSideApply=true           # good for CRDs / big resources
- Replace=true                   # kubectl replace instead of apply
- Force=true                     # kubectl apply --force, delete/recreate
- RespectIgnoreDifferences=true
- FailOnSharedResource=true
  • Per resource annotation argocd.argoproj.io/sync-options: Prune=false, Delete=false, Validate=false, Replace=true, SkipDryRunOnMissingResource=true

ignoreDifferences

ignoreDifferences:
- group: apps
  kind: Deployment
  jsonPointers:
  - /spec/replicas
- kind: ConfigMap
  jqPathExpressions:
  - '.data["config.yaml"]'
- group: "*"
  kind: "*"
  managedFieldsManagers:
  - kube-controller-manager
  • Add RespectIgnoreDifferences=true or the fields are still overwritten on sync
  • System-wide: resource.customizations.ignoreDifferences.<group_kind> in argocd-cm

Waves and hooks

metadata:
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded
  • Waves: lower first, default 0, negatives allowed; next wave waits for the previous to be healthy
  • Hooks: PreSync (migrations), Sync, PostSync (tests), SyncFail (notify), Skip
  • Delete policies: HookSucceeded, HookFailed, BeforeHookCreation (default)
  • Order: phase, then wave, then kind, then name

AppProject

apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: production
  namespace: argocd
spec:
  sourceRepos:
  - 'https://github.com/myorg/*'
  destinations:
  - namespace: production
    server: https://kubernetes.default.svc
  clusterResourceWhitelist:
  - group: ''
    kind: Namespace
  namespaceResourceBlacklist:
  - group: ''
    kind: ResourceQuota
  roles:
  - name: deployer
    policies:
    - p, proj:production:deployer, applications, sync, production/*, allow
  syncWindows:
  - kind: allow
    schedule: '0 9 * * 1-5'
    duration: 8h
    manualSync: true
  • Restricts repos, destinations, cluster-scoped kinds (clusterResourceWhitelist, default deny), namespaced kinds (namespaceResourceWhitelist/Blacklist)
  • default project allows everything
  • Sync windows: allow / deny

ApplicationSet

apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: apps
  namespace: argocd
spec:
  generators:
  - git:
      repoURL: https://github.com/example/apps.git
      revision: main
      directories:
      - path: apps/*
  template:
    metadata:
      name: '{{path.basename}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/example/apps.git
        targetRevision: main
        path: '{{path}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: '{{path.basename}}'
  • Generators: list, clusters (selector on cluster labels), git (directories/files), matrix, merge, scmProvider, pullRequest
  • Cluster generator vars: {{name}}, {{server}}
  • Matrix combines two generators (e.g. clusters x directories)

App of apps

  • Parent Application points at a directory of child Application manifests (in argocd namespace)
  • Use ApplicationSet for generated children, app of apps for hand-written ones

RBAC

  • argocd-rbac-cm, policy.csv:
    p, role:dev, applications, sync, myproj/*, allow
    g, my-group, role:dev
    
  • Format: p, subject, resource, action, object, effect
  • Resources: applications, clusters, repositories, projects, accounts, logs, exec
  • Actions: get, create, update, delete, sync, override, action/*
  • policy.default - role for authenticated users with no match; scopes - OIDC claims used for groups
  • Built-in roles: role:admin, role:readonly
  • Local users: accounts.alice: apiKey, login in argocd-cm; set password with argocd account update-password
  • Tokens: argocd account generate-token --account alice

Multi-cluster

argocd cluster add my-context      # creates ServiceAccount + RBAC in target
argocd cluster list
argocd cluster rm https://cluster-url
  • Stored as Secret with label argocd.argoproj.io/secret-type: cluster
  • Cluster labels drive ApplicationSet cluster generator
  • Hub and spoke: one Argo CD manages many clusters

CLI

argocd login argocd.example.com
argocd app create myapp --repo URL --path kubernetes/production \
  --dest-server https://kubernetes.default.svc --dest-namespace production
argocd app list
argocd app get myapp [--refresh|--hard-refresh]
argocd app diff myapp
argocd app sync myapp [--prune] [--dry-run] [--force] [--async]
argocd app sync myapp --resource apps:Deployment:myapp
argocd app wait myapp --health --timeout 120
argocd app history myapp
argocd app rollback myapp <ID>      # needs auto-sync off
argocd app manifests myapp
argocd app logs myapp
argocd app terminate-op myapp
argocd app delete myapp
argocd app set myapp --sync-policy automated --auto-prune --self-heal
argocd repo add URL --username u --password p
argocd repo add git@github.com:org/repo.git --ssh-private-key-path ~/.ssh/id_rsa
argocd repo list | argocd repo rm URL
argocd proj create p
argocd proj add-source p URL
argocd proj add-destination p https://kubernetes.default.svc ns

Argo Workflows

Basics

  • Workflow CRD; entrypoint picks the starting template
  • Workflow phases: Pending, Running, Succeeded, Failed, Error
  • Node phases also include Skipped, Omitted
  • Install: kubectl apply -n argo -f https://github.com/argoproj/argo-workflows/releases/download/<ver>/install.yaml
  • Executor pods need a ServiceAccount with workflowtaskresults create/patch (v3.4+)
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: hello-
spec:
  entrypoint: main
  serviceAccountName: argo-workflow
  activeDeadlineSeconds: 3600
  ttlStrategy:
    secondsAfterCompletion: 86400
  podGC:
    strategy: OnWorkflowCompletion
  arguments:
    parameters:
    - name: message
      value: hello
  templates:
  - name: main
    inputs:
      parameters:
      - name: message
    container:
      image: alpine
      command: [echo]
      args: ["{{inputs.parameters.message}}"]
  • activeDeadlineSeconds = max run time; ttlStrategy = cleanup; podGC = pod cleanup
  • onExit: handler runs an exit handler template always

Template types

  • container - one container
  • script - inline source, output in outputs.result
  • resource - action: create|apply|patch|delete, successCondition/failureCondition
  • steps - list of lists; outer sequential, inner parallel
  • dag - tasks with dependencies (or depends: "a.Succeeded || b")
  • suspend - pause until argo resume or duration
  • http, data, containerSet, plugin
- name: steps-example
  steps:
  - - name: a
      template: work
  - - name: b1       # b1 and b2 in parallel
      template: work
    - name: b2
      template: work
- name: dag-example
  dag:
    tasks:
    - name: A
      template: work
    - name: B
      dependencies: [A]
      template: work
    - name: C
      dependencies: [A]
      template: work
    - name: D
      dependencies: [B, C]
      template: work
  • DAG fails fast by default: after a task fails no new tasks start; failFast: false lets independent branches finish
  • Failed dependency skips dependents; continueOn: {failed: true} on a step/task goes on anyway

Variables

  • {{inputs.parameters.x}}, {{inputs.artifacts.x.path}}
  • {{workflow.name}}, {{workflow.namespace}}, {{workflow.parameters.x}}
  • {{steps.NAME.outputs.parameters.x}}, {{steps.NAME.outputs.result}}, {{steps.NAME.status}}
  • {{tasks.NAME.outputs.result}} in a DAG
  • {{item}} inside loops
  • {{=expr}} expression syntax

Loops and conditionals

- name: process
  template: work
  arguments:
    parameters:
    - name: item
      value: "{{item}}"
  withItems: [apple, banana]       # or withParam / withSequence
  when: "{{workflow.parameters.env}} == production"

Retry

retryStrategy:
  limit: "3"
  retryPolicy: OnFailure           # Always, OnFailure, OnError, OnTransientError
  backoff: {duration: 10s, factor: 2, maxDuration: 1m}
  • Applies per template/step
  • parallelism on workflow or template limits concurrent pods

Parameters and artifacts

inputs:
  artifacts:
  - name: src
    path: /src
    git:
      repo: https://github.com/example/repo.git
      revision: main
outputs:
  parameters:
  - name: out
    valueFrom:
      path: /tmp/out.txt
  artifacts:
  - name: result
    path: /tmp/result.txt
  • Pass between steps: arguments.artifacts: [{name: x, from: "{{steps.a.outputs.artifacts.result}}"}]
  • Repositories: S3 (MinIO), GCS, Azure Blob, Artifactory, HDFS, OSS, Git, HTTP
  • Default repo: artifactRepository in workflow-controller-configmap
  • archive: {none: {}} stops tar/gzip; optional: true won’t fail if missing
  • Shared storage: volumeClaimTemplates (PVC per workflow); emptyDir is per pod

WorkflowTemplate / Cron

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: use-template-
spec:
  workflowTemplateRef:
    name: build-template
---
apiVersion: argoproj.io/v1alpha1
kind: CronWorkflow
metadata:
  name: nightly
spec:
  schedule: "0 2 * * *"
  timezone: America/New_York
  concurrencyPolicy: Replace       # Allow, Forbid, Replace
  startingDeadlineSeconds: 0
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  suspend: false
  workflowSpec:
    entrypoint: main
    templates: [...]
  • WorkflowTemplate is namespaced, ClusterWorkflowTemplate cluster-wide
  • Reference one template inside: templateRef: {name: wt, template: build}; use clusterScope: true for cluster ones
  • WorkflowEventBinding triggers a WorkflowTemplate from the events API

Archive and server

  • Archive: Postgres/MySQL via persistence config; keeps finished workflows after CR deletion
  • Auth modes: server, client, sso
  • Default port 2746

CLI

argo submit wf.yaml [-p msg=hi] [--watch] [--serviceaccount sa]
argo submit --from workflowtemplate/my-template
argo list
argo get NAME
argo watch NAME
argo logs NAME [-f] [POD]
argo delete NAME            # --completed, --older 1d
argo terminate NAME         # stop now, run exit handlers
argo stop NAME              # graceful stop
argo retry NAME             # re-run failed nodes
argo resubmit NAME          # new run
argo suspend NAME
argo resume NAME
argo lint wf.yaml
argo template create|list|get|delete
argo cluster-template create|list
argo cron create|list|get|suspend|resume|delete

Argo Rollouts

Basics

  • Rollout CRD replaces Deployment (same pod template, adds strategy.blueGreen / strategy.canary)
  • Only a pod template change creates a new revision
  • Can use workloadRef to reference an existing Deployment
  • Status: Healthy, Progressing, Paused, Degraded
  • Kubectl plugin: kubectl argo rollouts; dashboard at localhost:3100
  • Install: kubectl apply -n argo-rollouts -f https://github.com/argoproj/argo-rollouts/releases/latest/download/install.yaml

Blue-green

strategy:
  blueGreen:
    activeService: my-app-active
    previewService: my-app-preview
    autoPromotionEnabled: false
    autoPromotionSeconds: 300
    scaleDownDelaySeconds: 30
    prePromotionAnalysis:
      templates:
      - templateName: smoke-tests
    postPromotionAnalysis:
      templates:
      - templateName: load-tests
  • Both services selected by the Rollout; controller patches selectors with the pod-template-hash
  • autoPromotionEnabled: false waits for promote; autoPromotionSeconds promotes after a delay
  • scaleDownDelaySeconds (default 30) keeps the old RS around for fast rollback
  • abortScaleDownDelaySeconds - same for the new RS after abort

Canary

strategy:
  canary:
    maxSurge: 25%
    maxUnavailable: 0
    steps:
    - setWeight: 20
    - pause: {}                    # until promoted
    - setWeight: 50
    - pause: {duration: 10m}
    - analysis:
        templates:
        - templateName: success-rate
        args:
        - name: service-name
          value: my-app
    - setCanaryScale:
        replicas: 3
    analysis:                      # background analysis
      templates:
      - templateName: error-rate
      startingStep: 1
  • Last step goes to 100% implicitly
  • Without a traffic router, weight is approximated by pod counts (maxSurge/maxUnavailable)
  • Steps: setWeight, pause, analysis, experiment, setCanaryScale, setHeaderRoute, setMirrorRoute
  • Failed analysis aborts the rollout and returns to stable

Traffic routing

canary:
  canaryService: my-app-canary
  stableService: my-app-stable
  trafficRouting:
    nginx:
      stableIngress: my-app
    # alb: {ingress: my-app, servicePort: 80}
    # istio: {virtualService: {name: my-app, routes: [primary]}}
    # smi: {trafficSplitName: my-app-split, rootService: my-app}
  • Providers: NGINX, ALB, Istio, SMI, Traefik, Ambassador, Apisix, Kong, Gateway API plugin
  • Istio edits VirtualService weights (or DestinationRule subsets)

AnalysisTemplate

apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: success-rate
spec:
  args:
  - name: service-name
  metrics:
  - name: success-rate
    interval: 30s
    count: 5
    initialDelay: 30s
    successCondition: result[0] >= 0.95
    failureLimit: 3
    provider:
      prometheus:
        address: http://prometheus.monitoring:9090
        query: |
          sum(rate(http_requests_total{service="{{args.service-name}}",status=~"2.."}[1m])) /
          sum(rate(http_requests_total{service="{{args.service-name}}"}[1m]))
  • ClusterAnalysisTemplate cluster-scoped; AnalysisRun is an instance
  • Providers: Prometheus, Datadog, New Relic, Wavefront, CloudWatch, Graphite, InfluxDB, Kayenta, Web, Job
  • successCondition / failureCondition use expr; failureLimit (default 0), inconclusiveLimit, consecutiveErrorLimit (default 4)
  • Step analysis blocks until done; background analysis runs alongside steps
  • Experiment runs extra ReplicaSets (+ analysis) side by side

CLI

kubectl argo rollouts get rollout my-app [--watch]
kubectl argo rollouts status my-app
kubectl argo rollouts list rollouts
kubectl argo rollouts promote my-app [--full]
kubectl argo rollouts pause my-app
kubectl argo rollouts abort my-app
kubectl argo rollouts retry rollout my-app
kubectl argo rollouts restart my-app
kubectl argo rollouts undo my-app [--to-revision=3]
kubectl argo rollouts set image my-app my-container=img:v2
kubectl argo rollouts dashboard
  • Resume a pause with promote, there is no resume

Blue-green vs canary

Blue-greenCanary
Trafficall at once on promotegradual by steps
Resources2x during updateless, partial
Rollbackinstant (switch selector)scale back / abort
Test before prodpreview servicesteps + analysis

Argo Events

Flow

EventSource -> EventBus -> Sensor -> Trigger
  • EventSource - receives events, publishes to bus
  • EventBus - transport; JetStream (default), NATS native (deprecated), Kafka
  • Sensor - dependencies + triggers
  • Default namespace argo-events; EventBus must be named default unless referenced

EventSource

apiVersion: argoproj.io/v1alpha1
kind: EventSource
metadata:
  name: webhook
spec:
  service:
    ports:
    - port: 12000
      targetPort: 12000
  webhook:
    example:
      port: "12000"
      endpoint: /example
      method: POST
  • Types: webhook, github, gitlab, calendar, resource, kafka, nats, redis, amqp, sns, sqs, pubsub, minio, file, slack, storagegrid, hdfs, azure events hub
  • calendar: schedule (cron) or interval, timezone
  • resource: group/version/resource, namespace, eventTypes (ADD, UPDATE, DELETE), filter
  • webhook serves HTTP, HTTPS with serverCertSecret/serverKeySecret
  • Event name = the key under the type (example above)

Sensor

apiVersion: argoproj.io/v1alpha1
kind: Sensor
metadata:
  name: webhook-sensor
spec:
  dependencies:
  - name: dep1
    eventSourceName: webhook
    eventName: example
    filters:
      data:
      - path: body.environment
        type: string
        value: ["production"]
  triggers:
  - template:
      name: wf
      conditions: "dep1"
      argoWorkflow:
        operation: submit
        source:
          resource:
            apiVersion: argoproj.io/v1alpha1
            kind: Workflow
            metadata:
              generateName: hook-
            spec:
              entrypoint: main
              arguments:
                parameters:
                - name: msg
              templates: [...]
        parameters:
        - src:
            dependencyName: dep1
            dataKey: body.message
          dest: spec.arguments.parameters.0.value
  • Multiple dependencies are ANDed; use conditions: "a || b" to change
  • Filters: data, context, time, expr
  • transform.jq reshapes event data
  • Event data: {{.Input.body.field}} in templated triggers, dataKey in parameters
  • Trigger retryStrategy, policy (status check) available

Triggers

  • argoWorkflow - operation: submit, resubmit, resume, retry, suspend, terminate, stop
  • k8s - operation: create, update, patch, delete; any resource
  • http, kafka, nats, awsLambda, slack, log, custom
  • Workflow source can be a WorkflowTemplate via workflowTemplateRef

EventBus

apiVersion: argoproj.io/v1alpha1
kind: EventBus
metadata:
  name: default
spec:
  jetstream:
    version: latest
    replicas: 3

Commands

kubectl get eventsources,sensors,eventbus -n argo-events
kubectl logs -n argo-events -l eventsource-name=webhook
kubectl logs -n argo-events -l sensor-name=webhook-sensor
  • Test webhook: curl -d '{"message":"hi"}' -H 'Content-Type: application/json' localhost:12000/example after port-forwarding the service

Misc

kubectl for CRDs

kubectl get applications,appprojects,applicationsets -n argocd
kubectl get workflows,cronworkflows,workflowtemplates -n argo
kubectl get rollouts,analysisruns,experiments

Common mistakes

  • Sync status vs health status
  • prune (delete removed) vs selfHeal (revert manual edits)
  • Missing RespectIgnoreDifferences=true
  • {{inputs.*}} vs {{workflow.*}} vs {{steps.*}} / {{tasks.*}}
  • Forgetting artifact repository config
  • Rollout with setWeight but no traffic router (pod ratio only)
  • Blue-green needs a Service for active, previewService is optional
  • Sensor dependencies are AND by default