You believe in declarative, in GitFlow, in small feature branches. Perfect. Your team is now making small changes on a branch and Merge Requests are happening, the CI is happening, all is good in the world.
Except sometimes people forget and do a kustomize build . | kubectl apply -f -
from the wrong branch (e.g. not master, prior to merge). You know that someday the CD will fix this. But someday is not here.
Enter this small hack piece of brilliance.
$ cat agilicus/v1/branchrestrict/BranchRestrict #!/usr/bin/env /usr/bin/python3 import subprocess import sys import fnmatch import yaml with open(sys.argv[1], 'r') as stream: try: data = yaml.safe_load(stream) except yaml.YAMLError as exc: print("Error parsing BranchRestrict generator input (%s)", file=sys.stderr) branch = subprocess.check_output(['/usr/bin/git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode('ascii') def allow(branch, target): print("---") sys.exit(0) def denied(branch, target): print(f"Error: branch '{branch}', denied by rule '{target}'", file=sys.stderr) sys.exit(1) for target in data['allowed_branches']: if fnmatch.filter([branch], target): allow(branch, target) for target in data['denied_branches']: if fnmatch.filter([branch], target): denied(branch, target)
OK, a plugin generator. We’ll use that like:
$ cat master-only.yaml --- apiVersion: agilicus/v1 kind: BranchRestrict metadata: name: not-used-br name: branch-restrict allowed_branches: master denied_branches: '*'
Perfect. Now no-one will forget and accidentally apply from their not-yet-merged feature branch. Beauty.