API Contract Smoke Test with Slack Alerts
Validate API status codes and response markers on a schedule, save evidence, and alert only on failures.
Migrate ingress-nginx to Gateway API with ingress2gateway. Compare answers request by request, approve the result, then roll back or retire the Ingresses.
# SPDX-License-Identifier: Apache-2.0
id: ingress-nginx-to-gateway-api-verified-migration
namespace: company.team
description: Migrate ingress-nginx Ingresses to Gateway API routes side by side.
A request-by-request comparison shows whether the new routes answer like the
old ones. Only then can a person accept the result and retire the old
Ingresses.
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: mode
type: SELECT
values:
- MIGRATE
- ROLLBACK
- RETIRE
defaults: MIGRATE
description: MIGRATE translates the Ingresses, creates the Gateway API routes
next to them and compares the answers. ROLLBACK deletes what MIGRATE
created. RETIRE deletes the old Ingresses after the new routes were
accepted and your traffic moved.
- id: gateway_class
type: STRING
defaults: ""
description: Name of an accepted GatewayClass, for example the one of Envoy
Gateway or NGINX Gateway Fabric. Every generated Gateway uses it.
- id: emitter
type: SELECT
values:
- envoy-gateway
- standard
defaults: envoy-gateway
description: Choose envoy-gateway when the GatewayClass is Envoy Gateway, so
that allow lists and body limits become Envoy policies. standard emits
only Gateway API objects.
- id: ingress_class
type: STRING
defaults: nginx
description: Ingress class that ingress-nginx serves.
- id: namespaces
type: STRING
defaults: ""
validator: ^([a-z0-9-]+(,[a-z0-9-]+)*)?$
description: Comma separated namespaces to migrate. Empty means all namespaces.
- id: old_http_endpoint
type: STRING
defaults: ""
validator: ^([^:\s]+:[0-9]{1,5})?$
description: host:port that reaches ingress-nginx over HTTP from the worker.
Empty reads the load balancer address of the ingress-nginx-controller
Service.
- id: old_https_endpoint
type: STRING
defaults: ""
validator: ^([^:\s]+:[0-9]{1,5})?$
description: host:port that reaches ingress-nginx over HTTPS. Empty means port
443 of the Service address.
- id: new_http_endpoint
type: STRING
defaults: ""
validator: ^([^:\s]+:[0-9]{1,5})?$
description: host:port that reaches the Gateways over HTTP. Empty uses the
address of each Gateway.
- id: new_https_endpoint
type: STRING
defaults: ""
validator: ^([^:\s]+:[0-9]{1,5})?$
description: host:port that reaches the Gateways over HTTPS. Empty uses the
address of each Gateway.
- id: compare_body
type: BOOL
defaults: true
description: Also compare the body of every 2xx answer. Turn it off when the
backends return different content on every request.
- id: migration_name
type: STRING
defaults: ingress-nginx
validator: ^[a-z0-9-]{1,40}$
description: Name of the migration. The state is kept in the namespace KV store
and every created object carries it as a label.
- id: tools_image
type: STRING
defaults: alpine/k8s:1.31.4
description: Image with kubectl, Python 3, jq, yq and curl.
- id: docker_network
type: STRING
defaults: bridge
description: Docker network of the task containers. They must reach the
Kubernetes API and both ingress addresses.
- id: dry_run
type: BOOL
defaults: true
description: Plan only. Nothing is created in the cluster.
- id: auto_remediate
type: BOOL
defaults: false
description: Allows the flow to change the cluster. A change runs only when this
is true and dry_run is false. Each change waits for an approval.
variables:
live: "{{ inputs.dry_run == false and inputs.auto_remediate == true }}"
approval_window: PT24H
programmed_wait: "150"
tool_url: https://github.com/kubernetes-sigs/ingress2gateway/releases/download/v1.2.0/ingress2gateway_Linux_x86_64.tar.gz
tool_sha256: 9aaef850521a6b217bc358fc2267429629990dfe624ede601178c73f32ccad6d
lib_py: |
import hashlib, json, os, re, subprocess, sys, tarfile, urllib.request
A = 'nginx.ingress.kubernetes.io/'
TOOL_VERSION = '1.2.0'
# Annotations that ingress2gateway 1.2.0 converts (provider README). Anything else on an Ingress is reported.
CONVERTED = {A + n for n in (
'canary canary-by-header canary-by-header-value canary-weight canary-weight-total rewrite-target app-root '
'permanent-redirect permanent-redirect-code temporal-redirect temporal-redirect-code ssl-redirect upstream-vhost '
'connection-proxy-header x-forwarded-prefix proxy-connect-timeout proxy-send-timeout proxy-read-timeout '
'proxy-body-size client-body-buffer-size backend-protocol use-regex enable-cors cors-allow-origin cors-allow-methods '
'cors-allow-headers cors-expose-headers cors-allow-credentials cors-max-age whitelist-source-range denylist-source-range '
'proxy-ssl-verify proxy-ssl-secret proxy-ssl-name proxy-ssl-server-name ssl-passthrough').split()}
HARMLESS = {A + 'ingress.class', 'kubernetes.io/ingress.class'}
SECURITY = re.compile(r'^' + re.escape(A) + r'(auth-|enable-modsecurity|modsecurity|enable-owasp|limit-|configuration-snippet|server-snippet|stream-snippet)')
def run(cmd, **kw):
return subprocess.run(cmd, capture_output=True, text=True, **kw)
def out(**values):
print('::' + json.dumps({'outputs': values}) + '::')
def setup_kube():
with open('kubeconfig', 'w') as f:
f.write(os.environ['KUBECONFIG_DATA'])
os.chmod('kubeconfig', 0o600)
os.environ['KUBECONFIG'] = os.path.abspath('kubeconfig')
def kubectl(*args, check=True):
r = run(['kubectl', *args])
if check and r.returncode != 0:
print(r.stderr.strip() or r.stdout.strip(), file=sys.stderr)
sys.exit('kubectl ' + ' '.join(args[:3]) + ' failed')
return r
def fetch_tool():
url, want = os.environ['TOOL_URL'], os.environ['TOOL_SHA256']
data = urllib.request.urlopen(url, timeout=60).read()
got = hashlib.sha256(data).hexdigest()
if got != want:
sys.exit('ingress2gateway archive checksum mismatch: expected %s, got %s' % (want, got))
with open('tool.tgz', 'wb') as f:
f.write(data)
with tarfile.open('tool.tgz') as t:
t.extract('ingress2gateway', '.')
os.chmod('ingress2gateway', 0o755)
def inventory():
"""Ingresses of the chosen class, in the chosen namespaces, as one List."""
ns = {n.strip() for n in os.environ.get('NAMESPACES', '').split(',') if n.strip()}
cls = os.environ['INGRESS_CLASS']
items = json.loads(kubectl('get', 'ingress', '-A', '-o', 'json').stdout)['items']
keep = []
for i in items:
c = i['spec'].get('ingressClassName') or i['metadata'].get('annotations', {}).get('kubernetes.io/ingress.class')
if c != cls or (ns and i['metadata']['namespace'] not in ns):
continue
keep.append(i)
keep.sort(key=lambda i: (i['metadata']['namespace'], i['metadata']['name']))
return keep
def key(i):
return i['metadata']['namespace'] + '/' + i['metadata']['name']
def inventory_hash(items):
core = [[key(i), i['spec'], {k: v for k, v in i['metadata'].get('annotations', {}).items() if k.startswith(A)}] for i in items]
return hashlib.sha256(json.dumps(core, sort_keys=True).encode()).hexdigest()
def translate(items):
"""Runs ingress2gateway on exactly these Ingresses. Returns (objects, warnings)."""
with open('inventory-subset.json', 'w') as f:
json.dump({'apiVersion': 'v1', 'kind': 'List', 'items': items}, f)
r = run(['./ingress2gateway', 'print', '--input-file', 'inventory-subset.json', '--providers', 'ingress-nginx', '-A',
'--ingress-nginx-ingress-class', os.environ['INGRESS_CLASS'], '--emitter', os.environ['EMITTER'],
'--allow-experimental-gw-api', '--no-color', '-o', 'yaml'])
if r.returncode != 0:
sys.exit('ingress2gateway failed: ' + r.stderr.strip()[-600:])
y = run(['yq', 'eval-all', '-o=json', '-I=0', '.'], input=r.stdout)
if y.returncode != 0:
sys.exit('could not read the ingress2gateway output: ' + y.stderr.strip()[-300:])
objs = []
for line in y.stdout.splitlines():
if line.strip():
o = json.loads(line)
objs.extend(o.get('items', []) if o.get('kind') == 'List' else [o])
for o in objs:
o.pop('status', None)
meta = o.setdefault('metadata', {})
meta.setdefault('labels', {})['migration.kestra.io/name'] = os.environ['MIGRATION']
meta['labels']['app.kubernetes.io/managed-by'] = 'kestra'
if o['kind'] == 'Gateway':
o['spec']['gatewayClassName'] = os.environ['GATEWAY_CLASS']
return objs, parse_warnings(r.stderr)
def parse_warnings(text):
text = re.sub(r'\x1b\[[0-9;]*m', '', text)
blocks, cur = [], None
for line in text.splitlines():
m = re.match(r'^\W*(WARN|INFO|ERROR)\b', line)
if m and '┌' in line:
cur = {'level': m.group(1), 'message': [], 'source': '', 'object': ''}
blocks.append(cur)
continue
if cur is None:
continue
body = line.replace('│', '').replace('└', '').replace('─', '').strip()
if not body:
continue
if body.startswith('source:'):
cur['source'] = body[7:].strip()
elif body.startswith('object:'):
cur['object'] = body[7:].strip()
else:
cur['message'].append(body)
return [{'level': b['level'], 'message': ' '.join(b['message']), 'source': b['source'], 'object': b['object']} for b in blocks]
def sample_path(path, regex):
"""A concrete request path for an Ingress path, filling regex groups with a fixed word."""
p = path or '/'
if regex or any(c in p for c in '()$^*+?[]\\'):
p = p.replace('(/|$)', '/').replace('(.*)', 'parity-check').replace('(.+)', 'parity-check').replace('$', '')
p = re.sub(r'\([^)]*\)', 'parity-check', p)
p = re.sub(r'[\^*+?\[\]\\]', '', p)
p = re.sub(r'/+', '/', p)
return p if p.startswith('/') else '/' + p
plan_py: |
import json, os, re, sys
from lib import *
setup_kube()
gc = run(['kubectl', 'get', 'gatewayclass', os.environ['GATEWAY_CLASS'], '-o', 'json'])
if gc.returncode != 0:
sys.exit('GatewayClass %s was not found. Install a Gateway API implementation and its GatewayClass first.' % os.environ['GATEWAY_CLASS'])
accepted = [c for c in json.loads(gc.stdout).get('status', {}).get('conditions', []) if c['type'] == 'Accepted']
if not accepted or accepted[0]['status'] != 'True':
sys.exit('GatewayClass %s is not accepted by its controller.' % os.environ['GATEWAY_CLASS'])
fetch_tool()
items = inventory()
json.dump(items, open('inventory.json', 'w'))
if not items:
out(total=0, clean=0, review=0, blocked=0, inventory_hash='', conflicts=0, dry_run_ok=True, resources=0, blocked_list='', review_list='', clean_list='')
sys.exit(0)
objs, warnings = translate(items)
json.dump({'apiVersion': 'v1', 'kind': 'List', 'items': objs}, open('manifests.json', 'w'))
by_obj = {}
for w in warnings:
by_obj.setdefault(w['object'], []).append(w)
plan = []
for i in items:
k = key(i)
ann = {a: v for a, v in i['metadata'].get('annotations', {}).items() if a.startswith(A) or a == 'kubernetes.io/ingress.class'}
issues = []
for a in sorted(ann):
if a not in CONVERTED and a not in HARMLESS:
issues.append({'annotation': a, 'severity': 'security' if SECURITY.match(a) else 'behavior', 'reason': 'ingress2gateway %s does not convert it' % TOOL_VERSION})
for w in warnings:
text = w['message']
tied = re.search(r'(^|[\s:])' + re.escape(k) + r'$', w['object']) or ('Ingress ' + k + ':') in text
if tied and w['level'] == 'WARN' and 'self-signed' not in text and not any(x['annotation'] and x['annotation'] in text for x in issues):
issues.append({'annotation': '', 'severity': 'tool', 'reason': text[:300]})
hosts = sorted({r.get('host', '') for r in i['spec'].get('rules', [])})
status = 'CLEAN' if not issues else ('BLOCKED' if any(x['severity'] in ('security', 'tool') for x in issues) else 'REVIEW')
plan.append({'key': k, 'hosts': hosts, 'tls': bool(i['spec'].get('tls')), 'annotations': sorted(ann), 'issues': issues, 'status': status})
# the server validates the generated objects and shows which ones already exist
dry = run(['kubectl', 'apply', '--dry-run=server', '-f', 'manifests.json'])
conflicts = []
for o in objs:
group = o['apiVersion'].split('/')[0] if '/' in o['apiVersion'] else ''
r = run(['kubectl', 'get', o['kind'].lower() + ('.' + group if group else ''), o['metadata']['name'], '-n', o['metadata'].get('namespace', 'default'), '-o', 'json'])
if r.returncode == 0:
labels = json.loads(r.stdout)['metadata'].get('labels', {})
if labels.get('migration.kestra.io/name') != os.environ['MIGRATION']:
conflicts.append(o['kind'] + ' ' + o['metadata'].get('namespace', '') + '/' + o['metadata']['name'])
kinds = sorted({o['kind'].lower() + ('.' + o['apiVersion'].split('/')[0] if '/' in o['apiVersion'] else '') for o in objs})
res = [o['kind'] + ' ' + o['metadata'].get('namespace', '') + '/' + o['metadata']['name'] for o in objs]
json.dump({'tool': TOOL_VERSION, 'emitter': os.environ['EMITTER'], 'inventory_hash': inventory_hash(items), 'ingresses': plan, 'resources': res,
'conflicts': conflicts, 'dry_run': {'ok': dry.returncode == 0, 'output': (dry.stdout + dry.stderr)[-1500:]}, 'warnings': warnings}, open('plan.json', 'w'), indent=1)
rows = ['| Ingress | Hosts | Status | Why |', '|---|---|---|---|']
for p in plan:
why = '; '.join((x['annotation'].replace(A, '') + ': ' if x['annotation'] else '') + x['reason'] for x in p['issues']) or 'all annotations convert'
rows.append('| %s | %s | %s | %s |' % (p['key'], ', '.join(p['hosts']), p['status'], why))
open('plan.md', 'w').write('\n'.join(rows) + '\n')
lst = lambda s: ','.join(p['key'] for p in plan if p['status'] == s)
out(total=len(plan), clean=sum(p['status'] == 'CLEAN' for p in plan), review=sum(p['status'] == 'REVIEW' for p in plan), blocked=sum(p['status'] == 'BLOCKED' for p in plan),
inventory_hash=inventory_hash(items), conflicts=len(conflicts), conflict_list='; '.join(conflicts), dry_run_ok=dry.returncode == 0, dry_run_error='' if dry.returncode == 0 else (dry.stderr.strip()[-400:]),
resources=len(res), kinds=','.join(kinds), blocked_list=lst('BLOCKED'), review_list=lst('REVIEW'), clean_list=lst('CLEAN'))
apply_py: |
import json, os, sys, time
from lib import *
setup_kube()
fetch_tool()
items = inventory()
if inventory_hash(items) != os.environ['EXPECT_HASH']:
out(stale=True, applied=0)
sys.exit(0)
skip = {k.strip() for k in os.environ.get('EXCLUDE', '').split(',') if k.strip()}
selected = [i for i in items if key(i) not in skip]
if not selected:
out(stale=False, applied=0, resources=0, ready=False)
sys.exit(0)
objs, warnings = translate(selected)
json.dump({'apiVersion': 'v1', 'kind': 'List', 'items': objs}, open('manifests.json', 'w'))
conflicts = []
for o in objs:
group = o['apiVersion'].split('/')[0] if '/' in o['apiVersion'] else ''
r = run(['kubectl', 'get', o['kind'].lower() + ('.' + group if group else ''), o['metadata']['name'], '-n', o['metadata'].get('namespace', 'default'), '-o', 'json'])
if r.returncode == 0 and json.loads(r.stdout)['metadata'].get('labels', {}).get('migration.kestra.io/name') != os.environ['MIGRATION']:
conflicts.append(o['kind'] + ' ' + o['metadata'].get('namespace', '') + '/' + o['metadata']['name'])
if conflicts:
sys.exit('These objects exist and were not created by this migration, so they are left alone: ' + '; '.join(conflicts))
r = kubectl('apply', '-f', 'manifests.json', check=False)
if r.returncode != 0:
sys.exit('kubectl apply failed: ' + (r.stderr.strip() or r.stdout.strip())[-600:])
print(r.stdout.strip())
gws = [o for o in objs if o['kind'] == 'Gateway']
routes = [o for o in objs if o['kind'].endswith('Route')]
deadline = time.time() + int(os.environ.get('WAIT_SECONDS', '150'))
def cond(status, typ):
return [c for c in status if c.get('type') == typ and c.get('status') == 'True']
while True:
gw_state, bad = {}, []
for g in gws:
j = json.loads(run(['kubectl', 'get', 'gateway', g['metadata']['name'], '-n', g['metadata']['namespace'], '-o', 'json']).stdout or '{}')
st = j.get('status', {})
gw_state[g['metadata']['namespace'] + '/' + g['metadata']['name']] = {'ok': bool(cond(st.get('conditions', []), 'Programmed')) and bool(st.get('addresses')),
'address': (st.get('addresses') or [{}])[0].get('value', ''), 'spec': j.get('spec', {})}
accepted = 0
for ro in routes:
j = json.loads(run(['kubectl', 'get', ro['kind'].lower() + '.gateway.networking.k8s.io', ro['metadata']['name'], '-n', ro['metadata']['namespace'], '-o', 'json']).stdout or '{}')
parents = j.get('status', {}).get('parents', [])
if parents and all(cond(p.get('conditions', []), 'Accepted') and cond(p.get('conditions', []), 'ResolvedRefs') for p in parents):
accepted += 1
else:
bad.append(ro['kind'] + ' ' + ro['metadata']['namespace'] + '/' + ro['metadata']['name'])
if (all(v['ok'] for v in gw_state.values()) and not bad) or time.time() > deadline:
break
time.sleep(5)
new_map = {}
for ro in routes:
for parent in ro['spec'].get('parentRefs', []):
g = gw_state.get(ro['metadata']['namespace'] + '/' + parent['name'])
if not g:
continue
ports = {l['protocol']: l['port'] for l in g['spec'].get('listeners', [])}
for h in ro['spec'].get('hostnames', []):
new_map[h] = {'address': g['address'], 'http': ports.get('HTTP', 80), 'https': ports.get('HTTPS', 443)}
json.dump(new_map, open('new_map.json', 'w'), indent=1)
kinds = sorted({o['kind'].lower() + ('.' + o['apiVersion'].split('/')[0] if '/' in o['apiVersion'] else '') for o in objs})
out(stale=False, applied=len(selected), applied_list=','.join(key(i) for i in selected), resources=len(objs), ready=all(v['ok'] for v in gw_state.values()),
routes_total=len(routes), routes_accepted=accepted, not_accepted='; '.join(bad), gateways='; '.join(k + ' ' + v['address'] for k, v in gw_state.items()), kinds=','.join(kinds))
parity_py: |
import hashlib, json, os, re, sys, time
from lib import *
NOISE = {'date', 'server', 'content-length', 'connection', 'transfer-encoding', 'keep-alive', 'via', 'x-request-id', 'x-envoy-upstream-service-time', 'x-envoy-decorator-operation'}
TIMEOUT = os.environ.get('PROBE_TIMEOUT', '10')
MODE = os.environ.get('MODE', 'compare')
COMPARE_BODY = os.environ.get('COMPARE_BODY', 'true') == 'true'
UNITS = {'': 1, 'k': 1024, 'm': 1024 ** 2, 'g': 1024 ** 3}
def endpoint(spec):
h, p = spec.rsplit(':', 1)
return h, int(p)
def build_probes(items, selected):
probes, skipped = [], []
for i in items:
if key(i) not in selected:
continue
ann = i['metadata'].get('annotations', {})
canary = ann.get(A + 'canary') == 'true'
regex = ann.get(A + 'use-regex') == 'true'
tls_hosts = {h for t in i['spec'].get('tls', []) for h in t.get('hosts', [])}
first = None
for rule in i['spec'].get('rules', []):
host = rule.get('host')
if not host:
skipped.append(key(i) + ' has a rule without a host')
continue
for p in rule.get('http', {}).get('paths', []):
base = sample_path(p.get('path'), regex)
paths = [base]
if p.get('pathType') == 'Prefix' and not regex:
paths.append(base.rstrip('/') + '/parity-check')
for path in paths:
first = first or (host, path)
if canary:
hdr = ann.get(A + 'canary-by-header')
if hdr:
probes.append({'ingress': key(i), 'host': host, 'scheme': 'http', 'method': 'GET', 'path': path, 'headers': {hdr: ann.get(A + 'canary-by-header-value', 'always')}})
else:
skipped.append(key(i) + ' is a weighted canary, which is random and is not probed')
continue
probes.append({'ingress': key(i), 'host': host, 'scheme': 'http', 'method': 'GET', 'path': path, 'headers': {}})
if host in tls_hosts:
probes.append({'ingress': key(i), 'host': host, 'scheme': 'https', 'method': 'GET', 'path': path, 'headers': {}})
if first and ann.get(A + 'proxy-body-size'):
m = re.match(r'^(\d+)([kKmMgG]?)$', ann[A + 'proxy-body-size'])
size = int(m.group(1)) * UNITS[m.group(2).lower()] + 1 if m else 0
if m and size <= 16 * 1024 ** 2 and int(m.group(1)) > 0:
probes.append({'ingress': key(i), 'host': first[0], 'scheme': 'http', 'method': 'POST', 'path': first[1], 'headers': {}, 'body_bytes': size})
else:
skipped.append(key(i) + ' has a proxy-body-size that cannot be probed')
if first and ann.get(A + 'enable-cors') == 'true':
probes.append({'ingress': key(i), 'host': first[0], 'scheme': 'http', 'method': 'OPTIONS', 'path': first[1],
'headers': {'Origin': 'https://parity.example', 'Access-Control-Request-Method': 'GET'}})
for n, p in enumerate(probes):
p['id'] = '%s %s://%s%s%s%s' % (p['method'], p['scheme'], p['host'], p['path'], ' ' + ','.join(k + '=' + v for k, v in p['headers'].items()) if p['headers'] else '',
' body=%d' % p['body_bytes'] if p.get('body_bytes') else '')
return probes, skipped
def fetch(addr, port, probe):
default = 443 if probe['scheme'] == 'https' else 80
cmd = ['curl', '-sS', '-k', '-m', TIMEOUT, '--connect-to', '%s:%d:%s:%d' % (probe['host'], default, addr, port), '-o', 'body.tmp', '-D', 'hdr.tmp', '-w', '%{http_code}',
'-X', probe['method']]
for k, v in probe['headers'].items():
cmd += ['-H', k + ': ' + v]
if probe.get('body_bytes'):
with open('payload.tmp', 'wb') as f:
f.write(b'0' * probe['body_bytes'])
cmd += ['--data-binary', '@payload.tmp']
cmd.append('%s://%s%s' % (probe['scheme'], probe['host'], probe['path']))
for attempt in range(2):
r = run(cmd)
if r.returncode == 0:
break
time.sleep(1)
if r.returncode != 0:
return {'error': (r.stderr.strip() or 'curl exit %d' % r.returncode)[:200]}
raw = open('hdr.tmp', 'rb').read().decode('latin-1')
block = raw.strip().split('\r\n\r\n')[-1]
names, loc = set(), ''
for line in block.splitlines()[1:]:
if ':' in line:
n, v = line.split(':', 1)
names.add(n.strip().lower())
if n.strip().lower() == 'location':
loc = v.strip()
return {'status': int(r.stdout.strip() or 0), 'location': loc, 'body': hashlib.sha256(open('body.tmp', 'rb').read()).hexdigest()[:16], 'headers': sorted(names - NOISE)}
def norm(loc):
m = re.match(r'^(https?://[^/]+)/?$', loc or '')
return m.group(1) if m else (loc or '')
def compare(old, new):
if 'error' in old or 'error' in new:
return 'ERROR', [('old ' + old['error']) if 'error' in old else '', ('new ' + new['error']) if 'error' in new else '']
d = []
if old['status'] != new['status']:
d.append('status %d -> %d' % (old['status'], new['status']))
if norm(old['location']) != norm(new['location']):
d.append('location %s -> %s' % (old['location'] or 'none', new['location'] or 'none'))
if old['status'] == new['status'] and 200 <= old['status'] < 300:
# bodies and headers of redirects and proxy-made errors differ between proxies, so only backend answers are compared
if COMPARE_BODY and old['body'] != new['body']:
d.append('body differs')
lost = sorted(set(old['headers']) - set(new['headers']))
if lost:
d.append('missing headers ' + ','.join(lost))
return ('MATCH' if not d else 'DIFF'), d
setup_kube() if os.environ.get('KUBECONFIG_DATA') else None
new_map = json.load(open('new_map.json'))
override = os.environ.get('NEW_HTTP'), os.environ.get('NEW_HTTPS')
results, baseline, still = [], [], []
if MODE == 'baseline':
probes = json.load(open('baseline.json'))
skipped = []
else:
items = json.load(open('inventory.json'))
probes, skipped = build_probes(items, set(os.environ['APPLIED'].split(',')))
if os.environ.get('OLD_HTTP'):
old_http, old_https = endpoint(os.environ['OLD_HTTP']), endpoint(os.environ.get('OLD_HTTPS') or os.environ['OLD_HTTP'])
else:
svc = json.loads(kubectl('get', 'svc', 'ingress-nginx-controller', '-n', 'ingress-nginx', '-o', 'json').stdout)
lb = (svc.get('status', {}).get('loadBalancer', {}).get('ingress') or [{}])[0]
addr = lb.get('ip') or lb.get('hostname')
if not addr:
sys.exit('The ingress-nginx controller Service has no load balancer address. Set old_http_endpoint (and old_https_endpoint) to host:port.')
old_http, old_https = (addr, 80), (addr, 443)
for p in probes:
n = new_map.get(p['host'])
if override[0] and p['scheme'] == 'http':
na, np_ = endpoint(override[0])
elif override[1] and p['scheme'] == 'https':
na, np_ = endpoint(override[1])
elif n:
na, np_ = n['address'], n['https' if p['scheme'] == 'https' else 'http']
else:
results.append({'id': p['id'], 'ingress': p['ingress'], 'verdict': 'ERROR', 'details': ['no Gateway address for host ' + p['host']]})
continue
oa, op = old_https if p['scheme'] == 'https' else old_http
new = fetch(na, np_, p)
if MODE == 'baseline':
# the Ingresses are gone. The Gateway must answer as it did when the result was accepted. ingress-nginx must no longer answer
verdict, details = compare(p['new'], new)
# only GET requests tell whether a host is still routed: ingress-nginx answers an oversized POST with 413 for any host
now_old = fetch(oa, op, p) if p['method'] == 'GET' else {'status': 0}
waited = time.time() + int(os.environ.get('SETTLE_SECONDS', '30'))
while p['method'] == 'GET' and 'status' in now_old and now_old['status'] == p['old'].get('status') and p['old'].get('status') != 404 and time.time() < waited:
time.sleep(3) # ingress-nginx reloads a few seconds after an Ingress is deleted
now_old = fetch(oa, op, p)
if verdict == 'MATCH' and 'status' in now_old and now_old['status'] == p['old'].get('status') and p['old'].get('status') != 404:
still.append(p['id'])
results.append({'id': p['id'], 'ingress': p['ingress'], 'verdict': verdict, 'details': details, 'old': now_old, 'new': new})
continue
old = fetch(oa, op, p)
verdict, details = compare(old, new)
results.append({'id': p['id'], 'ingress': p['ingress'], 'verdict': verdict, 'details': [x for x in details if x], 'old': old, 'new': new})
baseline.append({**p, 'old': old, 'new': new})
json.dump(results, open('parity.json', 'w'), indent=1)
if MODE != 'baseline':
json.dump(baseline, open('baseline.json', 'w'))
rows = ['| Probe | Result | What differs |', '|---|---|---|']
for r in results:
rows.append('| %s | %s | %s |' % (r['id'], r['verdict'], '; '.join(r['details']) or 'same status, redirect, body and headers'))
open('parity.md', 'w').write('\n'.join(rows) + '\n')
open('parity-diff.md', 'w').write('\n'.join(rows[:2] + [r for r in rows[2:] if '| MATCH |' not in r]) + '\n')
count = lambda v: sum(r['verdict'] == v for r in results)
bad = [r for r in results if r['verdict'] != 'MATCH']
out(total=len(results), match=count('MATCH'), diff=count('DIFF'), error=count('ERROR'), skipped=len(skipped), skipped_list='; '.join(skipped)[:500],
still_served=len(still), still_list='; '.join(still)[:500],
mismatches='; '.join('%s [%s]' % (r['id'], ', '.join(r['details'])) for r in bad)[:1500], mismatch_ingresses=','.join(sorted({r['ingress'] for r in bad if r.get('ingress')})))
recheck_py: |
from lib import *
setup_kube()
out(inventory_hash=inventory_hash(inventory()))
retire_py: |
import json, os, sys
from lib import *
setup_kube()
keys = {k.strip() for k in os.environ['KEYS'].split(',') if k.strip()}
chosen = [i for i in inventory() if key(i) in keys]
missing = sorted(keys - {key(i) for i in chosen})
clean = []
for i in chosen:
for f in ('resourceVersion', 'uid', 'creationTimestamp', 'generation', 'managedFields'):
i['metadata'].pop(f, None)
i.pop('status', None)
clean.append(i)
json.dump({'apiVersion': 'v1', 'kind': 'List', 'items': clean}, open('ingress-backup.json', 'w'), indent=1)
deleted = 0
if os.environ.get('LIVE') == 'true':
for i in chosen:
kubectl('delete', 'ingress', i['metadata']['name'], '-n', i['metadata']['namespace'], '--wait=true')
deleted += 1
out(backed_up=len(chosen), deleted=deleted, missing='; '.join(missing))
rollback_py: |
import json, os, sys
from lib import *
setup_kube()
kinds = [k for k in os.environ['KINDS'].split(',') if k]
sel = 'migration.kestra.io/name=' + os.environ['MIGRATION']
def found():
names = []
for k in kinds:
r = kubectl('get', k, '-A', '-l', sel, '-o', 'json', check=False)
if r.returncode == 0:
names += [(k, i['metadata'].get('namespace', ''), i['metadata']['name']) for i in json.loads(r.stdout)['items']]
return names
before = found()
if os.environ.get('LIVE') == 'true':
for k, ns, n in before:
kubectl('delete', k, n, '-n', ns, '--wait=true')
after = found() if os.environ.get('LIVE') == 'true' else before
out(found=len(before), remaining=len(after) if os.environ.get('LIVE') == 'true' else len(before), objects='; '.join('%s %s/%s' % b for b in before)[:1200])
restore_py: |
from lib import *
setup_kube()
r = kubectl('apply', '-f', 'ingress-backup.json', check=False)
out(restored=r.returncode == 0, detail=(r.stdout + r.stderr).strip()[-400:])
tasks:
- id: label_run
type: io.kestra.plugin.core.execution.Labels
labels:
migration: "{{ inputs.migration_name }}"
mode: "{{ inputs.mode | lower }}"
- id: require_gateway_class
type: io.kestra.plugin.core.execution.Fail
condition: "{{ inputs.mode != 'RETIRE' and inputs.gateway_class == '' }}"
errorMessage: Set gateway_class to the name of an accepted GatewayClass.
- id: read_state
type: io.kestra.plugin.core.kv.Get
key: "ingress-migration-{{ inputs.migration_name }}"
errorOnMissing: false
- id: current
type: io.kestra.plugin.core.output.OutputValues
values:
state: "{{ (outputs.read_state.value ?? {}).state ?? 'NONE' }}"
- id: require_allowed_state
type: io.kestra.plugin.core.execution.Fail
condition: >-
{{ (inputs.mode == 'MIGRATE' and outputs.current.values.state ==
'RETIRED') or
(inputs.mode == 'ROLLBACK' and not (['APPLYING', 'APPLIED', 'VERIFIED'] contains outputs.current.values.state)) or
(inputs.mode == 'RETIRE' and outputs.current.values.state != 'VERIFIED') }}
errorMessage: "The recorded state does not allow this mode. MIGRATE needs a
migration that was not retired, ROLLBACK needs created routes and RETIRE
needs a migration that was accepted (state VERIFIED)."
- id: migrate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.mode == 'MIGRATE' }}"
then:
- id: plan
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
description: Reads the Ingresses, translates them with ingress2gateway,
validates the result on the API server in dry-run mode and lists what
already exists.
inputFiles:
lib.py: "{{ vars.lib_py }}"
plan.py: "{{ vars.plan_py }}"
outputFiles:
- plan.json
- plan.md
- inventory.json
commands:
- python3 plan.py
- id: show_plan
type: io.kestra.plugin.core.log.Log
message: |
{{ outputs.plan.vars.total }} Ingresses of class {{ inputs.ingress_class }}: {{ outputs.plan.vars.clean }} convert cleanly, {{ outputs.plan.vars.review }} need a look, {{ outputs.plan.vars.blocked }} have behavior that Gateway API cannot express.
The translation creates {{ outputs.plan.vars.resources }} objects.
{{ read(outputs.plan.outputFiles['plan.md']) }}
- id: require_ingresses
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.plan.vars.total == 0 }}"
errorMessage: No Ingress of this class was found in the chosen namespaces. Check
ingress_class and namespaces.
- id: require_plan_applicable
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.plan.vars.conflicts > 0 or outputs.plan.vars.dry_run_ok
!= true }}"
errorMessage: "The generated objects cannot be created. Existing objects that
this migration did not create: {{ outputs.plan.vars.conflict_list }}.
API server dry run: {{ outputs.plan.vars.dry_run_error }}"
- id: label_plan
type: io.kestra.plugin.core.execution.Labels
labels:
ingresses: "{{ outputs.plan.vars.total }}"
blocked: "{{ outputs.plan.vars.blocked }}"
outcome: "{{ render(vars.live) == 'true' ? 'awaiting-approval' : 'planned' }}"
- id: plan_only
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) != 'true' }}"
then:
- id: log_plan_only
type: io.kestra.plugin.core.log.Log
message: Dry run. Nothing was created. Set dry_run to false and auto_remediate
to true to create the routes next to the Ingresses.
- id: apply_flow
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) == 'true' }}"
then:
- id: approve_plan
type: io.kestra.plugin.core.flow.Pause
description: The routes are created next to the Ingresses and receive no traffic
until your DNS or load balancer points at the Gateways. Nothing is
deleted.
pauseDuration: "{{ vars.approval_window }}"
behavior: CANCEL
onResume:
- id: decision
type: SELECT
displayName: Decision
isRadio: true
description: Blocked Ingresses carry annotations that Gateway API cannot
express, for example authentication or rate limits. Their
routes would answer differently.
expression: >-
{{ outputs.plan.vars.blocked > 0 ? [ {'label': 'APPLY_CLEAN:
create the routes of ' ~ (outputs.plan.vars.total -
outputs.plan.vars.blocked) ~ ' Ingresses and leave out ' ~
outputs.plan.vars.blocked_list, 'value': 'APPLY_CLEAN'},
{'label': 'APPLY_ALL: create the routes of all ' ~
outputs.plan.vars.total ~ ' Ingresses (the comparison will
show the blocked ones)', 'value': 'APPLY_ALL'}, {'label':
'CANCEL: create nothing', 'value': 'CANCEL'} ] : [ {'label':
'APPLY_ALL: create the routes of all ' ~
outputs.plan.vars.total ~ ' Ingresses', 'value': 'APPLY_ALL'},
{'label': 'CANCEL: create nothing', 'value': 'CANCEL'} ] }}
- id: note
type: STRING
displayName: Note
description: Why you decided this, for example a change ticket. Kept in the
execution.
required: false
- id: cancelled
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_plan.onResume.decision == 'CANCEL' }}"
then:
- id: label_cancelled
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: cancelled
- id: stop_cancelled
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: exclusions
type: io.kestra.plugin.core.output.OutputValues
values:
exclude: "{{ outputs.approve_plan.onResume.decision == 'APPLY_CLEAN' ?
outputs.plan.vars.blocked_list : '' }}"
- id: applying_state
type: io.kestra.plugin.core.kv.Set
description: Written before the first change, so a failure leaves a record that
ROLLBACK can use.
key: "ingress-migration-{{ inputs.migration_name }}"
kvType: JSON
value: >-
{{ {'state': 'APPLYING', 'inventory_hash':
outputs.plan.vars.inventory_hash, 'gateway_class':
inputs.gateway_class, 'emitter': inputs.emitter, 'kinds':
outputs.plan.vars.kinds | split(',')} | toJson }}
- id: apply
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
description: Reads the Ingresses again, stops if they changed since the plan,
translates the approved ones, applies them and waits for every
Gateway to be programmed and every route to be accepted.
inputFiles:
lib.py: "{{ vars.lib_py }}"
apply.py: "{{ vars.apply_py }}"
outputFiles:
- new_map.json
- manifests.json
commands:
- EXPECT_HASH="{{ outputs.plan.vars.inventory_hash }}" EXCLUDE="{{
outputs.exclusions.values.exclude }}" WAIT_SECONDS="{{
vars.programmed_wait }}" python3 apply.py
- id: require_fresh
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.apply.vars.stale == true }}"
errorMessage: The Ingresses changed while the plan waited for approval, so
nothing was created. Run MIGRATE again.
- id: require_ready
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.apply.vars.ready != true or
outputs.apply.vars.routes_accepted !=
outputs.apply.vars.routes_total }}"
errorMessage: "A Gateway is not programmed or a route is not accepted: {{
outputs.apply.vars.not_accepted }}. The created objects stay in
place. Fix the cause and run MIGRATE again. Or run ROLLBACK."
- id: applied_state
type: io.kestra.plugin.core.kv.Set
key: "ingress-migration-{{ inputs.migration_name }}"
kvType: JSON
value: >-
{{ {'state': 'APPLIED', 'inventory_hash':
outputs.plan.vars.inventory_hash, 'gateway_class':
inputs.gateway_class, 'emitter': inputs.emitter, 'kinds':
outputs.apply.vars.kinds | split(','), 'applied':
outputs.apply.vars.applied_list | split(','), 'gateways':
outputs.apply.vars.gateways} | toJson }}
- id: parity
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
description: Sends the same requests to ingress-nginx and to the new Gateways
and compares status, redirect, body and headers.
inputFiles:
lib.py: "{{ vars.lib_py }}"
parity.py: "{{ vars.parity_py }}"
inventory.json: "{{ outputs.plan.outputFiles['inventory.json'] }}"
new_map.json: "{{ outputs.apply.outputFiles['new_map.json'] }}"
outputFiles:
- parity.json
- parity.md
- parity-diff.md
- baseline.json
commands:
- APPLIED="{{ outputs.apply.vars.applied_list }}" OLD_HTTP="{{
inputs.old_http_endpoint }}" OLD_HTTPS="{{
inputs.old_https_endpoint }}" NEW_HTTP="{{
inputs.new_http_endpoint }}" NEW_HTTPS="{{
inputs.new_https_endpoint }}" COMPARE_BODY="{{
inputs.compare_body }}" MODE="compare" python3 parity.py
- id: label_parity
type: io.kestra.plugin.core.execution.Labels
labels:
probes: "{{ outputs.parity.vars.total }}"
differences: "{{ outputs.parity.vars.diff + outputs.parity.vars.error }}"
outcome: awaiting-review
- id: show_parity
type: io.kestra.plugin.core.log.Log
level: "{{ outputs.parity.vars.diff + outputs.parity.vars.error > 0 ? 'WARN' :
'INFO' }}"
message: |
{{ outputs.parity.vars.match }} of {{ outputs.parity.vars.total }} requests got the same answer from the Gateway as from ingress-nginx.{{ outputs.parity.vars.skipped > 0 ? ' Not probed: ' ~ outputs.parity.vars.skipped_list : '' }}
{{ outputs.parity.vars.diff + outputs.parity.vars.error > 0 ? read(outputs.parity.outputFiles['parity-diff.md']) : 'No differences.' }}
- id: approve_result
type: io.kestra.plugin.core.flow.Pause
description: Read the comparison in the show_parity log. Accepting records the
result and the answers of ingress-nginx as the baseline for
RETIRE. Nothing is deleted here.
pauseDuration: "{{ vars.approval_window }}"
behavior: CANCEL
onResume:
- id: decision
type: SELECT
displayName: Decision
isRadio: true
expression: >-
{{ outputs.parity.vars.diff + outputs.parity.vars.error == 0 ?
[ {'label': 'ACCEPT: all ' ~ outputs.parity.vars.total ~ '
requests matched, record the baseline', 'value': 'ACCEPT'},
{'label': 'KEEP: leave the routes in place while you fix the
Ingresses', 'value': 'KEEP'}, {'label': 'ROLLBACK: delete the
routes this migration created', 'value': 'ROLLBACK'} ] : [
{'label': 'ACCEPT_WITH_EXCEPTIONS: accept ' ~
(outputs.parity.vars.diff + outputs.parity.vars.error) ~ '
differences, described below', 'value':
'ACCEPT_WITH_EXCEPTIONS'}, {'label': 'KEEP: leave the routes
in place while you fix the Ingresses', 'value': 'KEEP'},
{'label': 'ROLLBACK: delete the routes this migration
created', 'value': 'ROLLBACK'} ] }}
- id: exceptions
type: STRING
displayName: Accepted differences
description: Required for ACCEPT_WITH_EXCEPTIONS. Say which differences you
accept and why.
required: false
- id: accept
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_result.onResume.decision == 'ACCEPT' or
outputs.approve_result.onResume.decision ==
'ACCEPT_WITH_EXCEPTIONS' }}"
then:
- id: require_exceptions_text
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.approve_result.onResume.decision ==
'ACCEPT_WITH_EXCEPTIONS' and
(outputs.approve_result.onResume.exceptions ?? '') | trim ==
'' }}"
errorMessage: ACCEPT_WITH_EXCEPTIONS needs a description of the accepted
differences. Resume again with one.
- id: recheck
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
description: The approval is a snapshot. Reads the Ingresses again before
recording it.
inputFiles:
lib.py: "{{ vars.lib_py }}"
recheck.py: "{{ vars.recheck_py }}"
commands:
- python3 recheck.py
- id: require_unchanged
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.recheck.vars.inventory_hash !=
outputs.plan.vars.inventory_hash }}"
errorMessage: The Ingresses changed while the result was under review. Nothing
was recorded. Run MIGRATE again.
- id: verified_state
type: io.kestra.plugin.core.kv.Set
key: "ingress-migration-{{ inputs.migration_name }}"
kvType: JSON
value: >-
{{ {'state': 'VERIFIED', 'inventory_hash':
outputs.plan.vars.inventory_hash, 'gateway_class':
inputs.gateway_class, 'emitter': inputs.emitter, 'kinds':
outputs.apply.vars.kinds | split(','), 'applied':
outputs.apply.vars.applied_list | split(','), 'gateways':
outputs.apply.vars.gateways, 'new_map':
fromJson(read(outputs.apply.outputFiles['new_map.json'])),
'probes': outputs.parity.vars.total, 'differences':
outputs.parity.vars.diff + outputs.parity.vars.error,
'accepted_exceptions':
(outputs.approve_result.onResume.exceptions ?? ''),
'approved_note': (outputs.approve_plan.onResume.note ?? '')} |
toJson }}
- id: baseline_state
type: io.kestra.plugin.core.kv.Set
key: "ingress-migration-{{ inputs.migration_name }}-baseline"
kvType: JSON
value: "{{ read(outputs.parity.outputFiles['baseline.json']) }}"
- id: read_back
type: io.kestra.plugin.core.kv.Get
key: "ingress-migration-{{ inputs.migration_name }}"
- id: verify_recorded
type: io.kestra.plugin.core.execution.Assert
errorMessage: The accepted state was not recorded.
conditions:
- "{{ outputs.read_back.value.state == 'VERIFIED' }}"
- "{{ outputs.read_back.value.applied | length ==
outputs.apply.vars.applied }}"
- id: label_verified
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: "{{ outputs.approve_result.onResume.decision == 'ACCEPT' ? 'verified' :
'verified-with-exceptions' }}"
- id: next_steps
type: io.kestra.plugin.core.log.Log
message: |
Accepted. Point DNS or your load balancer for these hosts at the Gateway addresses: {{ outputs.apply.vars.gateways }}.
After traffic moved and the old controller is idle, run this flow with mode RETIRE.
- id: keep
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_result.onResume.decision == 'KEEP' }}"
then:
- id: label_kept
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: kept-for-fixes
- id: log_kept
type: io.kestra.plugin.core.log.Log
message: The routes stay in place and the state is APPLIED. Fix the Ingresses or
the Gateway configuration, then run MIGRATE again. It updates
the same objects.
- id: stop_kept
type: io.kestra.plugin.core.execution.Exit
state: WARNING
- id: rollback_created
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_result.onResume.decision == 'ROLLBACK' }}"
then:
- id: delete_created
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
rollback.py: "{{ vars.rollback_py }}"
commands:
- KINDS="{{ outputs.apply.vars.kinds }}" LIVE="true" python3
rollback.py
- id: verify_deleted
type: io.kestra.plugin.core.execution.Assert
errorMessage: Objects created by this migration are still present.
conditions:
- "{{ outputs.delete_created.vars.remaining == 0 }}"
- id: forget_state
type: io.kestra.plugin.core.kv.Delete
key: "ingress-migration-{{ inputs.migration_name }}"
- id: label_rolled_back
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: rolled-back
- id: rollback
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.mode == 'ROLLBACK' }}"
then:
- id: approve_rollback
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) == 'true' }}"
then:
- id: confirm_rollback
type: io.kestra.plugin.core.flow.Pause
description: Deletes every Gateway API object that carries this migration's
label. The Ingresses are not touched.
pauseDuration: "{{ vars.approval_window }}"
behavior: CANCEL
onResume:
- id: decision
type: SELECT
displayName: Decision
isRadio: true
expression: >-
{{ [ {'label': 'ROLLBACK: delete the objects of migration ' ~
inputs.migration_name, 'value': 'ROLLBACK'}, {'label':
'CANCEL: change nothing', 'value': 'CANCEL'} ] }}
- id: rollback_cancelled
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) == 'true' and
outputs.confirm_rollback.onResume.decision == 'CANCEL' }}"
then:
- id: label_rollback_cancelled
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: cancelled
- id: stop_rollback_cancelled
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: rollback_objects
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
rollback.py: "{{ vars.rollback_py }}"
commands:
- KINDS="{{ (outputs.read_state.value ?? {}).kinds | join(',') }}"
LIVE="{{ render(vars.live) }}" python3 rollback.py
- id: verify_rollback
type: io.kestra.plugin.core.execution.Assert
errorMessage: Objects created by this migration are still present.
conditions:
- "{{ render(vars.live) != 'true' or
outputs.rollback_objects.vars.remaining == 0 }}"
- id: forget_rolled_back
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) == 'true' }}"
then:
- id: delete_state
type: io.kestra.plugin.core.kv.Delete
key: "ingress-migration-{{ inputs.migration_name }}"
- id: delete_baseline
type: io.kestra.plugin.core.kv.Delete
key: "ingress-migration-{{ inputs.migration_name }}-baseline"
- id: label_rollback
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: "{{ render(vars.live) == 'true' ? 'rolled-back' : 'rollback-previewed'
}}"
- id: retire
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.mode == 'RETIRE' }}"
then:
- id: read_baseline
type: io.kestra.plugin.core.kv.Get
key: "ingress-migration-{{ inputs.migration_name }}-baseline"
- id: show_retire
type: io.kestra.plugin.core.log.Log
message: "Retiring deletes {{ outputs.read_state.value.applied | length }}
Ingresses: {{ outputs.read_state.value.applied | join(', ') }}. Their
routes were accepted with {{ outputs.read_state.value.differences }}
known differences. A backup of the Ingresses is kept with this
execution."
- id: retire_preview
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) != 'true' }}"
then:
- id: label_retire_preview
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: retire-previewed
- id: retire_flow
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) == 'true' }}"
then:
- id: approve_retire
type: io.kestra.plugin.core.flow.Pause
description: Deletes the old Ingresses. After the deletion the flow asks the
Gateways the same questions again and restores the Ingresses from
the backup if an answer changed.
pauseDuration: "{{ vars.approval_window }}"
behavior: CANCEL
onResume:
- id: decision
type: SELECT
displayName: Decision
isRadio: true
expression: >-
{{ [ {'label': 'RETIRE: delete ' ~
(outputs.read_state.value.applied | length) ~ ' Ingresses',
'value': 'RETIRE'}, {'label': 'CANCEL: change nothing',
'value': 'CANCEL'} ] }}
- id: dns_switched
type: BOOL
displayName: Traffic already moved
defaults: false
description: Confirm that DNS or the load balancer already sends the traffic of
these hosts to the Gateway addresses.
- id: note
type: STRING
displayName: Note
required: false
- id: retire_cancelled
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_retire.onResume.decision == 'CANCEL' }}"
then:
- id: label_retire_cancelled
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: cancelled
- id: stop_retire_cancelled
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: require_traffic_moved
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.approve_retire.onResume.dns_switched != true }}"
errorMessage: Confirm that the traffic moved to the Gateways before the
Ingresses are deleted.
- id: delete_ingresses
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
retire.py: "{{ vars.retire_py }}"
outputFiles:
- ingress-backup.json
commands:
- KEYS="{{ outputs.read_state.value.applied | join(',') }}"
LIVE="true" python3 retire.py
- id: label_retired_started
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: ingresses-deleted
- id: check_gateways
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
description: Asks the Gateways the questions again and compares with the answers
recorded when the result was accepted. Also asks ingress-nginx,
which must no longer serve these hosts.
inputFiles:
lib.py: "{{ vars.lib_py }}"
parity.py: "{{ vars.parity_py }}"
baseline.json: "{{ outputs.read_baseline.value | toJson }}"
new_map.json: "{{ outputs.read_state.value.new_map | toJson }}"
outputFiles:
- parity-diff.md
commands:
- OLD_HTTP="{{ inputs.old_http_endpoint }}" OLD_HTTPS="{{
inputs.old_https_endpoint }}" NEW_HTTP="{{
inputs.new_http_endpoint }}" NEW_HTTPS="{{
inputs.new_https_endpoint }}" COMPARE_BODY="{{
inputs.compare_body }}" MODE="baseline" python3 parity.py
- id: restore_needed
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.check_gateways.vars.diff +
outputs.check_gateways.vars.error > 0 }}"
then:
- id: restore_ingresses
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
KUBECONFIG_DATA: "{{ secret('K8S_KUBECONFIG') }}"
INGRESS_CLASS: "{{ inputs.ingress_class }}"
NAMESPACES: "{{ inputs.namespaces }}"
GATEWAY_CLASS: "{{ inputs.gateway_class }}"
EMITTER: "{{ inputs.emitter }}"
MIGRATION: "{{ inputs.migration_name }}"
TOOL_URL: "{{ vars.tool_url }}"
TOOL_SHA256: "{{ vars.tool_sha256 }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
restore.py: "{{ vars.restore_py }}"
ingress-backup.json: "{{
outputs.delete_ingresses.outputFiles['ingress-backup.json']
}}"
commands:
- python3 restore.py
- id: label_restored
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: ingresses-restored
- id: fail_restored
type: io.kestra.plugin.core.execution.Fail
errorMessage: "The Gateways answered differently once the Ingresses were gone,
so the Ingresses were restored from the backup: {{
outputs.check_gateways.vars.mismatches }}"
- id: require_old_gone
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.check_gateways.vars.still_served > 0 }}"
errorMessage: "ingress-nginx still answers for hosts whose Ingresses were
deleted: {{ outputs.check_gateways.vars.still_list }}. Another
Ingress may serve them."
- id: retired_state
type: io.kestra.plugin.core.kv.Set
key: "ingress-migration-{{ inputs.migration_name }}"
kvType: JSON
value: >-
{{ {'state': 'RETIRED', 'retired':
outputs.read_state.value.applied, 'gateway_class':
outputs.read_state.value.gateway_class, 'checked_requests':
outputs.check_gateways.vars.total, 'note':
(outputs.approve_retire.onResume.note ?? '')} | toJson }}
- id: label_retired
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: retired
errors:
- id: label_failed
type: io.kestra.plugin.core.execution.Labels
description: Marks the run as failed. An outcome label set by an earlier step,
for example ingresses-restored, stays.
labels:
failed: "true"
- id: alert_migration_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'Ingress migration ' ~ inputs.migration_name ~ ' (' ~
inputs.mode ~ ') failed. Execution ' ~ execution.id ~ '. Created Gateway
API objects are never deleted automatically: read the log, then run
MIGRATE again or ROLLBACK.'} | toJson }}
triggers:
- id: weekly_plan
type: io.kestra.plugin.core.trigger.Schedule
disabled: true
cron: "0 7 * * 1"
inputs:
mode: MIGRATE
dry_run: true
auto_remediate: false
ingress-nginx is retired and ingress2gateway translates most of its annotations. It prints the ones it cannot convert as warnings on stderr and still writes the routes. A dropped auth-url or a rewrite with capture groups then becomes a route that answers differently. This flow creates the routes next to the Ingresses. It sends the same requests to both controllers and shows every difference before anyone approves.
plan reads the Ingresses of one class, translates them with a pinned and checksummed ingress2gateway, marks Ingresses with unconverted annotations as BLOCKED, validates the objects with a server side dry run. It refuses to touch objects this migration did not create. dry_run ends here.approve_plan (Pause) offers APPLY_CLEAN, APPLY_ALL or CANCEL, with the blocked Ingresses named.apply re-reads the Ingresses and stops if they changed, creates labeled Gateways, routes and policies. It waits until every Gateway is programmed and every route accepted. The KV key ingress-migration-<name> records the state.parity sends the same requests to ingress-nginx and to the Gateway: each path, a sub path, the canary header, an oversized POST for proxy-body-size, a CORS preflight and HTTPS for TLS hosts. It compares status and redirect target. For 2xx answers it also compares the body and the response headers.approve_result (Pause) offers ACCEPT, ACCEPT_WITH_EXCEPTIONS (a description is required), KEEP or ROLLBACK. Accepting re-reads the Ingresses first. It stores the answers as the baseline.auth-url annotation turned a 401 into a 200. The HSTS header was missing.migration.kestra.io/name.outcome, blocked, probes and differences.Platform teams that run ingress-nginx and must move to a Gateway API controller.
Pause with onResume inputs builds the decision form from the plan. The KV store makes every mode safe to run again. The restore step keeps a failed retire from leaving the old Ingresses deleted.
26 runs on each of Kestra 2.0.6 and 2.0.5 with ingress-nginx 1.15.1, Envoy Gateway 1.9.3, Gateway API 1.6.3 and ingress2gateway 1.2.0 on Kubernetes 1.34. Covered: an Ingress changed during each approval, a missing GatewayClass, read only credentials, rollback and a retire that restored the Ingresses.
A cluster with Gateway API CRDs and an accepted GatewayClass. Docker workers must reach the API server and both load balancers. Permissions: read Ingresses, Services and GatewayClasses. Manage Gateways and HTTPRoutes, plus Envoy policies with the envoy-gateway emitter. Delete Ingresses for RETIRE.
K8S_KUBECONFIG holds the kubeconfig of the cluster. The tasks read it directly, so it is never shown in the execution form. SLACK_WEBHOOK_URL is used for the failure alert.
gateway_class is required. emitter is envoy-gateway or standard. old_http_endpoint and old_https_endpoint are needed when the ingress-nginx Service has no load balancer address. dry_run defaults to true and auto_remediate to false.
dry_run false and auto_remediate true, choose APPLY_CLEAN and read the show_parity log.Only Envoy Gateway was tested. Probes come from one worker address. Weighted canaries, gRPC routes and TCP routes are not probed. Change the variables tool_url and tool_sha256 to pin or mirror another ingress2gateway release.
This blueprint was created by zkasuran.
Validate API status codes and response markers on a schedule, save evidence, and alert only on failures.
Monitor third-party OpenAPI specifications for consumer-impacting contract changes and govern accepted revisions with persistent PASS/WARN/BLOCK decisions.
Observe API quota headers, preserve measurements, and alert before exhaustion.
Audit Apache APISIX gateway health, detect canary route drift or disabled upstreams, and dispatch Slack alerts.
Probe three endpoints in parallel every 30 minutes and post one Slack alert naming each site that did not answer HTTP 200.
Continuous cluster supervision auditing, coordinator and DBServer health probing, and Slack incident alerting for ArangoDB.
