k3d admission
时间: 2024-06-13 13:07:06 浏览: 102
基于Kubernetes的k3d集群可以使用admission webhook来验证和修改资源对象。下面是一个简单的k3d admission webhook的演示:
1. 创建一个名为`validating-webhook.yaml`的文件,内容如下:
```yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: example.k3d.local
webhooks:
- name: example.k3d.local
clientConfig:
service:
name: example.k3d.local
namespace: default
path: "/validate"
caBundle: ""
rules:
- apiGroups:
- ""
- "extensions"
- "apps"
apiVersions:
- "v1"
- "v1beta1"
- "v1beta2"
operations:
- CREATE
- UPDATE
resources:
- "pods"
- "deployments"
- "replicasets"
failurePolicy: Fail
sideEffects: None
admissionReviewVersions:
- v1
- v1beta1
```
这个文件定义了一个名为`example.k3d.local`的验证webhook,它将验证和修改`pods`、`deployments`和`replicasets`资源对象。
2. 创建一个名为`deployment.yaml`的文件,内容如下:
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
```
这个文件定义了一个名为`nginx-deployment`的Deployment对象,它将创建3个Nginx容器。
3. 创建一个名为`Dockerfile`的文件,内容如下:
```dockerfile
FROM python:3.7-alpine
RUN pip install flask
COPY app.py /app.py
CMD ["python", "/app.py"]
```
这个文件定义了一个基于Python 3.7的Docker镜像,它将安装Flask并运行一个名为`app.py`的应用程序。
4. 创建一个名为`app.py`的文件,内容如下:
```python
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
@app.route('/validate', methods=['POST'])
def validate():
admission_review = request.get_json()
resource = admission_review['request']['object']
if resource['kind'] == 'Deployment':
if resource['metadata']['name'] != 'nginx-deployment':
return jsonify({'response': {'allowed': False, 'status': {'reason': 'Name is not nginx-deployment'}}})
return jsonify({'response': {'allowed': True}})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
```
这个文件定义了一个Flask应用程序,它将验证`Deployment`对象的名称是否为`nginx-deployment`。
5. 构建Docker镜像:
```shell
docker build -t k3d-admission .
```
6. 创建一个名为`k3d-cluster.yaml`的文件,内容如下:
```yaml
apiVersion: k3d.io/v1alpha2
kind: Cluster
nodes: 1
name: k3d-admission
ports:
- port: 8080:8080
protocol: TCP
image: rancher/k3s:v1.20.4-k3s1
wait: true
```
这个文件定义了一个名为`k3d-admission`的k3d集群,它将暴露端口8080以便验证webhook服务可以访问。
7. 创建k3d集群:
```shell
k3d cluster create -f k3d-cluster.yaml
```
8. 部署验证webhook服务:
```shell
kubectl apply -f validating-webhook.yaml
kubectl apply -f deployment.yaml
```
9. 验证验证webhook服务是否工作:
```shell
kubectl create deployment nginx --image=nginx:1.14.2
```
这个命令将创建一个名为`nginx`的Deployment对象,但是由于它的名称不是`nginx-deployment`,验证webhook服务将拒绝它的创建。
阅读全文