Ravindra BagaleCourses & study guides मराठी

Chapter 96: Flux GitOps — Sources, Reconciliation and Safe Local Practice

DevOps

96.18 Entirely local lab: a small model, not Flux

Fictional teaching story. At a fictional classroom, Anika and Max use dictionaries and harmless YAML files to practise decisions without connecting to Kubernetes.

Why

You can learn a comparison rule locally without pretending you tested a real controller or cluster security.

What

Save the supplied model and tests in a new personal practice directory. Use no existing repository, real manifests, credentials or cluster context.

How

Entirely local lab: a small model, not Flux
Original classroom diagram: Entirely local lab: a small model, not Flux

MODEL ONLY — NOT FLUX. The executed lab is ordinary local Python. It does not implement Flux controllers, Kubernetes managed fields, real Kustomize rendering, CRD schema validation, Git fetching, Helm, admission control or authorization. Its tests are not API compatibility proofs or cluster security validation. The URL parser never connects to its fictional URL. A path check in this model is deliberately narrower than actual Kustomize path semantics.

The local model has explicit inputs

A model is a deliberately simplified representation. A fixture is invented test input. Our desired/live dictionaries contain fictional names and strings; previous_inventory is a list of previously managed names.

Immediate practice example

  1. Read the example from top to bottom. Do not send it to a real cluster.
from fluxmodel import duration, plan
print(duration("1m30s"))
print(plan({"config":"blue"}, {"config":"red", "old":"demo"}, ["config", "old"], prune=False))
  1. Read the expected result.

Illustrative output: not executed by Flux, kubectl, Helm or Kubernetes.

90
{'apply': ['config'], 'delete': []}
  1. Understand each line in plain English.

The import reads the local file printed below. The duration subset converts this example into seconds. The plan compares fictional strings and proposes one apply name. Because prune is false, it proposes no deletion. This result was actually reproduced with local Python; the general example-output banner remains a warning that no Flux or cluster output exists.

Save fluxmodel.py

Copy this complete local model into a new empty practice folder. The program contains no subprocess, network, Git or Kubernetes operations.

"""LOCAL teaching model only: NOT Flux, Kustomize, API validation or security proof.
No subprocesses, network, Kubernetes client, credentials or Git operations.
"""
import re
from pathlib import PurePosixPath
from urllib.parse import urlparse
from copy import deepcopy

def duration(text):
    # Intentional subset: positive whole h/m/s, ordered once each; NOT full Go grammar.
    m=re.fullmatch(r'(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?',text)
    if not m or not any(x is not None for x in m.groups()):raise ValueError('bad demo duration')
    seconds=sum(int(x or 0)*n for x,n in zip(m.groups(),[3600,60,1]))
    if seconds<=0:raise ValueError('positive duration required')
    return seconds

def source_url(text):
    p=urlparse(text)
    if p.scheme not in {'https','ssh','oci'} or not p.hostname or not p.path.strip('/'):
        raise ValueError('explicit URL required')
    if p.username or p.password:raise ValueError('demo forbids embedded identity/credentials')
    return p.scheme,p.hostname,p.path

def relative_path(text):
    p=PurePosixPath(text)
    if not text or p.is_absolute() or '..' in p.parts:raise ValueError('path leaves demo scope')
    return p.as_posix()

def validate_source(obj):
    assert obj['apiVersion']=='source.toolkit.fluxcd.io/v1'
    assert obj['kind']=='GitRepository'
    duration(obj['spec']['interval']);source_url(obj['spec']['url'])
    assert obj['spec']['ref']['branch']=='main'
    return True

def validate_kustomization(obj):
    # Shape checks only; deliberately NOT a CRD schema validator.
    assert obj['apiVersion']=='kustomize.toolkit.fluxcd.io/v1'
    assert obj['kind']=='Kustomization'
    s=obj['spec'];duration(s['interval']);relative_path(s['path'])
    assert type(s['prune']) is bool
    assert s['sourceRef']=={'kind':'GitRepository','name':'classroom'}
    return True

def patch_config(base,patch):
    # Only merge ConfigMap.data for matching kind/name; not general Kustomize merge.
    if base['kind']!='ConfigMap' or patch['kind']!=base['kind'] or patch['metadata']['name']!=base['metadata']['name']:
        raise ValueError('wrong demo patch target')
    if set(patch)-{'apiVersion','kind','metadata','data'}:raise ValueError('unsupported demo patch')
    out=deepcopy(base);out.setdefault('data',{}).update(patch.get('data',{}));return out

def plan(desired,live,previous_inventory,prune=False,protected=(),suspended=False,dependency_ready=True):
    # Names stand in for resource identities; real Flux tracks richer inventory/field ownership.
    if suspended or not dependency_ready:return {'apply':[],'delete':[]}
    apply=sorted(k for k,v in desired.items() if live.get(k)!=v)
    delete=sorted(set(previous_inventory)-set(desired)-set(protected)) if prune else []
    return {'apply':apply,'delete':delete}

if __name__=='__main__':
    print('MODEL ONLY: no cluster or API contacted')
    print('Interval seconds:',duration('1m30s'))
    print(plan({'config':'blue'},{'config':'red','old':'demo'},['config','old'],prune=False))

Save test_fluxmodel.py

A unit test checks a small specified behaviour. The tests below use only synthetic values, including deliberately invalid input.

import unittest
from fluxmodel import *
class FluxModelTests(unittest.TestCase):
    def test_duration(self):self.assertEqual(duration('1m30s'),90)
    def test_hours(self):self.assertEqual(duration('1h'),3600)
    def test_zero(self):
        with self.assertRaises(ValueError):duration('0s')
    def test_bad_unit(self):
        with self.assertRaises(ValueError):duration('1day')
    def test_empty(self):
        with self.assertRaises(ValueError):duration('')
    def test_url(self):self.assertEqual(source_url('https://git.example.invalid/classroom.git')[0],'https')
    def test_scp_rejected(self):
        with self.assertRaises(ValueError):source_url('git@example.invalid:repo.git')
    def test_inline_identity_rejected(self):
        with self.assertRaises(ValueError):source_url('https://demo@git.example.invalid/classroom.git')
    def test_relative(self):self.assertEqual(relative_path('./clusters/lab'),'clusters/lab')
    def test_parent(self):
        with self.assertRaises(ValueError):relative_path('../other-team')
    def test_absolute(self):
        with self.assertRaises(ValueError):relative_path('/etc')
    def test_drift(self):self.assertEqual(plan({'a':'blue'},{'a':'red'},['a'])['apply'],['a'])
    def test_same(self):self.assertEqual(plan({'a':'blue'},{'a':'blue'},['a'])['apply'],[])
    def test_no_prune(self):self.assertEqual(plan({}, {'old':'demo'},['old'])['delete'],[])
    def test_prune_inventory(self):self.assertEqual(plan({}, {'old':'demo','foreign':'demo'},['old'],True)['delete'],['old'])
    def test_protected(self):self.assertEqual(plan({}, {},['keep'],True,['keep'])['delete'],[])
    def test_suspend(self):self.assertEqual(plan({'a':'new'},{},[],suspended=True)['apply'],[])
    def test_dependency(self):self.assertEqual(plan({'a':'new'},{},[],dependency_ready=False)['apply'],[])
    def test_patch_copy(self):
        base={'apiVersion':'v1','kind':'ConfigMap','metadata':{'name':'demo'},'data':{'color':'blue'}}
        patch={'apiVersion':'v1','kind':'ConfigMap','metadata':{'name':'demo'},'data':{'color':'green'}}
        self.assertEqual(patch_config(base,patch)['data']['color'],'green');self.assertEqual(base['data']['color'],'blue')
    def test_patch_target(self):
        with self.assertRaises(ValueError):patch_config({'kind':'ConfigMap','metadata':{'name':'a'}},{'kind':'ConfigMap','metadata':{'name':'b'}})
if __name__=='__main__':unittest.main()

Run only these local Python checks

  1. Open your own new practice directory containing the two files.
  2. Run the local program and local tests. Neither command contacts a cluster.
python3 fluxmodel.py
python3 -m unittest -v
  1. Compare with the actual local output recorded during chapter preparation.

ACTUAL local Python output — NOT Flux integration.

MODEL ONLY: no cluster or API contacted
Interval seconds: 90
{'apply': ['config'], 'delete': []}

Ran 20 tests
OK
  1. Change only fictional input and explain the result before rerunning.

duration accepts only positive ordered whole-hour/minute/second combinations, not every Go duration. source_url parses text and deliberately rejects embedded identity; that is a classroom rule, not a full Flux URL validator. relative_path rejects parent traversal for its narrow input. patch_config copies and merges only matching ConfigMap data. plan compares dictionaries, skips work when paused or blocked by a dependency, and only proposes deletion from its supplied inventory when prune is true. It never deletes files or resources. The tests do not establish any production security property.

Local YAML reading exercise

  1. Save the GitRepository, Flux Kustomization, ConfigMap and local kustomization.yaml examples as separate files in an empty practice directory.
  2. Read each apiVersion aloud before identifying its purpose.
  3. Compare the sourceRef name, relative path and base/overlay file names. A YAML parser accepting the text does not mean Kubernetes accepts its schema.
  4. The preparation process parsed every displayed YAML document locally. No kubectl, Flux CLI, Kustomize engine, Helm engine, Git remote or cluster was run. You do not need to install a new dependency or service for the Python tests above.

Ravindra Bagale's Tip

Passing local tests proves these narrow model rules, not that Flux deployed anything.

Did you understand? Let us try it once more.