1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| apiVersion: v1 kind: ConfigMap metadata: name: webhook-config data: webhook.py: | from flask import Flask, request, jsonify import base64 import json
app = Flask(__name__)
@app.route('/validate', methods=['POST']) def validate(): admission_request = request.get_json()
obj = admission_request.get('request', {}).get('object', {})
if obj.get('kind') == 'Pod': name = obj.get('metadata', {}).get('name', '') if 'bad' in name: return jsonify({ 'apiVersion': 'admission.k8s.io/v1', 'kind': 'AdmissionResponse', 'response': { 'uid': admission_request['request']['uid'], 'allowed': False, 'status': { 'code': 403, 'message': 'Pod名称不能包含"bad"' } } })
return jsonify({ 'apiVersion': 'admission.k8s.io/v1', 'kind': 'AdmissionResponse', 'response': { 'uid': admission_request['request']['uid'], 'allowed': True } })
if __name__ == '__main__': app.run(host='0.0.0.0', port=8443, ssl_context='adhoc')
--- apiVersion: apps/v1 kind: Deployment metadata: name: validation-webhook spec: replicas: 1 selector: matchLabels: app: validation-webhook template: metadata: labels: app: validation-webhook spec: containers: - name: webhook image: python:3.9-slim command: ["python", "-c"] args: - | import subprocess subprocess.run(["pip", "install", "flask", "pyopenssl"]) exec(open('/config/webhook.py').read()) ports: - containerPort: 8443 volumeMounts: - name: config mountPath: /config volumes: - name: config configMap: name: webhook-config
|