TExcelTAD
Home › GitOps: Argo CD & Flux › ApplicationSets

ApplicationSets

An ApplicationSet is a template plus one or more generators. Each generator produces a list of parameter sets; the applicationset-controller renders the template once per set and creates, updates or deletes the resulting Applications to match. Add a folder, a cluster or a pull request, and an Application appears; remove it, and the Application goes.

Generators

Generator Produces one parameter set per… Example use
list element of a literal list a fixed set of environments
clusters cluster registered in Argo CD (filter by labels) deploy add-ons to every cluster labelled env=prod
git (directories) folder matching a path pattern one app per apps/* folder
git (files) JSON/YAML file matching a pattern, with its contents as parameters one app per config.json
matrix combination of two generators every app × every cluster
merge set from one generator, overridden by matching sets from others defaults plus per-cluster exceptions
pullRequest / scmProvider open PR / repository in GitHub, GitLab… preview environments per PR
clusterDecisionResource, plugin external decisions advanced cases

With goTemplate: true (recommended), templates use Go templates with Sprig functions: {{.path.basename}}, {{index .path.segments 1}}, {{.name}}. Add goTemplateOptions: ["missingkey=error"] so a typo fails instead of silently rendering an empty string.

The generators, modelled

This model implements a Git directory generator over linkly-deploy's folders, a list generator of clusters, and their matrix, then renders an Application name and namespace for each combination:

python · try it yourself
from fnmatch import fnmatch

repo_dirs = ["apps/staging", "apps/production", "apps/base", "infrastructure/gateway"]

def git_directories(include, exclude=()):
    out = []
    for d in sorted(repo_dirs):
        if fnmatch(d, include) and not any(fnmatch(d, e) for e in exclude):
            out.append({"path": {"path": d, "basename": d.split("/")[-1], "segments": d.split("/")}})
    return out

def list_gen(elements):
    return [dict(e) for e in elements]

def matrix(a, b):
    return [{**x, **y} for x in a for y in b]

def render(params):
    env = params["path"]["basename"]
    ns = {"staging": "linkly-staging", "production": "linkly-prod"}[env]
    return f'{params["cluster"]}-linkly-{env}: path={params["path"]["path"]} ns={ns} server={params["url"]}'

dirs = git_directories("apps/*", exclude=["apps/base"])
print("git directories:", [d["path"]["basename"] for d in dirs])
clusters = list_gen([{"cluster": "eu", "url": "https://eu.k8s.example.com"},
                     {"cluster": "us", "url": "https://us.k8s.example.com"}])
for params in matrix(dirs, clusters):
    print(render(params))
git directories: ['production', 'staging']
eu-linkly-production: path=apps/production ns=linkly-prod server=https://eu.k8s.example.com
us-linkly-production: path=apps/production ns=linkly-prod server=https://us.k8s.example.com
eu-linkly-staging: path=apps/staging ns=linkly-staging server=https://eu.k8s.example.com
us-linkly-staging: path=apps/staging ns=linkly-staging server=https://us.k8s.example.com

Two folders × two clusters = four Applications. Adding apps/qa adds two more, with no edits to the ApplicationSet.

The real thing

The same idea as an ApplicationSet. The apps/base folder is excluded because it is not an environment:

bash · try it yourself
cat > linkly-appset.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata: {name: linkly, namespace: argocd}
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - git:
        repoURL: https://github.com/acme/linkly-deploy.git
        revision: main
        directories:
          - path: apps/*
          - path: apps/base
            exclude: true
  template:
    metadata:
      name: 'linkly-{{.path.basename}}'
      labels: {env: '{{.path.basename}}'}
    spec:
      project: linkly                 # fixed, never a template parameter
      source:
        repoURL: https://github.com/acme/linkly-deploy.git
        targetRevision: main
        path: '{{.path.path}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: '{{if eq .path.basename "production"}}linkly-prod{{else}}linkly-{{.path.basename}}{{end}}'
      syncPolicy:
        automated: {prune: true, selfHeal: true}
        syncOptions: [CreateNamespace=true]
  syncPolicy:
    preserveResourcesOnDeletion: true   # deleting the ApplicationSet keeps the deployed objects
EOF
kubeconform -strict -summary linkly-appset.yaml
Summary: 1 resource found in 1 file - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0

You can preview what the controller would generate against a live Argo CD with argocd appset generate linkly-appset.yaml (sample session; it needs API access because generators read Git and clusters through Argo CD).

Safety rules for ApplicationSets

  • Never template project from generator parameters, especially with pullRequest or scmProvider generators: anyone who can open a PR or create a repo could then pick a more privileged project. The Argo CD docs call this out explicitly.
  • Deletion cascades: removing a folder deletes its generated Application and, through the finalizer, its workload. spec.syncPolicy.applicationsSyncPolicy: create-update stops the controller from deleting Applications at all; preserveResourcesOnDeletion: true keeps workloads if the ApplicationSet itself is deleted.
  • Generated Applications are owned by the controller: manual edits to them are overwritten. Change the template instead.

Rolling out across environments: Progressive Syncs

A plain ApplicationSet lets every generated app sync at once, so a change to the template hits staging and production together. Progressive Syncs (Beta since Argo CD 3.3, enabled on the controller with --enable-progressive-syncs or applicationsetcontroller.enable.progressive.syncs: "true" in argocd-cmd-params-cm) syncs groups of apps in steps, waiting for each step to be healthy:

yaml
spec:
  strategy:
    type: RollingSync
    rollingSync:
      steps:
        - matchExpressions:
            - {key: env, operator: In, values: [staging]}
        - matchExpressions:
            - {key: env, operator: In, values: [production]}
          maxUpdate: 50%          # at most half of the production apps at a time

The steps select Applications by their labels, which is why the template above sets env. Progressive Syncs control the timing of syncs for one change; promotion of versions between environments still happens by commit (Environment Promotion).

Test yourself

A git directory generator matches apps/* and excludes apps/base. The repo has apps/base, apps/staging, apps/production and apps/qa. How many Applications are generated?

  1. 1
  2. 3
  3. 4
  4. 0 until someone runs a sync

Why must project in an ApplicationSet template not come from a pull-request generator parameter?

  1. Projects can't be templated at all
  2. A PR author could choose a more privileged project and escape its restrictions
  3. It makes the Applications OutOfSync
  4. Pull requests have no parameters

What does goTemplateOptions: ["missingkey=error"] change?

  1. Nothing in goTemplate mode
  2. A reference to a parameter that doesn't exist fails instead of rendering an empty value
  3. It disables Sprig functions
  4. It makes the controller skip broken generators silently