TExcelTAD
Home › GitOps: Argo CD & Flux › Image Automation

Image Automation

The promotion lesson had CI open a pull request to bump an image tag. Flux can do the bump itself: it scans a registry for new tags, picks the newest one that matches a policy, and commits the new tag to Git. The commit goes through Git like any human change, so history and revert still work. This is typically used for environments that should always run the latest build (dev, staging), not for production.

Three objects, two controllers

Object Controller Says
ImageRepository image-reflector-controller "scan ghcr.io/acme/linkly every 5 minutes and remember its tags"
ImagePolicy image-reflector-controller "of those tags, the latest is the highest semver in >=1.5.0-0 <1.6.0"
ImageUpdateAutomation image-automation-controller "check out main, update every file under ./apps/staging that has a policy marker, commit and push"

The two image controllers are not installed by default: add them with --components-extra=image-reflector-controller,image-automation-controller at bootstrap.

Generate and validate the objects

bash · try it yourself
flux create image repository linkly --image=ghcr.io/acme/linkly --interval=5m --export > image.yaml
flux create image policy linkly --image-ref=linkly --select-semver=">=1.5.0-0 <1.6.0" --export >> image.yaml
flux create image update linkly-staging \
  --git-repo-ref=linkly-deploy --git-repo-path=./apps/staging \
  --checkout-branch=main --push-branch=main \
  --author-name=fluxcdbot --author-email=fluxcdbot@users.noreply.github.com \
  --commit-template="staging: {{range .Changed.Changes}}{{.OldValue}} -> {{.NewValue}} {{end}}" \
  --interval=5m --export >> image.yaml
yq -N '.kind + "/" + .metadata.name' image.yaml
yq 'select(.kind == "ImagePolicy") | .spec.policy' image.yaml
kubeconform -strict -summary image.yaml
ImageRepository/linkly
ImagePolicy/linkly
ImageUpdateAutomation/linkly-staging
semver:
  range: '>=1.5.0-0 <1.6.0'
Summary: 3 resources found in 1 file - Valid: 3, Invalid: 0, Errors: 0, Skipped: 0

Staging follows the 1.5 line. The -0 in >=1.5.0-0 matters: in semver ranges, pre-releases like 1.5.0-rc.2 only match if the range itself mentions a pre-release. Staging wants release candidates, production wouldn't.

Markers tell Flux what to edit

The automation only touches lines carrying a policy marker, a comment naming the ImagePolicy (namespace:name), optionally with :tag or :name to update only that part:

yaml
# apps/staging/values.yaml  (or a Deployment, a kustomization.yaml images: entry, a HelmRelease...)
image:
  repository: ghcr.io/acme/linkly # {"$imagepolicy": "flux-system:linkly:name"}
  tag: 1.5.0-rc.1 # {"$imagepolicy": "flux-system:linkly:tag"}

When the policy's latest image becomes ghcr.io/acme/linkly:1.5.0-rc.2, the controller rewrites the tag line, commits with the template above (staging: 1.5.0-rc.1 -> 1.5.0-rc.2) and pushes. The kustomize-controller then applies the new commit like any other. Lines without markers are never changed, so the production folder is safe as long as it has no markers.

How a policy picks "latest", modelled

ImagePolicy supports three orderings: semver (with a range), alphabetical and numerical (both with order: asc|desc), plus filterTags to keep only tags matching a regex and extract a part of them for sorting. This model implements semver with ranges and pre-release rules, and a numerical policy over tags like main-<sha>-<build>:

python · try it yourself
import re

def parse(v):
    m = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?", v)
    if not m:
        return None
    pre = tuple(int(p) if p.isdigit() else p for p in m[4].split(".")) if m[4] else None
    return (int(m[1]), int(m[2]), int(m[3])), pre

def key(v):
    core, pre = parse(v)
    # a release sorts after its pre-releases; numeric identifiers sort before strings
    pre_key = (1,) if pre is None else (0,) + tuple((0, p, "") if isinstance(p, int) else (1, 0, p) for p in pre)
    return core, pre_key

def in_range(v, low, high, allow_pre):
    core, pre = parse(v)
    if pre is not None and not allow_pre:
        return False
    return key(low) <= key(v) < key(high)

tags = ["1.4.0", "1.4.1", "1.5.0-rc.1", "1.5.0-rc.2", "1.5.0-rc.10", "2.0.0-beta.1", "latest", "main-3f2a1c9-118"]
valid = [t for t in tags if parse(t)]
print("staging  >=1.5.0-0 <1.6.0:", max((t for t in valid if in_range(t, "1.5.0-0", "1.6.0", True)), key=key))
print("prod-ish >=1.4.0 <2.0.0:  ", max((t for t in valid if in_range(t, "1.4.0", "2.0.0", False)), key=key))

builds = ["main-3f2a1c9-118", "main-a91be07-121", "main-07c44d2-119", "feature-x-9a8b7c6-130"]
pattern = re.compile(r"^main-[a-f0-9]+-(?P<ts>[0-9]+)
quot;) # filterTags.pattern, extract: $ts picked = max((b for b in builds if pattern.match(b)), key=lambda b: int(pattern.match(b)["ts"])) print("numerical on main builds: ", picked)
staging  >=1.5.0-0 <1.6.0: 1.5.0-rc.10
prod-ish >=1.4.0 <2.0.0:   1.4.1
numerical on main builds:  main-a91be07-121

Note rc.10 beating rc.2 (numeric comparison, not text) and feature-x-…-130 being ignored by the filter even though its number is highest. Never use alphabetical ordering on semver tags: 1.10.0 sorts before 1.9.0 as text.

Guard rails

  • Push to a branch (--push-branch=image-updates) instead of main if you want a pull request and a review for each bump; the cost is a human in the loop.
  • Give the automation's deploy key write access to the deploy repo only, and protect the production folder with CODEOWNERS (markers can be added there by mistake).
  • Tag images immutably (1.5.0-rc.2, main-<sha>-<build>); a policy that follows a moving tag like latest never sees a change.
  • Argo CD's equivalent is the separate Argo CD Image Updater project, which writes back either to Git (a .argocd-source-<app>.yaml file or the kustomization) or to the Application's parameters.

Test yourself

Which file lines does Flux's image-automation-controller change?

  1. Every image: line in the repo
  2. Only lines with a $imagepolicy marker comment under the configured path
  3. Only Deployments
  4. Only files named values.yaml

Why does the staging policy use the range >=1.5.0-0 <1.6.0 rather than >=1.5.0 <1.6.0?

  1. Flux requires it
  2. Pre-release tags like 1.5.0-rc.2 only match ranges that include a pre-release
  3. To exclude 1.5.0
  4. To sort alphabetically

Tags 1.9.0 and 1.10.0 exist. Which policy type would wrongly pick 1.9.0 as the latest?

  1. semver
  2. alphabetical (desc)
  3. numerical with extract
  4. none