TExcelTAD
Home › GitOps: Argo CD & Flux › GitOps Exercises

GitOps Exercises

The first four exercises re-implement, as small pure functions, the rules a GitOps agent applies: computing a sync plan, gating sync waves on health, generating Applications, and promoting only the right values. The calls are already in place; run the starter to see placeholder output, complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real Flux session with a bug to find.

Exercise 1: A sync plan with prune and ignore rules

Topics: The Reconcile Loop, Drift, Self-Heal & Prune

Write sync_plan(desired, live, managed, prune, ignore). Objects are {"Kind/name": {field: value}}. Return, in this order: for each desired object (sorted by key) create KEY if it's not live, or patch KEY f1,f2 listing the differing fields in sorted order, skipping fields in ignore[KEY]; then, for each live object (sorted) that is managed but no longer desired, delete KEY when prune is true and orphan KEY otherwise. Never touch unmanaged objects.

python · try it yourself
def sync_plan(desired, live, managed, prune, ignore):
    plan = []
    # TODO
    return plan

desired = {"Deployment/linkly": {"image": "1.5.0", "replicas": 2},
           "Service/linkly": {"port": 80},
           "HTTPRoute/linkly": {"host": "lnk.example.com"}}
live = {"Deployment/linkly": {"image": "1.4.1", "replicas": 6},
        "Service/linkly": {"port": 80},
        "CronJob/cleanup": {"schedule": "0 3 * * *"},
        "Secret/linkly-db": {"url": "..."}}
managed = {"Deployment/linkly", "Service/linkly", "CronJob/cleanup"}
print(sync_plan(desired, live, managed, prune=True, ignore={"Deployment/linkly": {"replicas"}}))
print(sync_plan(desired, live, managed, prune=False, ignore={}))
[]
[]

Expected output:

text
['patch Deployment/linkly image', 'create HTTPRoute/linkly', 'delete CronJob/cleanup']
['patch Deployment/linkly image,replicas', 'create HTTPRoute/linkly', 'orphan CronJob/cleanup']
Show solution
python
def sync_plan(desired, live, managed, prune, ignore):
    plan = []
    for key in sorted(desired):
        if key not in live:
            plan.append(f"create {key}")
            continue
        changed = sorted(f for f, v in desired[key].items()
                         if f not in ignore.get(key, set()) and live[key].get(f) != v)
        if changed:
            plan.append(f"patch {key} {','.join(changed)}")
    for key in sorted(live):
        if key in managed and key not in desired:
            plan.append(f"{'delete' if prune else 'orphan'} {key}")
    return plan

Secret/linkly-db never appears: it is neither desired nor managed. The ignored replicas (owned by an HPA) disappears from the first plan only.

Exercise 2: Gate sync waves on health

Topics: Sync Waves & Hooks, Health Checks

Write next_step(objects). Go through the waves from lowest to highest. In the first wave that has unsynced objects, return wave W: apply A, B (names sorted). If a wave is fully synced but some objects in it have a health other than None (no check) or "Healthy", return wave W: wait for A, B. If every wave is synced and healthy, return done.

python · try it yourself
def next_step(objects):
    # TODO
    return "?"

objs = [
    {"name": "ConfigMap/linkly-config", "wave": -1, "synced": True, "health": None},
    {"name": "StatefulSet/redis", "wave": -1, "synced": True, "health": "Progressing"},
    {"name": "Deployment/linkly", "wave": 0, "synced": False, "health": "Missing"},
    {"name": "HTTPRoute/linkly", "wave": 1, "synced": False, "health": None},
]
print(next_step(objs))
objs[1]["health"] = "Healthy"; print(next_step(objs))
objs[2].update(synced=True, health="Progressing"); print(next_step(objs))
objs[2]["health"] = "Healthy"; print(next_step(objs))
objs[3]["synced"] = True; print(next_step(objs))
?
?
?
?
?

Expected output:

text
wave -1: wait for StatefulSet/redis
wave 0: apply Deployment/linkly
wave 0: wait for Deployment/linkly
wave 1: apply HTTPRoute/linkly
done
Show solution
python
def next_step(objects):
    for w in sorted({o["wave"] for o in objects}):
        group = [o for o in objects if o["wave"] == w]
        todo = sorted(o["name"] for o in group if not o["synced"])
        if todo:
            return f"wave {w}: apply {', '.join(todo)}"
        waiting = sorted(o["name"] for o in group if o["health"] not in (None, "Healthy"))
        if waiting:
            return f"wave {w}: wait for {', '.join(waiting)}"
    return "done"

The first call shows the blocking behaviour: linkly can't start while Redis in wave -1 is still Progressing.

Exercise 3: An ApplicationSet-style generator

Topics: ApplicationSets, Repository Layouts

Write generate(dirs, include_prefix, exclude, clusters). A directory matches if it starts with include_prefix, is exactly one level below it (like the pattern apps/*), and isn't in exclude. Its last path segment is the environment. For each matching directory (sorted) and each cluster (in the given order) whose envs contain that environment, produce "<cluster>-linkly-<env> -> <server> path=<dir>".

python · try it yourself
def generate(dirs, include_prefix, exclude, clusters):
    apps = []
    # TODO
    return apps

dirs = ["apps/base", "apps/staging", "apps/production", "apps/qa", "apps/production/extra", "infrastructure/gateway"]
clusters = [{"name": "eu", "server": "https://eu.example.com", "envs": ["staging", "production"]},
            {"name": "us", "server": "https://us.example.com", "envs": ["production"]},
            {"name": "lab", "server": "https://lab.example.com", "envs": ["qa", "staging"]}]
for app in generate(dirs, "apps/", {"apps/base"}, clusters):
    print(app)
print("total:", len(generate(dirs, "apps/", {"apps/base"}, clusters)))
total: 0

Expected output:

text
eu-linkly-production -> https://eu.example.com path=apps/production
us-linkly-production -> https://us.example.com path=apps/production
lab-linkly-qa -> https://lab.example.com path=apps/qa
eu-linkly-staging -> https://eu.example.com path=apps/staging
lab-linkly-staging -> https://lab.example.com path=apps/staging
total: 5
Show solution
python
def generate(dirs, include_prefix, exclude, clusters):
    apps = []
    for d in sorted(dirs):
        if not d.startswith(include_prefix) or d.count("/") != include_prefix.count("/") or d in exclude:
            continue
        env = d.rsplit("/", 1)[1]
        for c in clusters:
            if env in c["envs"]:
                apps.append(f"{c['name']}-linkly-{env} -> {c['server']} path={d}")
    return apps

apps/production/extra is two levels deep and doesn't match apps/*, just as in Argo CD's Git directory generator. This is a matrix of directories and clusters, filtered by a cluster property.

Exercise 4: Promote only what should move

Topics: Environment Promotion by Commit

Write promote(staging, production). Copy only the fields in PROMOTABLE (pairs of section and field) from staging to production, return the new production values and a list of changes section.field: old -> new in sorted order. Don't modify the production argument.

python · try it yourself
PROMOTABLE = {("image", "tag"), ("chart", "version")}

def promote(staging, production):
    out, changes = production, []
    # TODO
    return out, changes

staging = {"image": {"tag": "1.5.0"}, "chart": {"version": "0.4.0"}, "replicaCount": 1, "logLevel": "debug"}
production = {"image": {"tag": "1.4.1"}, "chart": {"version": "0.4.0"}, "replicaCount": 3}
new, changes = promote(staging, production)
print(changes)
print(new)
print("production argument still:", production["image"]["tag"])
[]
{'image': {'tag': '1.4.1'}, 'chart': {'version': '0.4.0'}, 'replicaCount': 3}
production argument still: 1.4.1

Expected output:

text
['image.tag: 1.4.1 -> 1.5.0']
{'image': {'tag': '1.5.0'}, 'chart': {'version': '0.4.0'}, 'replicaCount': 3}
production argument still: 1.4.1
Show solution
python
def promote(staging, production):
    out = {k: (dict(v) if isinstance(v, dict) else v) for k, v in production.items()}
    changes = []
    for section, field in sorted(PROMOTABLE):
        new = staging.get(section, {}).get(field)
        if new is None:
            continue
        old = out.setdefault(section, {}).get(field)
        if old != new:
            out[section][field] = new
            changes.append(f"{section}.{field}: {old} -> {new}")
    return out, changes

replicaCount and logLevel stay environment-specific, and the chart version is already equal, so the promotion commit changes one line.

Exercise 5: The URL that went missing

Topics: The Kustomize Controller

A Flux Kustomization substitutes ${domain} into linkly's ConfigMap, but production ended up with BASE_URL: https://. Run the session, find the bug, then change it so that (a) the URL is right and (b) the same kind of mistake fails the build next time instead of producing an empty value.

bash · try it yourself
mkdir -p linkly-deploy/apps/production && cd linkly-deploy
cat > apps/production/config.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata: {name: linkly-config}
data:
  BASE_URL: https://${domain}
EOF
printf 'resources: [config.yaml]\n' > apps/production/kustomization.yaml
flux create kustomization linkly-production --source=GitRepository/linkly-deploy \
  --path=./apps/production --prune=true --interval=10m --target-namespace=linkly-prod --export > ks.yaml
yq -i '.spec.postBuild.substitute.domian = "lnk.example.com"' ks.yaml
flux build kustomization linkly-production --path ./apps/production --kustomization-file ./ks.yaml --dry-run | yq 'select(.kind == "ConfigMap") | .data'
BASE_URL: https://
Show solution

The variable is spelled domian in the Kustomization, so ${domain} has no value and Flux substitutes an empty string, silently. Fix the key, and build with --strict-substitute, which fails when a variable without a default is missing (on the cluster, the kustomize-controller has the matching StrictPostBuildSubstitutions feature gate):

bash · try it yourself
mkdir -p linkly-deploy/apps/production && cd linkly-deploy
cat > apps/production/config.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata: {name: linkly-config}
data:
  BASE_URL: https://${domain}
EOF
printf 'resources: [config.yaml]\n' > apps/production/kustomization.yaml
flux create kustomization linkly-production --source=GitRepository/linkly-deploy \
  --path=./apps/production --prune=true --interval=10m --target-namespace=linkly-prod --export > ks.yaml
yq -i '.spec.postBuild.substitute.domian = "lnk.example.com"' ks.yaml
echo "--- strict, with the typo:"
flux build kustomization linkly-production --path ./apps/production --kustomization-file ./ks.yaml \
  --dry-run --strict-substitute > /dev/null 2>err.txt; echo "exit code: $?"; grep -o 'variable substitution failed.*' err.txt
yq -i 'del(.spec.postBuild.substitute.domian) | .spec.postBuild.substitute.domain = "lnk.example.com"' ks.yaml
echo "--- strict, fixed:"
flux build kustomization linkly-production --path ./apps/production --kustomization-file ./ks.yaml \
  --dry-run --strict-substitute | yq 'select(.kind == "ConfigMap") | .data'
--- strict, with the typo:
exit code: 1
variable substitution failed: variable not set (strict mode): "domain"
--- strict, fixed:
BASE_URL: https://lnk.example.com

Test yourself

In Exercise 2, why does the first call return wait for StatefulSet/redis rather than apply Deployment/linkly?

  1. Deployments are always applied last
  2. Wave -1 is synced but not healthy yet, and later waves wait for it
  3. Redis has a higher wave number
  4. ConfigMaps have no health

What did --strict-substitute change in Exercise 5?

  1. It renamed the variable
  2. It turned a missing variable without a default into a build error instead of an empty string
  3. It disabled substitution
  4. It applied to the cluster