用webhook+flask完成一个插件,在k8s集群中,master部署一个pod,调度到了node1上,node1弹出提示让用户选择y/n,来继续调度或者拒绝并停止调度,写出flask和webhook.yaml
时间: 2024-10-16 17:09:57 浏览: 22
打造jenkins+docker+nodejs项目的自动部署环境(webhook)
要在Kubernetes(K8s)集群中使用Webhook和Flask实现这样一个功能,首先你需要创建一个简单的Flask应用来处理Webhook请求,并在`webhook.yaml`文件中配置Webhook服务。以下是基本步骤:
### 1. 创建Flask应用
```python
# app.py
from flask import Flask, request, jsonify
import os
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def handle_webhook():
data = request.get_json()
# 检查数据来自Kubernetes并处理调度请求
if 'action' in data and 'object' in data and data['kind'] == 'Pod':
pod_name = data['object']['metadata']['name']
node_name = data['object']['spec']['nodeName']
if data['object']['status']['phase'] == 'Pending' and 'containerStatuses' in data['object']['status']:
user_choice = input(f"Node {node_name} received Pod '{pod_name}'. Do you want to continue (y/n)? ")
if user_choice.lower() == 'n':
response_data = {
"apiVersion": "v1",
"response": {
"status": "Rejected",
"message": f"User rejected scheduling for Pod '{pod_name}' on Node '{node_name}'"
}
}
return jsonify(response_data), 200
else:
response_data = {
"apiVersion": "v1",
"response": {
"status": "Approved",
"message": f"Scheduling of Pod '{pod_name}' on Node '{node_name}' approved by user."
}
}
return jsonify(response_data), 200
else:
pass # 如果Pod已经运行或失败,不做处理
return 'Invalid or unexpected request.', 400
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('FLASK_RUN_PORT', 5000)), debug=True)
```
### 2. 配置Webhook.yaml
```yaml
# webhook.yaml
apiVersion: admissionregistration.k8s.io/v1beta1
kind: MutatingWebhookConfiguration
metadata:
name: my-webhook-config
webhooks:
- name: my-webhook.example.com
clientConfig:
service:
name: my-flask-service
namespace: default
port: 5000
rules:
- apiGroups: ["*"]
apiVersions: ["*"]
operations: [ "CREATE", "UPDATE" ]
resources: ["pods"]
admissionReviewVersions: ["v1"]
---
apiVersion: v1
kind: Service
metadata:
name: my-flask-service
spec:
selector:
app: flask-app
ports:
- name: webhook
protocol: TCP
port: 5000
targetPort: 5000
type: ClusterIP
```
在这个YAML配置中,我们定义了一个MutatingWebhook,它监听K8s对Pod资源的创建和更新操作。当新的Pod被创建或已有的Pod被修改时,Webhook会将请求转发到Flask应用。Flask应用根据请求内容做出判断并返回相应的批准或拒绝决策。
请确保你的K8s环境已经安装并且能够访问网络,然后使用kubectl创建这两个资源:
```shell
kubectl apply -f webhook.yaml
```
现在,每当有新Pod调度到Node1时,Flask应用就会提示用户是否继续调度。如果用户选择拒绝,Pod的创建会被阻止。
阅读全文